Add openxr_preview headers and related samples (#35)

* Add openxr_preview headers and related samples for hand tracking, anchors and unbounded spaces.

* delete a staled file

* Move action context into XrUtility
This commit is contained in:
yl-msft 2020-02-22 11:33:18 -08:00 коммит произвёл GitHub
Родитель 8049c3267b
Коммит 0a26f96731
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
201 изменённых файлов: 104867 добавлений и 170 удалений

Просмотреть файл

@ -14,6 +14,7 @@ ConstructorInitializerAllOnOneLineOrOnePerLine: 'false'
IndentCaseLabels: 'false'
IndentWidth: '4'
IndentWrappedFunctionNames: 'false'
ForEachMacros: ['TEST_CLASS']
KeepEmptyLinesAtTheStartOfBlocks: 'false'
MaxEmptyLinesToKeep: '1'
NamespaceIndentation: All

1
.gitattributes поставляемый
Просмотреть файл

@ -20,3 +20,4 @@
*.exe filter=lfs diff=lfs merge=lfs -text
*.pdf filter=lfs diff=lfs merge=lfs -text
*.msi filter=lfs diff=lfs merge=lfs -text
*.mui filter=lfs diff=lfs merge=lfs -text

8
.gitignore поставляемый
Просмотреть файл

@ -19,6 +19,8 @@
[Rr]eleases/
x64/
x86/
ARM/
ARM64/
bld/
[Bb]in/
[Oo]bj/
@ -26,6 +28,7 @@ bld/
# Visual Studio 2015/2017 cache/options directory
.vs/
.vscode/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
@ -84,6 +87,8 @@ StyleCopReport.xml
*.pidb
*.svclog
*.scc
*.idb
*.tlog
# Chutzpah Test files
_Chutzpah*
@ -203,6 +208,7 @@ BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.msix
# Visual Studio cache files
# files ending in .cache can be ignored
@ -326,4 +332,4 @@ ASALocalRun/
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
.mfractor/

Просмотреть файл

@ -5,14 +5,15 @@ VisualStudioVersion = 15.0.28307.421
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BasicXrApp_uwp", "samples\BasicXrApp\BasicXrApp_uwp.vcxproj", "{1B09B21C-2D7A-4278-81C8-84A47D5834A7}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BasicXrApp_win32", "samples\BasicXrApp\BasicXrApp_win32.vcxproj", "{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "xrUtility", "xrUtility", "{D71728CE-842F-4FA7-94AE-01AEA60BC45A}"
ProjectSection(SolutionItems) = preProject
samples\XrUtility\XrError.h = samples\XrUtility\XrError.h
samples\XrUtility\XrExtensions.h = samples\XrUtility\XrExtensions.h
samples\XrUtility\XrHandle.h = samples\XrUtility\XrHandle.h
samples\XrUtility\XrMath.h = samples\XrUtility\XrMath.h
samples\XrUtility\XrString.h = samples\XrUtility\XrString.h
samples\XrUtility\XrToString.h = samples\XrUtility\XrToString.h
shared\XrUtility\XrError.h = shared\XrUtility\XrError.h
shared\XrUtility\XrExtensions.h = shared\XrUtility\XrExtensions.h
shared\XrUtility\XrHandle.h = shared\XrUtility\XrHandle.h
shared\XrUtility\XrMath.h = shared\XrUtility\XrMath.h
shared\XrUtility\XrString.h = shared\XrUtility\XrString.h
EndProjectSection
EndProject
Global
@ -51,6 +52,18 @@ Global
{1B09B21C-2D7A-4278-81C8-84A47D5834A7}.Release|x86.ActiveCfg = Release|Win32
{1B09B21C-2D7A-4278-81C8-84A47D5834A7}.Release|x86.Build.0 = Release|Win32
{1B09B21C-2D7A-4278-81C8-84A47D5834A7}.Release|x86.Deploy.0 = Release|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|ARM.ActiveCfg = Debug|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|ARM64.ActiveCfg = Debug|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|x64.ActiveCfg = Debug|x64
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|x64.Build.0 = Debug|x64
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|x86.ActiveCfg = Debug|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|x86.Build.0 = Debug|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|ARM.ActiveCfg = Release|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|ARM64.ActiveCfg = Release|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|x64.ActiveCfg = Release|x64
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|x64.Build.0 = Release|x64
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|x86.ActiveCfg = Release|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

Просмотреть файл

@ -1,41 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.421
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "xrUtility", "xrUtility", "{D71728CE-842F-4FA7-94AE-01AEA60BC45A}"
ProjectSection(SolutionItems) = preProject
samples\XrUtility\XrError.h = samples\XrUtility\XrError.h
samples\XrUtility\XrExtensions.h = samples\XrUtility\XrExtensions.h
samples\XrUtility\XrHandle.h = samples\XrUtility\XrHandle.h
samples\XrUtility\XrMath.h = samples\XrUtility\XrMath.h
samples\XrUtility\XrString.h = samples\XrUtility\XrString.h
samples\XrUtility\XrToString.h = samples\XrUtility\XrToString.h
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BasicXrApp_win32", "samples\BasicXrApp\BasicXrApp_win32.vcxproj", "{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|x64.ActiveCfg = Debug|x64
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|x64.Build.0 = Debug|x64
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|x86.ActiveCfg = Debug|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Debug|x86.Build.0 = Debug|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|x64.ActiveCfg = Release|x64
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|x64.Build.0 = Release|x64
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|x86.ActiveCfg = Release|Win32
{A75A907B-8952-4ED2-BC2D-A68F09CEBD83}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3877BD70-2592-47B5-B2F6-D20DBF593692}
EndGlobalSection
EndGlobal

Просмотреть файл

@ -8,5 +8,8 @@
<OutDir Condition="$(OutDir)==''">$(SolutionDir)bin\$(Configuration)\$(Platform)\</OutDir>
<IntermediateOutputPath Condition="$(IntermediateOutputPath)==''">$(SolutionDir)obj\$(Configuration)\$(Platform)\$(MSBuildProjectName)\</IntermediateOutputPath>
<GeneratedFilesDir Condition="$(GeneratedFilesDir)==''">$(SolutionDir)obj\$(Configuration)\$(Platform)\$(MSBuildProjectName)\GeneratedFiles</GeneratedFilesDir>
<SharedPath>$(MSBuildThisFileDirectory)shared</SharedPath>
<OpenXrSdkPath>$(MSBuildThisFileDirectory)openxr_preview</OpenXrSdkPath>
</PropertyGroup>
</Project>

9
Directory.Build.targets Normal file
Просмотреть файл

@ -0,0 +1,9 @@
<Project>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(OpenXrSdkPath)\include;$(SharedPath);$(SharedPath)\ext;$(IntDir)\CompiledShaders;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
</Project>

266
Samples.sln Normal file
Просмотреть файл

@ -0,0 +1,266 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29215.179
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Gltf_uwp", "shared\gltf\Gltf_uwp.vcxproj", "{63475578-0C83-4B2F-9AC5-A4513DE2907F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pbr_uwp", "shared\pbr\pbr_uwp.vcxproj", "{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "shared", "shared", "{1DCE4CA8-2962-4E73-ACC8-9A460DC7C2C0}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "XrSceneLib_uwp", "samples\XrSceneLib\XrSceneLib_uwp.vcxproj", "{56F1C3F4-8AB3-4518-9671-AA4219F56167}"
ProjectSection(ProjectDependencies) = postProject
{63475578-0C83-4B2F-9AC5-A4513DE2907F} = {63475578-0C83-4B2F-9AC5-A4513DE2907F}
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB} = {334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pbr_win32", "shared\pbr\pbr_win32.vcxproj", "{2B7688F8-9AE6-4A67-809B-1BAC82094F21}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "XrSceneLib_win32", "samples\XrSceneLib\XrSceneLib_win32.vcxproj", "{A758AF22-F54F-4C74-BF85-05A377B5892E}"
ProjectSection(ProjectDependencies) = postProject
{6A3225A3-0750-47B7-8004-80CA543F8B8B} = {6A3225A3-0750-47B7-8004-80CA543F8B8B}
{2B7688F8-9AE6-4A67-809B-1BAC82094F21} = {2B7688F8-9AE6-4A67-809B-1BAC82094F21}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Gltf_win32", "shared\gltf\Gltf_win32.vcxproj", "{6A3225A3-0750-47B7-8004-80CA543F8B8B}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "uwp", "uwp", "{5CBE3AE5-D53F-40E2-9380-F6348A569040}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "win32", "win32", "{279ABC91-3426-45B0-8876-113A48B7FB34}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "XrUtility", "XrUtility", "{AF0F6DD8-1BC3-4818-919E-9B239B544B5E}"
ProjectSection(SolutionItems) = preProject
shared\XrUtility\XrActionContext.h = shared\XrUtility\XrActionContext.h
shared\XrUtility\XrEnumerate.h = shared\XrUtility\XrEnumerate.h
shared\XrUtility\XrError.h = shared\XrUtility\XrError.h
shared\XrUtility\XrInstanceContext.h = shared\XrUtility\XrInstanceContext.h
shared\XrUtility\XrExtensions.h = shared\XrUtility\XrExtensions.h
shared\XrUtility\XrHand.h = shared\XrUtility\XrHand.h
shared\XrUtility\XrHandle.h = shared\XrUtility\XrHandle.h
shared\XrUtility\XrMath.h = shared\XrUtility\XrMath.h
shared\XrUtility\XrStereoView.h = shared\XrUtility\XrStereoView.h
shared\XrUtility\XrString.h = shared\XrUtility\XrString.h
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SampleShared_win32", "shared\SampleShared\SampleShared_win32.vcxproj", "{269C12FA-E68D-470B-A734-4701034306BD}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SampleShared_uwp", "shared\SampleShared\SampleShared_uwp.vcxproj", "{7A3653FD-90A8-4627-9185-F3EEFA539F49}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "openxr", "openxr", "{FAD9AAA7-533C-4BFC-8F54-A1A855044CEF}"
ProjectSection(SolutionItems) = preProject
openxr_preview\include\openxr\openxr.h = openxr_preview\include\openxr\openxr.h
openxr_preview\include\openxr\openxr_platform.h = openxr_preview\include\openxr\openxr_platform.h
openxr_preview\include\openxr\openxr_platform_defines.h = openxr_preview\include\openxr\openxr_platform_defines.h
openxr_preview\include\openxr\openxr_reflection.h = openxr_preview\include\openxr\openxr_reflection.h
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SampleSceneUwp", "samples\SampleSceneUwp\SampleSceneUwp.vcxproj", "{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SampleSceneWin32", "samples\SampleSceneWin32\SampleSceneWin32.vcxproj", "{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ThreeCubesUwp", "samples\ThreeCubesUwp\ThreeCubesUwp.vcxproj", "{66973A07-2499-4DB1-B16B-7558C0FC87D9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM = Release|ARM
Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Debug|ARM.ActiveCfg = Debug|ARM
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Debug|ARM.Build.0 = Debug|ARM
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Debug|ARM64.ActiveCfg = Debug|ARM64
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Debug|ARM64.Build.0 = Debug|ARM64
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Debug|x64.ActiveCfg = Debug|x64
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Debug|x64.Build.0 = Debug|x64
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Debug|x86.ActiveCfg = Debug|Win32
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Debug|x86.Build.0 = Debug|Win32
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Release|ARM.ActiveCfg = Release|ARM
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Release|ARM.Build.0 = Release|ARM
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Release|ARM64.ActiveCfg = Release|ARM64
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Release|ARM64.Build.0 = Release|ARM64
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Release|x64.ActiveCfg = Release|x64
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Release|x64.Build.0 = Release|x64
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Release|x86.ActiveCfg = Release|Win32
{63475578-0C83-4B2F-9AC5-A4513DE2907F}.Release|x86.Build.0 = Release|Win32
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Debug|ARM.ActiveCfg = Debug|ARM
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Debug|ARM.Build.0 = Debug|ARM
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Debug|ARM64.ActiveCfg = Debug|ARM64
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Debug|ARM64.Build.0 = Debug|ARM64
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Debug|x64.ActiveCfg = Debug|x64
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Debug|x64.Build.0 = Debug|x64
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Debug|x86.ActiveCfg = Debug|Win32
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Debug|x86.Build.0 = Debug|Win32
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Release|ARM.ActiveCfg = Release|ARM
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Release|ARM.Build.0 = Release|ARM
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Release|ARM64.ActiveCfg = Release|ARM64
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Release|ARM64.Build.0 = Release|ARM64
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Release|x64.ActiveCfg = Release|x64
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Release|x64.Build.0 = Release|x64
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Release|x86.ActiveCfg = Release|Win32
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB}.Release|x86.Build.0 = Release|Win32
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Debug|ARM.ActiveCfg = Debug|ARM
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Debug|ARM.Build.0 = Debug|ARM
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Debug|ARM64.ActiveCfg = Debug|ARM64
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Debug|ARM64.Build.0 = Debug|ARM64
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Debug|x64.ActiveCfg = Debug|x64
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Debug|x64.Build.0 = Debug|x64
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Debug|x86.ActiveCfg = Debug|Win32
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Debug|x86.Build.0 = Debug|Win32
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Release|ARM.ActiveCfg = Release|ARM
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Release|ARM.Build.0 = Release|ARM
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Release|ARM64.ActiveCfg = Release|ARM64
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Release|ARM64.Build.0 = Release|ARM64
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Release|x64.ActiveCfg = Release|x64
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Release|x64.Build.0 = Release|x64
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Release|x86.ActiveCfg = Release|Win32
{56F1C3F4-8AB3-4518-9671-AA4219F56167}.Release|x86.Build.0 = Release|Win32
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Debug|ARM.ActiveCfg = Debug|ARM
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Debug|ARM64.ActiveCfg = Debug|ARM64
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Debug|x64.ActiveCfg = Debug|x64
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Debug|x64.Build.0 = Debug|x64
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Debug|x86.ActiveCfg = Debug|Win32
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Debug|x86.Build.0 = Debug|Win32
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Release|ARM.ActiveCfg = Release|ARM
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Release|ARM64.ActiveCfg = Release|ARM64
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Release|x64.ActiveCfg = Release|x64
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Release|x64.Build.0 = Release|x64
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Release|x86.ActiveCfg = Release|Win32
{2B7688F8-9AE6-4A67-809B-1BAC82094F21}.Release|x86.Build.0 = Release|Win32
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Debug|ARM.ActiveCfg = Debug|ARM
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Debug|ARM64.ActiveCfg = Debug|ARM64
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Debug|x64.ActiveCfg = Debug|x64
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Debug|x64.Build.0 = Debug|x64
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Debug|x86.ActiveCfg = Debug|Win32
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Debug|x86.Build.0 = Debug|Win32
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Release|ARM.ActiveCfg = Release|ARM
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Release|ARM64.ActiveCfg = Release|ARM64
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Release|x64.ActiveCfg = Release|x64
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Release|x64.Build.0 = Release|x64
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Release|x86.ActiveCfg = Release|Win32
{A758AF22-F54F-4C74-BF85-05A377B5892E}.Release|x86.Build.0 = Release|Win32
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Debug|ARM.ActiveCfg = Debug|ARM
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Debug|ARM64.ActiveCfg = Debug|ARM64
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Debug|x64.ActiveCfg = Debug|x64
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Debug|x64.Build.0 = Debug|x64
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Debug|x86.ActiveCfg = Debug|Win32
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Debug|x86.Build.0 = Debug|Win32
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Release|ARM.ActiveCfg = Release|ARM
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Release|ARM64.ActiveCfg = Release|ARM64
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Release|x64.ActiveCfg = Release|x64
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Release|x64.Build.0 = Release|x64
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Release|x86.ActiveCfg = Release|Win32
{6A3225A3-0750-47B7-8004-80CA543F8B8B}.Release|x86.Build.0 = Release|Win32
{269C12FA-E68D-470B-A734-4701034306BD}.Debug|ARM.ActiveCfg = Debug|ARM
{269C12FA-E68D-470B-A734-4701034306BD}.Debug|ARM64.ActiveCfg = Debug|ARM64
{269C12FA-E68D-470B-A734-4701034306BD}.Debug|x64.ActiveCfg = Debug|x64
{269C12FA-E68D-470B-A734-4701034306BD}.Debug|x64.Build.0 = Debug|x64
{269C12FA-E68D-470B-A734-4701034306BD}.Debug|x86.ActiveCfg = Debug|Win32
{269C12FA-E68D-470B-A734-4701034306BD}.Debug|x86.Build.0 = Debug|Win32
{269C12FA-E68D-470B-A734-4701034306BD}.Release|ARM.ActiveCfg = Release|ARM
{269C12FA-E68D-470B-A734-4701034306BD}.Release|ARM64.ActiveCfg = Release|ARM64
{269C12FA-E68D-470B-A734-4701034306BD}.Release|x64.ActiveCfg = Release|x64
{269C12FA-E68D-470B-A734-4701034306BD}.Release|x64.Build.0 = Release|x64
{269C12FA-E68D-470B-A734-4701034306BD}.Release|x86.ActiveCfg = Release|Win32
{269C12FA-E68D-470B-A734-4701034306BD}.Release|x86.Build.0 = Release|Win32
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Debug|ARM.ActiveCfg = Debug|ARM
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Debug|ARM.Build.0 = Debug|ARM
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Debug|ARM64.ActiveCfg = Debug|ARM64
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Debug|ARM64.Build.0 = Debug|ARM64
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Debug|x64.ActiveCfg = Debug|x64
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Debug|x64.Build.0 = Debug|x64
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Debug|x86.ActiveCfg = Debug|Win32
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Debug|x86.Build.0 = Debug|Win32
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Release|ARM.ActiveCfg = Release|ARM
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Release|ARM.Build.0 = Release|ARM
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Release|ARM64.ActiveCfg = Release|ARM64
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Release|ARM64.Build.0 = Release|ARM64
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Release|x64.ActiveCfg = Release|x64
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Release|x64.Build.0 = Release|x64
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Release|x86.ActiveCfg = Release|Win32
{7A3653FD-90A8-4627-9185-F3EEFA539F49}.Release|x86.Build.0 = Release|Win32
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|ARM.ActiveCfg = Debug|ARM
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|ARM.Build.0 = Debug|ARM
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|ARM.Deploy.0 = Debug|ARM
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|ARM64.ActiveCfg = Debug|ARM64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|ARM64.Build.0 = Debug|ARM64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|ARM64.Deploy.0 = Debug|ARM64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|x64.ActiveCfg = Debug|x64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|x64.Build.0 = Debug|x64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|x64.Deploy.0 = Debug|x64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|x86.ActiveCfg = Debug|Win32
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|x86.Build.0 = Debug|Win32
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Debug|x86.Deploy.0 = Debug|Win32
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|ARM.ActiveCfg = Release|ARM
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|ARM.Build.0 = Release|ARM
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|ARM.Deploy.0 = Release|ARM
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|ARM64.ActiveCfg = Release|ARM64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|ARM64.Build.0 = Release|ARM64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|ARM64.Deploy.0 = Release|ARM64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|x64.ActiveCfg = Release|x64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|x64.Build.0 = Release|x64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|x64.Deploy.0 = Release|x64
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|x86.ActiveCfg = Release|Win32
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|x86.Build.0 = Release|Win32
{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}.Release|x86.Deploy.0 = Release|Win32
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Debug|ARM.ActiveCfg = Debug|Win32
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Debug|ARM64.ActiveCfg = Debug|Win32
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Debug|x64.ActiveCfg = Debug|x64
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Debug|x64.Build.0 = Debug|x64
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Debug|x86.ActiveCfg = Debug|Win32
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Debug|x86.Build.0 = Debug|Win32
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Release|ARM.ActiveCfg = Release|Win32
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Release|ARM64.ActiveCfg = Release|Win32
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Release|x64.ActiveCfg = Release|x64
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Release|x64.Build.0 = Release|x64
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Release|x86.ActiveCfg = Release|Win32
{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}.Release|x86.Build.0 = Release|Win32
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|ARM.ActiveCfg = Debug|ARM
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|ARM.Build.0 = Debug|ARM
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|ARM.Deploy.0 = Debug|ARM
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|ARM64.ActiveCfg = Debug|ARM64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|ARM64.Build.0 = Debug|ARM64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|ARM64.Deploy.0 = Debug|ARM64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|x64.ActiveCfg = Debug|x64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|x64.Build.0 = Debug|x64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|x64.Deploy.0 = Debug|x64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|x86.ActiveCfg = Debug|Win32
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|x86.Build.0 = Debug|Win32
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Debug|x86.Deploy.0 = Debug|Win32
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|ARM.ActiveCfg = Release|ARM
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|ARM.Build.0 = Release|ARM
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|ARM.Deploy.0 = Release|ARM
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|ARM64.ActiveCfg = Release|ARM64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|ARM64.Build.0 = Release|ARM64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|ARM64.Deploy.0 = Release|ARM64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|x64.ActiveCfg = Release|x64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|x64.Build.0 = Release|x64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|x64.Deploy.0 = Release|x64
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|x86.ActiveCfg = Release|Win32
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|x86.Build.0 = Release|Win32
{66973A07-2499-4DB1-B16B-7558C0FC87D9}.Release|x86.Deploy.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{63475578-0C83-4B2F-9AC5-A4513DE2907F} = {5CBE3AE5-D53F-40E2-9380-F6348A569040}
{334E53B6-28DC-4F46-A7D9-CCEC681F4FEB} = {5CBE3AE5-D53F-40E2-9380-F6348A569040}
{2B7688F8-9AE6-4A67-809B-1BAC82094F21} = {279ABC91-3426-45B0-8876-113A48B7FB34}
{6A3225A3-0750-47B7-8004-80CA543F8B8B} = {279ABC91-3426-45B0-8876-113A48B7FB34}
{5CBE3AE5-D53F-40E2-9380-F6348A569040} = {1DCE4CA8-2962-4E73-ACC8-9A460DC7C2C0}
{279ABC91-3426-45B0-8876-113A48B7FB34} = {1DCE4CA8-2962-4E73-ACC8-9A460DC7C2C0}
{AF0F6DD8-1BC3-4818-919E-9B239B544B5E} = {1DCE4CA8-2962-4E73-ACC8-9A460DC7C2C0}
{269C12FA-E68D-470B-A734-4701034306BD} = {279ABC91-3426-45B0-8876-113A48B7FB34}
{7A3653FD-90A8-4627-9185-F3EEFA539F49} = {5CBE3AE5-D53F-40E2-9380-F6348A569040}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6883759C-1988-4CF6-8FDF-9FF149924A59}
EndGlobalSection
EndGlobal

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,383 @@
#ifndef OPENXR_PLATFORM_H_
#define OPENXR_PLATFORM_H_ 1
/*
** Copyright (c) 2017-2020 The Khronos Group Inc.
**
** 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.
*/
/*
** This header is generated from the Khronos OpenXR XML API Registry.
**
*/
#include "openxr.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef XR_USE_PLATFORM_ANDROID
#define XR_KHR_android_thread_settings 1
#define XR_KHR_android_thread_settings_SPEC_VERSION 5
#define XR_KHR_ANDROID_THREAD_SETTINGS_EXTENSION_NAME "XR_KHR_android_thread_settings"
typedef enum XrAndroidThreadTypeKHR {
XR_ANDROID_THREAD_TYPE_APPLICATION_MAIN_KHR = 1,
XR_ANDROID_THREAD_TYPE_APPLICATION_WORKER_KHR = 2,
XR_ANDROID_THREAD_TYPE_RENDERER_MAIN_KHR = 3,
XR_ANDROID_THREAD_TYPE_RENDERER_WORKER_KHR = 4,
XR_ANDROID_THREAD_TYPE_MAX_ENUM_KHR = 0x7FFFFFFF
} XrAndroidThreadTypeKHR;
typedef XrResult (XRAPI_PTR *PFN_xrSetAndroidApplicationThreadKHR)(XrSession session, XrAndroidThreadTypeKHR threadType, uint32_t threadId);
#ifndef XR_NO_PROTOTYPES
XRAPI_ATTR XrResult XRAPI_CALL xrSetAndroidApplicationThreadKHR(
XrSession session,
XrAndroidThreadTypeKHR threadType,
uint32_t threadId);
#endif
#endif /* XR_USE_PLATFORM_ANDROID */
#ifdef XR_USE_PLATFORM_ANDROID
#define XR_KHR_android_surface_swapchain 1
#define XR_KHR_android_surface_swapchain_SPEC_VERSION 4
#define XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME "XR_KHR_android_surface_swapchain"
typedef XrResult (XRAPI_PTR *PFN_xrCreateSwapchainAndroidSurfaceKHR)(XrSession session, const XrSwapchainCreateInfo* info, XrSwapchain* swapchain, jobject* surface);
#ifndef XR_NO_PROTOTYPES
XRAPI_ATTR XrResult XRAPI_CALL xrCreateSwapchainAndroidSurfaceKHR(
XrSession session,
const XrSwapchainCreateInfo* info,
XrSwapchain* swapchain,
jobject* surface);
#endif
#endif /* XR_USE_PLATFORM_ANDROID */
#ifdef XR_USE_PLATFORM_ANDROID
#define XR_KHR_android_create_instance 1
#define XR_KHR_android_create_instance_SPEC_VERSION 3
#define XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME "XR_KHR_android_create_instance"
typedef struct XrInstanceCreateInfoAndroidKHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
void* XR_MAY_ALIAS applicationVM;
void* XR_MAY_ALIAS applicationActivity;
} XrInstanceCreateInfoAndroidKHR;
#endif /* XR_USE_PLATFORM_ANDROID */
#ifdef XR_USE_GRAPHICS_API_VULKAN
#define XR_KHR_vulkan_swapchain_format_list 1
#define XR_KHR_vulkan_swapchain_format_list_SPEC_VERSION 2
#define XR_KHR_VULKAN_SWAPCHAIN_FORMAT_LIST_EXTENSION_NAME "XR_KHR_vulkan_swapchain_format_list"
typedef struct XrVulkanSwapchainFormatListCreateInfoKHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
uint32_t viewFormatCount;
const VkFormat* viewFormats;
} XrVulkanSwapchainFormatListCreateInfoKHR;
#endif /* XR_USE_GRAPHICS_API_VULKAN */
#ifdef XR_USE_GRAPHICS_API_OPENGL
#define XR_KHR_opengl_enable 1
#define XR_KHR_opengl_enable_SPEC_VERSION 8
#define XR_KHR_OPENGL_ENABLE_EXTENSION_NAME "XR_KHR_opengl_enable"
#ifdef XR_USE_PLATFORM_WIN32
typedef struct XrGraphicsBindingOpenGLWin32KHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
HDC hDC;
HGLRC hGLRC;
} XrGraphicsBindingOpenGLWin32KHR;
#endif // XR_USE_PLATFORM_WIN32
#ifdef XR_USE_PLATFORM_XLIB
typedef struct XrGraphicsBindingOpenGLXlibKHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
Display* xDisplay;
uint32_t visualid;
GLXFBConfig glxFBConfig;
GLXDrawable glxDrawable;
GLXContext glxContext;
} XrGraphicsBindingOpenGLXlibKHR;
#endif // XR_USE_PLATFORM_XLIB
#ifdef XR_USE_PLATFORM_XCB
typedef struct XrGraphicsBindingOpenGLXcbKHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
xcb_connection_t* connection;
uint32_t screenNumber;
xcb_glx_fbconfig_t fbconfigid;
xcb_visualid_t visualid;
xcb_glx_drawable_t glxDrawable;
xcb_glx_context_t glxContext;
} XrGraphicsBindingOpenGLXcbKHR;
#endif // XR_USE_PLATFORM_XCB
#ifdef XR_USE_PLATFORM_WAYLAND
typedef struct XrGraphicsBindingOpenGLWaylandKHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
struct wl_display* display;
} XrGraphicsBindingOpenGLWaylandKHR;
#endif // XR_USE_PLATFORM_WAYLAND
typedef struct XrSwapchainImageOpenGLKHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
uint32_t image;
} XrSwapchainImageOpenGLKHR;
typedef struct XrGraphicsRequirementsOpenGLKHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
XrVersion minApiVersionSupported;
XrVersion maxApiVersionSupported;
} XrGraphicsRequirementsOpenGLKHR;
typedef XrResult (XRAPI_PTR *PFN_xrGetOpenGLGraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsOpenGLKHR* graphicsRequirements);
#ifndef XR_NO_PROTOTYPES
XRAPI_ATTR XrResult XRAPI_CALL xrGetOpenGLGraphicsRequirementsKHR(
XrInstance instance,
XrSystemId systemId,
XrGraphicsRequirementsOpenGLKHR* graphicsRequirements);
#endif
#endif /* XR_USE_GRAPHICS_API_OPENGL */
#ifdef XR_USE_GRAPHICS_API_OPENGL_ES
#define XR_KHR_opengl_es_enable 1
#define XR_KHR_opengl_es_enable_SPEC_VERSION 6
#define XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME "XR_KHR_opengl_es_enable"
#ifdef XR_USE_PLATFORM_ANDROID
typedef struct XrGraphicsBindingOpenGLESAndroidKHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
EGLDisplay display;
EGLConfig config;
EGLContext context;
} XrGraphicsBindingOpenGLESAndroidKHR;
#endif // XR_USE_PLATFORM_ANDROID
typedef struct XrSwapchainImageOpenGLESKHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
uint32_t image;
} XrSwapchainImageOpenGLESKHR;
typedef struct XrGraphicsRequirementsOpenGLESKHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
XrVersion minApiVersionSupported;
XrVersion maxApiVersionSupported;
} XrGraphicsRequirementsOpenGLESKHR;
typedef XrResult (XRAPI_PTR *PFN_xrGetOpenGLESGraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsOpenGLESKHR* graphicsRequirements);
#ifndef XR_NO_PROTOTYPES
XRAPI_ATTR XrResult XRAPI_CALL xrGetOpenGLESGraphicsRequirementsKHR(
XrInstance instance,
XrSystemId systemId,
XrGraphicsRequirementsOpenGLESKHR* graphicsRequirements);
#endif
#endif /* XR_USE_GRAPHICS_API_OPENGL_ES */
#ifdef XR_USE_GRAPHICS_API_VULKAN
#define XR_KHR_vulkan_enable 1
#define XR_KHR_vulkan_enable_SPEC_VERSION 6
#define XR_KHR_VULKAN_ENABLE_EXTENSION_NAME "XR_KHR_vulkan_enable"
typedef struct XrGraphicsBindingVulkanKHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
VkInstance instance;
VkPhysicalDevice physicalDevice;
VkDevice device;
uint32_t queueFamilyIndex;
uint32_t queueIndex;
} XrGraphicsBindingVulkanKHR;
typedef struct XrSwapchainImageVulkanKHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
VkImage image;
} XrSwapchainImageVulkanKHR;
typedef struct XrGraphicsRequirementsVulkanKHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
XrVersion minApiVersionSupported;
XrVersion maxApiVersionSupported;
} XrGraphicsRequirementsVulkanKHR;
typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanInstanceExtensionsKHR)(XrInstance instance, XrSystemId systemId, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer);
typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanDeviceExtensionsKHR)(XrInstance instance, XrSystemId systemId, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer);
typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanGraphicsDeviceKHR)(XrInstance instance, XrSystemId systemId, VkInstance vkInstance, VkPhysicalDevice* vkPhysicalDevice);
typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanGraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsVulkanKHR* graphicsRequirements);
#ifndef XR_NO_PROTOTYPES
XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanInstanceExtensionsKHR(
XrInstance instance,
XrSystemId systemId,
uint32_t bufferCapacityInput,
uint32_t* bufferCountOutput,
char* buffer);
XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanDeviceExtensionsKHR(
XrInstance instance,
XrSystemId systemId,
uint32_t bufferCapacityInput,
uint32_t* bufferCountOutput,
char* buffer);
XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanGraphicsDeviceKHR(
XrInstance instance,
XrSystemId systemId,
VkInstance vkInstance,
VkPhysicalDevice* vkPhysicalDevice);
XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanGraphicsRequirementsKHR(
XrInstance instance,
XrSystemId systemId,
XrGraphicsRequirementsVulkanKHR* graphicsRequirements);
#endif
#endif /* XR_USE_GRAPHICS_API_VULKAN */
#ifdef XR_USE_GRAPHICS_API_D3D11
#define XR_KHR_D3D11_enable 1
#define XR_KHR_D3D11_enable_SPEC_VERSION 4
#define XR_KHR_D3D11_ENABLE_EXTENSION_NAME "XR_KHR_D3D11_enable"
typedef struct XrGraphicsBindingD3D11KHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
ID3D11Device* device;
} XrGraphicsBindingD3D11KHR;
typedef struct XrSwapchainImageD3D11KHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
ID3D11Texture2D* texture;
} XrSwapchainImageD3D11KHR;
typedef struct XrGraphicsRequirementsD3D11KHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
LUID adapterLuid;
D3D_FEATURE_LEVEL minFeatureLevel;
} XrGraphicsRequirementsD3D11KHR;
typedef XrResult (XRAPI_PTR *PFN_xrGetD3D11GraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsD3D11KHR* graphicsRequirements);
#ifndef XR_NO_PROTOTYPES
XRAPI_ATTR XrResult XRAPI_CALL xrGetD3D11GraphicsRequirementsKHR(
XrInstance instance,
XrSystemId systemId,
XrGraphicsRequirementsD3D11KHR* graphicsRequirements);
#endif
#endif /* XR_USE_GRAPHICS_API_D3D11 */
#ifdef XR_USE_GRAPHICS_API_D3D12
#define XR_KHR_D3D12_enable 1
#define XR_KHR_D3D12_enable_SPEC_VERSION 5
#define XR_KHR_D3D12_ENABLE_EXTENSION_NAME "XR_KHR_D3D12_enable"
typedef struct XrGraphicsBindingD3D12KHR {
XrStructureType type;
const void* XR_MAY_ALIAS next;
ID3D12Device* device;
ID3D12CommandQueue* queue;
} XrGraphicsBindingD3D12KHR;
typedef struct XrSwapchainImageD3D12KHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
ID3D12Resource* texture;
} XrSwapchainImageD3D12KHR;
typedef struct XrGraphicsRequirementsD3D12KHR {
XrStructureType type;
void* XR_MAY_ALIAS next;
LUID adapterLuid;
D3D_FEATURE_LEVEL minFeatureLevel;
} XrGraphicsRequirementsD3D12KHR;
typedef XrResult (XRAPI_PTR *PFN_xrGetD3D12GraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsD3D12KHR* graphicsRequirements);
#ifndef XR_NO_PROTOTYPES
XRAPI_ATTR XrResult XRAPI_CALL xrGetD3D12GraphicsRequirementsKHR(
XrInstance instance,
XrSystemId systemId,
XrGraphicsRequirementsD3D12KHR* graphicsRequirements);
#endif
#endif /* XR_USE_GRAPHICS_API_D3D12 */
#ifdef XR_USE_PLATFORM_WIN32
#define XR_KHR_win32_convert_performance_counter_time 1
#define XR_KHR_win32_convert_performance_counter_time_SPEC_VERSION 1
#define XR_KHR_WIN32_CONVERT_PERFORMANCE_COUNTER_TIME_EXTENSION_NAME "XR_KHR_win32_convert_performance_counter_time"
typedef XrResult (XRAPI_PTR *PFN_xrConvertWin32PerformanceCounterToTimeKHR)(XrInstance instance, const LARGE_INTEGER* performanceCounter, XrTime* time);
typedef XrResult (XRAPI_PTR *PFN_xrConvertTimeToWin32PerformanceCounterKHR)(XrInstance instance, XrTime time, LARGE_INTEGER* performanceCounter);
#ifndef XR_NO_PROTOTYPES
XRAPI_ATTR XrResult XRAPI_CALL xrConvertWin32PerformanceCounterToTimeKHR(
XrInstance instance,
const LARGE_INTEGER* performanceCounter,
XrTime* time);
XRAPI_ATTR XrResult XRAPI_CALL xrConvertTimeToWin32PerformanceCounterKHR(
XrInstance instance,
XrTime time,
LARGE_INTEGER* performanceCounter);
#endif
#endif /* XR_USE_PLATFORM_WIN32 */
#ifdef XR_USE_TIMESPEC
#define XR_KHR_convert_timespec_time 1
#define XR_KHR_convert_timespec_time_SPEC_VERSION 1
#define XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME "XR_KHR_convert_timespec_time"
typedef XrResult (XRAPI_PTR *PFN_xrConvertTimespecTimeToTimeKHR)(XrInstance instance, const struct timespec* timespecTime, XrTime* time);
typedef XrResult (XRAPI_PTR *PFN_xrConvertTimeToTimespecTimeKHR)(XrInstance instance, XrTime time, struct timespec* timespecTime);
#ifndef XR_NO_PROTOTYPES
XRAPI_ATTR XrResult XRAPI_CALL xrConvertTimespecTimeToTimeKHR(
XrInstance instance,
const struct timespec* timespecTime,
XrTime* time);
XRAPI_ATTR XrResult XRAPI_CALL xrConvertTimeToTimespecTimeKHR(
XrInstance instance,
XrTime time,
struct timespec* timespecTime);
#endif
#endif /* XR_USE_TIMESPEC */
#ifdef __cplusplus
}
#endif
#endif

Просмотреть файл

@ -0,0 +1,120 @@
/*
** Copyright (c) 2017-2020 The Khronos Group Inc.
**
** 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.
*/
#ifndef OPENXR_PLATFORM_DEFINES_H_
#define OPENXR_PLATFORM_DEFINES_H_ 1
#ifdef __cplusplus
extern "C" {
#endif
/* Platform-specific calling convention macros.
*
* Platforms should define these so that OpenXR clients call OpenXR functions
* with the same calling conventions that the OpenXR implementation expects.
*
* XRAPI_ATTR - Placed before the return type in function declarations.
* Useful for C++11 and GCC/Clang-style function attribute syntax.
* XRAPI_CALL - Placed after the return type in function declarations.
* Useful for MSVC-style calling convention syntax.
* XRAPI_PTR - Placed between the '(' and '*' in function pointer types.
*
* Function declaration: XRAPI_ATTR void XRAPI_CALL xrFunction(void);
* Function pointer type: typedef void (XRAPI_PTR *PFN_xrFunction)(void);
*/
#if defined(_WIN32)
#define XRAPI_ATTR
// On Windows, functions use the stdcall convention
#define XRAPI_CALL __stdcall
#define XRAPI_PTR XRAPI_CALL
#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH < 7
#error "API not supported for the 'armeabi' NDK ABI"
#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7 && defined(__ARM_32BIT_STATE)
// On Android 32-bit ARM targets, functions use the "hardfloat"
// calling convention, i.e. float parameters are passed in registers. This
// is true even if the rest of the application passes floats on the stack,
// as it does by default when compiling for the armeabi-v7a NDK ABI.
#define XRAPI_ATTR __attribute__((pcs("aapcs-vfp")))
#define XRAPI_CALL
#define XRAPI_PTR XRAPI_ATTR
#else
// On other platforms, use the default calling convention
#define XRAPI_ATTR
#define XRAPI_CALL
#define XRAPI_PTR
#endif
#include <stddef.h>
#if !defined(XR_NO_STDINT_H)
#if defined(_MSC_VER) && (_MSC_VER < 1600)
typedef signed __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef signed __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef signed __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
#endif // !defined( XR_NO_STDINT_H )
// XR_PTR_SIZE (in bytes)
#if (defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__))
#define XR_PTR_SIZE 8
#else
#define XR_PTR_SIZE 4
#endif
// Needed so we can use clang __has_feature portably.
#if !defined(XR_COMPILER_HAS_FEATURE)
#if defined(__clang__)
#define XR_COMPILER_HAS_FEATURE(x) __has_feature(x)
#else
#define XR_COMPILER_HAS_FEATURE(x) 0
#endif
#endif
// Identifies if the current compiler has C++11 support enabled.
// Does not by itself identify if any given C++11 feature is present.
#if !defined(XR_CPP11_ENABLED) && defined(__cplusplus)
#if defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__)
#define XR_CPP11_ENABLED 1
#elif defined(_MSC_VER) && (_MSC_VER >= 1600)
#define XR_CPP11_ENABLED 1
#elif (__cplusplus >= 201103L) // 201103 is the first C++11 version.
#define XR_CPP11_ENABLED 1
#endif
#endif
// Identifies if the current compiler supports C++11 nullptr.
#if !defined(XR_CPP_NULLPTR_SUPPORTED)
#if defined(XR_CPP11_ENABLED) && \
((defined(__clang__) && XR_COMPILER_HAS_FEATURE(cxx_nullptr)) || \
(defined(__GNUC__) && (((__GNUC__ * 1000) + __GNUC_MINOR__) >= 4006)) || \
(defined(_MSC_VER) && (_MSC_VER >= 1600)) || \
(defined(__EDG_VERSION__) && (__EDG_VERSION__ >= 403)))
#define XR_CPP_NULLPTR_SUPPORTED 1
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Просмотреть файл

@ -1,21 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.props')" />
<PropertyGroup Label="Globals">
<ProjectGuid>{1b09b21c-2d7a-4278-81c8-84a47d5834a7}</ProjectGuid>
<Keyword>HolographicApp</Keyword>
<RootNamespace>BasicXrApp</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<MinimumVisualStudioVersion>15.0</MinimumVisualStudioVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.17763.0</WindowsTargetPlatformMinVersion>
<PackageCertificateThumbprint>0071016DCE22933BB0F19305D78E0794B55121C8</PackageCertificateThumbprint>
<PackageCertificateKeyFile>BasicXrApp_uwp_TemporaryKey.pfx</PackageCertificateKeyFile>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
@ -29,10 +14,6 @@
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
@ -45,11 +26,30 @@
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{1b09b21c-2d7a-4278-81c8-84a47d5834a7}</ProjectGuid>
<Keyword>HolographicApp</Keyword>
<RootNamespace>BasicXrApp</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<MinimumVisualStudioVersion>15.0</MinimumVisualStudioVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.17763.0</WindowsTargetPlatformMinVersion>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
<PackageCertificateThumbprint>0071016DCE22933BB0F19305D78E0794B55121C8</PackageCertificateThumbprint>
<PackageCertificateKeyFile>TemporaryKey.pfx</PackageCertificateKeyFile>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v140</PlatformToolset>
@ -64,6 +64,7 @@
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<SpectreMitigation>false</SpectreMitigation>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
@ -79,22 +80,30 @@
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_WINDOWS;%(PreprocessorDefinitions);UWP</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<AdditionalOptions>%(AdditionalOptions) /permissive-</AdditionalOptions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<AdditionalOptions>%(AdditionalOptions) /permissive-</AdditionalOptions>
<LanguageStandard>stdcpp17</LanguageStandard>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
<AdditionalDependencies>OneCore.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
@ -103,6 +112,7 @@
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
@ -136,7 +146,7 @@
<AppxManifest Include="Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
<None Include="BasicXrApp_uwp_TemporaryKey.pfx" />
<None Include="TemporaryKey.pfx" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
@ -144,13 +154,13 @@
<Import Project="$(VSINSTALLDIR)\Common7\IDE\Extensions\Microsoft\VsGraphics\ImageContentTask.targets" />
<Import Project="$(VSINSTALLDIR)\Common7\IDE\Extensions\Microsoft\VsGraphics\MeshContentTask.targets" />
<Import Project="$(VSINSTALLDIR)\Common7\IDE\Extensions\Microsoft\VsGraphics\ShaderGraphContentTask.targets" />
<Import Project="..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.targets')" />
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.targets'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -44,9 +44,10 @@
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="BasicXrApp_uwp_TemporaryKey.pfx">
<None Include="TemporaryKey.pfx">
<Filter>Assets</Filter>
</None>
<None Include="packages.config" />
<None Include="$(OpenXRLoaderBinaryRoot)\bin\openxr_loader.dll" />
</ItemGroup>
</Project>

Просмотреть файл

@ -1,17 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.props')" />
<PropertyGroup Label="Globals">
<CppWinRTOptimized>true</CppWinRTOptimized>
<MinimalCoreWin>true</MinimalCoreWin>
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{a75a907b-8952-4ed2-bc2d-a68f09cebd83}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>BasicXrApp_win32</RootNamespace>
<WindowsTargetPlatformVersion Condition=" '$(WindowsTargetPlatformVersion)' == '' ">10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.17763.0</WindowsTargetPlatformMinVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
@ -30,21 +19,23 @@
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<CppWinRTOptimized>true</CppWinRTOptimized>
<MinimalCoreWin>true</MinimalCoreWin>
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{a75a907b-8952-4ed2-bc2d-a68f09cebd83}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>BasicXrApp_win32</RootNamespace>
<WindowsTargetPlatformVersion Condition=" '$(WindowsTargetPlatformVersion)' == '' ">10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.17763.0</WindowsTargetPlatformMinVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '16.0'">v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
@ -54,18 +45,34 @@
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<AdditionalOptions>%(AdditionalOptions) /permissive-</AdditionalOptions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<AdditionalOptions>%(AdditionalOptions) /permissive-</AdditionalOptions>
<LanguageStandard>stdcpp17</LanguageStandard>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
<AdditionalDependencies>windowsapp.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
@ -76,11 +83,6 @@
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
@ -110,13 +112,13 @@
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.targets')" />
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6\build\native\OpenXR.Loader.targets'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -69,11 +69,11 @@ namespace {
createInfo.enabledExtensionCount = (uint32_t)enabledExtensions.size();
createInfo.enabledExtensionNames = enabledExtensions.data();
createInfo.applicationInfo = {"", 1, "OpenXR Sample", 1, XR_CURRENT_API_VERSION};
createInfo.applicationInfo = {"BasicXrApp", 1, "", 1, XR_CURRENT_API_VERSION};
strcpy_s(createInfo.applicationInfo.applicationName, m_applicationName.c_str());
CHECK_XRCMD(xrCreateInstance(&createInfo, m_instance.Put()));
m_extensions = std::make_unique<xr::ExtensionDispatchTable>(m_instance.Get());
m_extensions.PopulateDispatchTable(m_instance.Get());
}
std::vector<const char*> SelectExtensions() {
@ -235,7 +235,7 @@ namespace {
// Create the D3D11 device for the adapter associated with the system.
XrGraphicsRequirementsD3D11KHR graphicsRequirements{XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR};
CHECK_XRCMD(m_extensions->xrGetD3D11GraphicsRequirementsKHR(m_instance.Get(), m_systemId, &graphicsRequirements));
CHECK_XRCMD(m_extensions.xrGetD3D11GraphicsRequirementsKHR(m_instance.Get(), m_systemId, &graphicsRequirements));
// Create a list of feature levels which are both supported by the OpenXR runtime and this application.
std::vector<D3D_FEATURE_LEVEL> featureLevels = {D3D_FEATURE_LEVEL_12_1,
@ -503,13 +503,13 @@ namespace {
createInfo.pose = poseInScene;
createInfo.time = placementTime;
XrResult result = m_extensions->xrCreateSpatialAnchorMSFT(
m_session.Get(), &createInfo, hologram.Anchor.Put(m_extensions->xrDestroySpatialAnchorMSFT));
XrResult result = m_extensions.xrCreateSpatialAnchorMSFT(
m_session.Get(), &createInfo, hologram.Anchor.Put(m_extensions.xrDestroySpatialAnchorMSFT));
if (XR_SUCCEEDED(result)) {
XrSpatialAnchorSpaceCreateInfoMSFT createSpaceInfo{XR_TYPE_SPATIAL_ANCHOR_SPACE_CREATE_INFO_MSFT};
createSpaceInfo.anchor = hologram.Anchor.Get();
createSpaceInfo.poseInAnchorSpace = xr::math::Pose::Identity();
CHECK_XRCMD(m_extensions->xrCreateSpatialAnchorSpaceMSFT(m_session.Get(), &createSpaceInfo, hologram.Cube.Space.Put()));
CHECK_XRCMD(m_extensions.xrCreateSpatialAnchorSpaceMSFT(m_session.Get(), &createSpaceInfo, hologram.Cube.Space.Put()));
} else if (result == XR_ERROR_CREATE_SPATIAL_ANCHOR_FAILED_MSFT) {
DEBUG_PRINT("Anchor cannot be created, likely due to lost positional tracking.");
} else {
@ -840,7 +840,7 @@ namespace {
xr::InstanceHandle m_instance;
xr::SessionHandle m_session;
uint64_t m_systemId{XR_NULL_SYSTEM_ID};
std::unique_ptr<xr::ExtensionDispatchTable> m_extensions;
xr::ExtensionDispatchTable m_extensions;
struct {
bool DepthExtensionSupported{false};

Просмотреть файл

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenXR.Loader" version="1.0.6" targetFramework="native" />
<package id="OpenXR.Loader" version="1.0.6.2" targetFramework="native" />
</packages>

Просмотреть файл

@ -0,0 +1,48 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "App.h"
std::unique_ptr<Scene> CreateOrbitScene(SceneContext* sceneContext);
std::unique_ptr<Scene> CreateHandTrackingScene(SceneContext* sceneContext);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) {
try {
CHECK_HRCMD(::CoInitializeEx(nullptr, COINIT_MULTITHREADED));
auto on_exit = MakeScopeGuard([] { ::CoUninitialize(); });
const std::vector<const char*> requiredExtensions = {
XR_MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME,
XR_MSFT_SPATIAL_ANCHOR_EXTENSION_NAME,
XR_MSFT_HAND_INTERACTION_PREVIEW_EXTENSION_NAME,
XR_MSFT_HAND_TRACKING_PREVIEW_EXTENSION_NAME,
XR_MSFT_HAND_TRACKING_MESH_PREVIEW_EXTENSION_NAME,
};
auto app = CreateXrApp({"SampleSceneUwp", 1}, requiredExtensions);
app->AddScene(CreateHandTrackingScene(app->SceneContext()));
app->AddScene(CreateOrbitScene(app->SceneContext()));
app->Run();
} catch (const std::exception& ex) {
sample::Trace("Unhandled Exception: {}\n", ex.what());
return 1;
} catch (...) {
sample::Trace(L"Unhandled Exception\n");
return 1;
}
return 0;
}

Просмотреть файл

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:uap2="http://schemas.microsoft.com/appx/manifest/uap/windows10/2" IgnorableNamespaces="uap mp uap2">
<Identity Name="SampleSceneUwp" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="309c7a45-edf9-45bd-8df1-eab43feff765" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
<Properties>
<DisplayName>SampleSceneUwp</DisplayName>
<PublisherDisplayName>Microsoft Corporation</PublisherDisplayName>
<Logo>SampleShared_uwp\UWPAssets\storelogo-sdk.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.18295.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="App.App">
<uap:VisualElements DisplayName="SampleSceneUwp" Square150x150Logo="SampleShared_uwp\UWPAssets\squareTile-sdk.png" Square44x44Logo="SampleShared_uwp\UWPAssets\smallTile-sdk.png" Description="SampleSceneUwp" BackgroundColor="#00B2F0">
<uap:SplashScreen Image="SampleShared_uwp\UWPAssets\splash-sdk.png" />
<uap:DefaultTile>
<uap:ShowNameOnTiles>
<uap:ShowOn Tile="square150x150Logo" />
</uap:ShowNameOnTiles>
</uap:DefaultTile>
</uap:VisualElements>
</Application>
</Applications>
<Capabilities>
<uap2:Capability Name="spatialPerception" />
</Capabilities>
</Package>

Просмотреть файл

@ -0,0 +1,173 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM64">
<Configuration>Debug</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM64">
<Configuration>Release</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{11ADC3A8-3996-40EC-B481-5EAA3ACB63C9}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>SampleSceneUwp</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.17763.0</WindowsTargetPlatformMinVersion>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
<PackageCertificateThumbprint>0071016DCE22933BB0F19305D78E0794B55121C8</PackageCertificateThumbprint>
<PackageCertificateKeyFile>TemporaryKey.pfx</PackageCertificateKeyFile>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<!-- PREfast builds only compile code, not link them. Set the uwp projects to static lib to skip package generation problems. -->
<ConfigurationType Condition="'$(LinkCompiled)'!='false'">Application</ConfigurationType>
<ConfigurationType Condition="'$(LinkCompiled)'=='false'">StaticLibrary</ConfigurationType>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<SpectreMitigation>false</SpectreMitigation>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup>
<IncludePath>$(SharedPath);$(SharedPath)\ext;$(OpenXrSdkPath)\include;$(IntDir)\CompiledShaders;$(ProjectDir)..\XrSceneLib;$(IncludePath);</IncludePath>
<AppxPackageSigningEnabled>True</AppxPackageSigningEnabled>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_WINDOWS;%(PreprocessorDefinitions);UWP</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<AdditionalOptions>%(AdditionalOptions) /permissive-</AdditionalOptions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
<AdditionalDependencies>OneCore.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="Main.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="Scene_Orbit.cpp" />
<ClCompile Include="Scene_HandTracking.cpp" />
</ItemGroup>
<ItemGroup>
<None Include="TemporaryKey.pfx" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<None Include="$(SharedPath)\pbr\brdf_lut.png">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(SharedPath)\SampleShared\Sample_DiffuseHDR.dds">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(SharedPath)\SampleShared\Sample_SpecularHDR.dds">
<DeploymentContent>true</DeploymentContent>
</None>
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest" Condition="'$(LinkCompiled)'!='false'">
<SubType>Designer</SubType>
</AppxManifest>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\XrSceneLib\XrSceneLib_uwp.vcxproj">
<Project>{56f1c3f4-8ab3-4518-9671-aa4219f56167}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="Main.cpp" />
<ClCompile Include="pch.cpp" />
<ClCompile Include="Scene_Orbit.cpp" />
<ClCompile Include="Scene_HandTracking.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest" />
</ItemGroup>
<ItemGroup>
<None Include="TemporaryKey.pfx" />
<None Include="packages.config" />
<None Include="$(OpenXRLoaderBinaryRoot)\bin\openxr_loader.dll" />
<None Include="$(SharedPath)\pbr\brdf_lut.png">
<Filter>Assets</Filter>
</None>
<None Include="$(SharedPath)\SampleShared\Sample_DiffuseHDR.dds">
<Filter>Assets</Filter>
</None>
<None Include="$(SharedPath)\SampleShared\Sample_SpecularHDR.dds">
<Filter>Assets</Filter>
</None>
</ItemGroup>
<ItemGroup>
<Filter Include="Assets">
<UniqueIdentifier>{8eb32a1e-ec4a-4c3c-881e-2e7e281f7df2}</UniqueIdentifier>
</Filter>
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,373 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include <XrUtility/XrHand.h>
#include "PbrModelObject.h"
#include "Scene.h"
using namespace DirectX;
namespace {
//
// This sample displays hand tracking inputs appears as hand mesh, or joint axes.
// User can clap their hands to toggle between different display mode
// It also demos a simple procedural coloring of the hand mesh using the "open palm" reference hand input.
//
struct HandTrackingScene : public Scene {
HandTrackingScene(SceneContext* sceneContext)
: Scene(sceneContext, L"Hand Tracking", true) {
m_jointMaterial = Pbr::Material::CreateFlat(m_sceneContext->PbrResources, Pbr::RGBA::White, 0.85f, 0.01f);
m_meshMaterial = Pbr::Material::CreateFlat(m_sceneContext->PbrResources, Pbr::RGBA::White, 1, 0);
auto createJointObjects = [&](HandData& handData) {
auto jointModel = std::make_shared<Pbr::Model>();
Pbr::PrimitiveBuilder primitiveBuilder;
XrHandPoseTypeInfoMSFT poseTypeCreateInfo{XR_TYPE_HAND_POSE_TYPE_INFO_MSFT};
poseTypeCreateInfo.handPoseType = XR_HAND_POSE_TYPE_TRACKED_MSFT;
for (XrHandJointMSFT joint : xr::HandJoints) {
XrHandJointSpaceCreateInfoMSFT jointCreateInfo{XR_TYPE_HAND_JOINT_SPACE_CREATE_INFO_MSFT, &poseTypeCreateInfo};
jointCreateInfo.joint = joint;
jointCreateInfo.handTracker = handData.TrackerHandle.Get();
jointCreateInfo.poseInJointSpace = xr::math::Pose::Identity();
JointData& jointData = handData.JointData[xr::JointToIndex(joint)];
CHECK_XRCMD(m_sceneContext->Extensions.xrCreateHandJointSpaceMSFT(
m_sceneContext->Session, &jointCreateInfo, jointData.JointSpace.Put()));
// Create a axis object attached to each joint space
jointData.NodeIndex = jointModel->AddNode(DirectX::XMMatrixIdentity(), Pbr::RootNodeIndex, "joint");
primitiveBuilder.AddAxis(1.0f, 0.5f, jointData.NodeIndex);
}
// Now that the axis have been added for each joint into the primitive builder,
// it can be baked into the model as a single primitive.
jointModel->AddPrimitive(Pbr::Primitive(m_sceneContext->PbrResources, primitiveBuilder, m_jointMaterial));
handData.JointModel = AddSceneObject(std::make_shared<PbrModelObject>(std::move(jointModel)));
handData.JointModel->SetVisible(false);
};
// For each hand, initialize the joint objects, hand mesh buffers and corresponding spaces.
const std::tuple<XrHandMSFT, HandData&> hands[] = {{XrHandMSFT::XR_HAND_LEFT_MSFT, m_leftHandData},
{XrHandMSFT::XR_HAND_RIGHT_MSFT, m_rightHandData}};
for (const auto& [hand, handData] : hands) {
XrHandTrackerCreateInfoMSFT createInfo{XR_TYPE_HAND_TRACKER_CREATE_INFO_MSFT};
createInfo.hand = hand;
CHECK_XRCMD(m_sceneContext->Extensions.xrCreateHandTrackerMSFT(
m_sceneContext->Session, &createInfo, handData.TrackerHandle.Put(m_sceneContext->Extensions.xrDestroyHandTrackerMSFT)));
createJointObjects(handData);
// Pre-allocate buffers for hand mesh indices and vertices
const XrSystemHandTrackingMeshPropertiesMSFT& handMeshSystemProperties = sceneContext->System.HandMeshSystemProperties;
handData.IndexBuffer = std::make_unique<uint32_t[]>(handMeshSystemProperties.maxHandMeshIndexCount);
handData.VertexBuffer = std::make_unique<XrHandMeshVertexMSFT[]>(handMeshSystemProperties.maxHandMeshVertexCount);
handData.meshState.indexBuffer.indexCapacityInput = handMeshSystemProperties.maxHandMeshIndexCount;
handData.meshState.indexBuffer.indices = handData.IndexBuffer.get();
handData.meshState.vertexBuffer.vertexCapacityInput = handMeshSystemProperties.maxHandMeshVertexCount;
handData.meshState.vertexBuffer.vertices = handData.VertexBuffer.get();
XrHandMeshSpaceCreateInfoMSFT meshSpaceCreateInfo{XR_TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT};
meshSpaceCreateInfo.handTracker = handData.TrackerHandle.Get();
meshSpaceCreateInfo.poseInHandMeshSpace = xr::math::Pose::Identity();
meshSpaceCreateInfo.handPoseType = XR_HAND_POSE_TYPE_TRACKED_MSFT;
CHECK_XRCMD(m_sceneContext->Extensions.xrCreateHandMeshSpaceMSFT(
m_sceneContext->Session, &meshSpaceCreateInfo, handData.MeshSpace.Put()));
meshSpaceCreateInfo.handPoseType = XR_HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT;
CHECK_XRCMD(m_sceneContext->Extensions.xrCreateHandMeshSpaceMSFT(
m_sceneContext->Session, &meshSpaceCreateInfo, handData.ReferenceMeshSpace.Put()));
}
// Set a clap detector that will toggle the display mode.
m_clapDetector = std::make_unique<SpaceCollider>(
SpaceCollider::Condition{m_leftHandData.JointData[xr::JointToIndex(XR_HAND_JOINT_PALM_MSFT)].JointSpace.Get(),
m_rightHandData.JointData[xr::JointToIndex(XR_HAND_JOINT_PALM_MSFT)].JointSpace.Get(),
/* DistanceTolerance */ 0.02f},
[this]() { m_mode = (HandDisplayMode)(((uint32_t)m_mode + 1) % (uint32_t)HandDisplayMode::Count); });
}
void OnUpdate(const FrameTime& frameTime) override {
// Detect hand clap to toggle hand display mode.
m_clapDetector->Update(frameTime.PredictedDisplayTime);
for (HandData& handData : {std::ref(m_leftHandData), std::ref(m_rightHandData)}) {
bool jointsVisible = m_mode == HandDisplayMode::Joints;
bool meshVisible = m_mode == HandDisplayMode::Mesh;
XrHandTrackerStateMSFT handTrackerState{XR_TYPE_HAND_TRACKER_STATE_MSFT};
CHECK_XRCMD(m_sceneContext->Extensions.xrGetHandTrackerStateMSFT(
handData.TrackerHandle.Get(), frameTime.PredictedDisplayTime, &handTrackerState));
if (!handTrackerState.isActive) {
jointsVisible = false;
meshVisible = false;
}
if (jointsVisible) {
jointsVisible = UpdateJoints(handData, m_sceneContext->SceneSpace, frameTime.PredictedDisplayTime);
}
if (meshVisible) {
meshVisible = UpdateMesh(handData, m_sceneContext->SceneSpace, frameTime.PredictedDisplayTime);
}
handData.JointModel->SetVisible(jointsVisible);
if (handData.MeshSceneObject != nullptr) { // Pbr mesh object creation is deferred.
handData.MeshSceneObject->SetVisible(meshVisible);
}
}
}
struct JointData {
xr::SpaceHandle JointSpace;
Pbr::NodeIndex_t NodeIndex;
};
struct HandData {
xr::HandTrackerHandle TrackerHandle;
// Data to display hand joints tracking
std::shared_ptr<PbrModelObject> JointModel;
std::array<JointData, xr::HandJointCount> JointData;
// Data to display hand mesh tracking
xr::SpaceHandle MeshSpace;
xr::SpaceHandle ReferenceMeshSpace;
std::vector<XMFLOAT4> VertexColors;
std::shared_ptr<PbrModelObject> MeshSceneObject;
// Data to process open-palm reference hand.
XrHandMeshMSFT meshState{XR_TYPE_HAND_MESH_MSFT};
std::unique_ptr<uint32_t[]> IndexBuffer{};
std::unique_ptr<XrHandMeshVertexMSFT[]> VertexBuffer{};
};
bool UpdateJoints(HandData& handData, XrSpace referenceSpace, XrTime time) {
bool jointsVisible = false;
XrHandJointRadiusMSFT jointRadius{XR_TYPE_HAND_JOINT_RADIUS_MSFT};
XrSpaceLocation jointLocation{XR_TYPE_SPACE_LOCATION, &jointRadius};
for (const auto& [jointSpace, nodeIndex] : handData.JointData) {
CHECK_XRCMD(xrLocateSpace(jointSpace.Get(), referenceSpace, time, &jointLocation));
if (xr::math::Pose::IsPoseValid(jointLocation)) {
Pbr::Node& jointNode = handData.JointModel->GetModel()->GetNode(nodeIndex);
const float radius = jointRadius.radius;
jointNode.SetTransform(XMMatrixScaling(radius, radius, radius) * xr::math::LoadXrPose(jointLocation.pose));
jointsVisible = true;
}
}
return jointsVisible;
}
bool UpdateMesh(HandData& handData, XrSpace referenceSpace, XrTime time) {
XrHandMeshUpdateInfoMSFT meshUpdateInfo{XR_TYPE_HAND_MESH_UPDATE_INFO_MSFT};
meshUpdateInfo.time = time;
meshUpdateInfo.handPoseType = XR_HAND_POSE_TYPE_TRACKED_MSFT;
CHECK_XRCMD(
m_sceneContext->Extensions.xrUpdateHandMeshMSFT(handData.TrackerHandle.Get(), &meshUpdateInfo, &handData.meshState));
if (!handData.meshState.isActive) {
return false;
}
bool indicesChanged = handData.meshState.indexBufferChanged;
bool verticesChanged = handData.meshState.vertexBufferChanged;
if (indicesChanged) {
// Index buffer is changed, recalculate vertices color based on neutral hand pose.
ComputeHandMeshColor(handData, time);
}
if (verticesChanged) {
Pbr::PrimitiveBuilder meshBuilder = CreateHandMeshPrimitiveBuilder(handData.meshState.indexBuffer.indices,
handData.meshState.indexBuffer.indexCountOutput,
handData.meshState.vertexBuffer.vertices,
handData.meshState.vertexBuffer.vertexCountOutput,
handData.VertexColors);
if (!handData.MeshSceneObject) {
// The hand mesh scene object doesn't exist yet and must be created.
Pbr::Primitive surfacePrimitive(
m_sceneContext->PbrResources, meshBuilder, m_meshMaterial, false /* updatableBuffers */);
auto surfaceModel = std::make_shared<Pbr::Model>();
surfaceModel->AddPrimitive(std::move(surfacePrimitive));
handData.MeshSceneObject = AddSceneObject(std::make_shared<PbrModelObject>(surfaceModel));
} else {
// Update vertices and indices of the existing hand mesh scene object's primitive.
handData.MeshSceneObject->GetModel()->GetPrimitive(0).UpdateBuffers(
m_sceneContext->Device.get(), m_sceneContext->DeviceContext.get(), meshBuilder);
}
}
if (handData.MeshSceneObject) {
XrSpaceLocation meshLocation{XR_TYPE_SPACE_LOCATION};
CHECK_XRCMD(xrLocateSpace(handData.MeshSpace.Get(), referenceSpace, time, &meshLocation));
if (xr::math::Pose::IsPoseValid(meshLocation)) {
handData.MeshSceneObject->Pose() = meshLocation.pose;
return true;
}
}
return false;
}
void ComputeHandMeshColor(HandData& handData, XrTime time) {
// Compute a color for each vertex on hand mesh based on relative position to an open palm reference hand.
// Use the middle finger tip and wrist joints to normalize the vertical range.
// Use the little finger tip and thumb tip joints to normalize the horizonal range.
XrVector3f vZero{}, vOne{}, hZero{}, hOne{};
for (const auto& [joint, jointPosition] :
std::vector<std::tuple<XrHandJointMSFT, XrVector3f&>>{{XR_HAND_JOINT_MIDDLE_TIP_MSFT, vZero},
{XR_HAND_JOINT_WRIST_MSFT, vOne},
{XR_HAND_JOINT_LITTLE_TIP_MSFT, hZero},
{XR_HAND_JOINT_THUMB_TIP_MSFT, hOne}}) {
XrHandPoseTypeInfoMSFT handPoseTypeInfo{XR_TYPE_HAND_POSE_TYPE_INFO_MSFT};
handPoseTypeInfo.handPoseType = XR_HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT;
XrHandJointSpaceCreateInfoMSFT createInfo{XR_TYPE_HAND_JOINT_SPACE_CREATE_INFO_MSFT, &handPoseTypeInfo};
createInfo.handTracker = handData.TrackerHandle.Get();
createInfo.poseInJointSpace = xr::math::Pose::Identity();
createInfo.joint = joint;
xr::SpaceHandle jointSpace;
CHECK_XRCMD(m_sceneContext->Extensions.xrCreateHandJointSpaceMSFT(m_sceneContext->Session, &createInfo, jointSpace.Put()));
XrSpaceLocation jointLocation{XR_TYPE_SPACE_LOCATION};
CHECK_XRCMD(xrLocateSpace(jointSpace.Get(), handData.ReferenceMeshSpace.Get(), time, &jointLocation));
assert(xr::math::Pose::IsPoseValid(jointLocation));
jointPosition = jointLocation.pose.position;
}
const XrHandMeshVertexBufferMSFT& vertexBuffer = handData.meshState.vertexBuffer;
handData.VertexColors.resize(vertexBuffer.vertexCountOutput);
// Calculate the normalized length of a vertex to a line segment defined by two point [zero, one].
auto weight = [](const XrVector3f& v, const XrVector3f& zero, const XrVector3f& one) -> float {
const XrVector3f dm = {one.x - zero.x, one.y - zero.y, one.z - zero.z};
const XrVector3f dv = {v.x - zero.x, v.y - zero.y, v.z - zero.z};
const float lm = dm.x * dm.x + dm.y * dm.y + dm.z * dm.z;
const float vm = dv.x * dm.x + dv.y * dm.y + dv.z * dm.z;
return std::min(1.f, std::max(0.f, vm / lm));
};
for (uint32_t i = 0; i < vertexBuffer.vertexCountOutput; i++) {
const XrVector3f& vertexPosition = vertexBuffer.vertices[i].position;
const float v = weight(vertexPosition, vZero, vOne);
const float h = weight(vertexPosition, hZero, hOne);
// Pick a simple psuedo color map to visualize figers in colors.
handData.VertexColors[i] = {v, (1 - h), h, 1};
}
}
Pbr::PrimitiveBuilder CreateHandMeshPrimitiveBuilder(uint32_t* indices,
uint32_t indexCount,
XrHandMeshVertexMSFT* vertices,
uint32_t vertexCount,
const std::vector<XMFLOAT4>& vertexColors) {
Pbr::PrimitiveBuilder builder;
builder.Vertices.resize(vertexCount);
builder.Indices = std::vector<uint32_t>(indices, indices + indexCount);
for (uint32_t i = 0; i < vertexCount; i++, vertices++) {
Pbr::Vertex& vertex = builder.Vertices[i];
vertex.Position = xr::math::cast(vertices->position);
vertex.Normal = xr::math::cast(vertices->normal);
vertex.Color0 = vertexColors[i];
bool xDominant = std::abs(vertex.Normal.x) > std::abs(vertex.Normal.y);
XMVECTOR basis = xDominant ? g_XMIdentityR1 : g_XMIdentityR0;
XMVECTOR normal = XMLoadFloat3(&vertex.Normal);
XMVECTOR tangent = XMVector3Cross(normal, basis);
XMStoreFloat4(&vertex.Tangent, tangent);
XMStoreFloat2(&vertex.TexCoord0, g_XMZero);
vertex.ModelTransformIndex = Pbr::RootNodeIndex; // Index into the node transforms
}
return builder;
}
// Detects two spaces collide to each other
class SpaceCollider {
public:
struct Condition {
XrSpace A;
XrSpace B;
float DistanceTolerance;
};
SpaceCollider() = delete;
SpaceCollider(SpaceCollider&) = delete;
SpaceCollider(SpaceCollider&&) = delete;
SpaceCollider(Condition condition, std::function<void()> callback)
: m_condition(std::move(condition))
, m_callback(callback) {
}
void Update(XrTime time) {
XrSpaceLocation location{XR_TYPE_SPACE_LOCATION};
CHECK_XRCMD(xrLocateSpace(m_condition.A, m_condition.B, time, &location));
if (xr::math::Pose::IsPoseValid(location)) {
const auto position = xr::math::LoadXrVector3(location.pose.position);
const float distance = XMVectorGetX(XMVector3Length(position));
const bool state = distance < m_condition.DistanceTolerance;
const bool trigger = lastState.has_value() && !lastState.value() && state;
lastState = state;
if (trigger) {
m_callback();
}
}
}
private:
Condition m_condition;
std::function<void()> m_callback;
std::optional<bool> lastState{};
};
enum class HandDisplayMode { Mesh, Joints, Count };
HandDisplayMode m_mode{HandDisplayMode::Mesh};
std::shared_ptr<Pbr::Material> m_meshMaterial, m_jointMaterial;
HandData m_leftHandData;
HandData m_rightHandData;
std::unique_ptr<SpaceCollider> m_clapDetector;
};
} // namespace
std::unique_ptr<Scene> CreateHandTrackingScene(SceneContext* sceneContext) {
if (!sceneContext->Extensions.SupportsHandJointTracking || !sceneContext->System.HandTrackingSystemProperties.supportsHandTracking) {
return nullptr;
}
if (!sceneContext->Extensions.SupportsHandMeshTracking || !sceneContext->System.HandMeshSystemProperties.supportsHandTrackingMesh) {
return nullptr;
}
return std::make_unique<HandTrackingScene>(sceneContext);
}

Просмотреть файл

@ -0,0 +1,71 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "PbrModelObject.h"
#include "Scene.h"
using namespace DirectX;
using namespace xr::math;
using namespace std::chrono;
using namespace std::chrono_literals;
namespace {
//
// This sample displays a simple orbit in front of the user using local reference space
// and shows how to pause the animation when the session lost focus while it continues rendering.
//
struct OrbitScene : public Scene {
OrbitScene(SceneContext* sceneContext)
: Scene(sceneContext, L"Orbit Scene", true) {
XrReferenceSpaceCreateInfo createInfo{XR_TYPE_REFERENCE_SPACE_CREATE_INFO};
createInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
createInfo.poseInReferenceSpace = Pose::Translation({0, 0, -2}); // 2 meters in front
CHECK_XRCMD(xrCreateReferenceSpace(m_sceneContext->Session, &createInfo, m_centerSpace.Put()));
m_sun = AddSceneObject(MakeSphere(m_sceneContext->PbrResources, 0.5f, 20, Pbr::FromSRGB(Colors::OrangeRed)));
m_earth = AddSceneObject(MakeSphere(m_sceneContext->PbrResources, 0.1f, 20, Pbr::FromSRGB(Colors::SeaGreen)));
m_earth->SetParent(m_sun);
}
void OnUpdate(const FrameTime& frameTime) override {
XrSpaceLocation location = {XR_TYPE_SPACE_LOCATION};
CHECK_XRCMD(xrLocateSpace(m_centerSpace.Get(), m_sceneContext->SceneSpace, frameTime.PredictedDisplayTime, &location));
if (Pose::IsPoseValid(location)) {
m_sun->Pose() = location.pose;
}
if (m_sceneContext->SessionState == XR_SESSION_STATE_FOCUSED) {
const float seconds = duration_cast<duration<float>>(frameTime.TotalElapsed).count();
const float angle = seconds * XM_PI; // half circle a second
XrVector3f earthPosition;
earthPosition.x = 0.6f * sin(angle);
earthPosition.y = 0.0f;
earthPosition.z = 0.6f * cos(angle);
m_earth->Pose().position = earthPosition;
}
}
private:
xr::SpaceHandle m_centerSpace;
std::shared_ptr<PbrModelObject> m_sun;
std::shared_ptr<PbrModelObject> m_earth;
};
} // namespace
std::unique_ptr<Scene> CreateOrbitScene(SceneContext* sceneContext) {
return std::make_unique<OrbitScene>(sceneContext);
}

Двоичные данные
samples/SampleSceneUwp/TemporaryKey.pfx Normal file

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenXR.Loader" version="1.0.6.2" targetFramework="native" />
</packages>

Просмотреть файл

@ -0,0 +1,16 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"

Просмотреть файл

@ -0,0 +1,51 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <sdkddkver.h>
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <array>
#include <atomic>
#include <chrono>
#include <chrono>
#include <exception>
#include <future>
#include <initializer_list>
#include <memory>
#include <pathcch.h>
#include <set>
#include <string>
#include <tuple>
#include <vector>
#include <d3d11_2.h>
#include <DirectXColors.h>
#define XR_USE_PLATFORM_WIN32
#define XR_USE_GRAPHICS_API_D3D11
#include <openxr/openxr.h>
#include <openxr/openxr_platform.h>
#include <XrUtility/XrError.h>
#include <XrUtility/XrMath.h>
#include <SampleShared/Trace.h>
#include <SampleShared/ScopeGuard.h>
#include <fmt/format.h>

Просмотреть файл

@ -0,0 +1,37 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "App.h"
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) {
try {
CHECK_HRCMD(::CoInitializeEx(nullptr, COINIT_MULTITHREADED));
auto on_exit = MakeScopeGuard([] { ::CoUninitialize(); });
const std::vector<const char*> requiredExtensions = {};
auto app = CreateXrApp({"SampleSceneWin32", 1}, requiredExtensions);
app->Run();
} catch (const std::exception& ex) {
sample::Trace("Unhandled Exception: {}\n", ex.what());
return 1;
} catch (...) {
sample::Trace(L"Unhandled Exception\n");
return 1;
}
return 0;
}

Просмотреть файл

@ -0,0 +1,135 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{4D888630-45DB-4CAA-8AAA-3C4CE33F90AB}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>SampleSceneWin32</RootNamespace>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<SpectreMitigation>false</SpectreMitigation>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup>
<IncludePath>$(SharedPath);$(SharedPath)\ext;$(OpenXrSdkPath)\include;$(IntDir)\CompiledShaders;$(ProjectDir)..\XrSceneLib;$(IncludePath);</IncludePath>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
<AdditionalDependencies>d3d11.lib;dxgi.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="Main.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\XrSceneLib\XrSceneLib_win32.vcxproj">
<Project>{a758af22-f54f-4c74-bf85-05a377b5892e}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<Target Name="CopyContent" AfterTargets="Build">
<ItemGroup>
<ContentFiles Include="$(SharedPath)\pbr\brdf_lut.png" />
<ContentFiles Include="$(SharedPath)\SampleShared\Sample_SpecularHDR.dds" />
<ContentFiles Include="$(SharedPath)\SampleShared\Sample_DiffuseHDR.dds" />
</ItemGroup>
<Copy DestinationFolder="$(OutDir)" SkipUnchangedFiles="True" SourceFiles="@(ContentFiles)" UseHardlinksIfPossible="True" />
</Target>
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenXR.Loader" version="1.0.6.2" targetFramework="native" />
</packages>

Просмотреть файл

@ -0,0 +1,16 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"

Просмотреть файл

@ -0,0 +1,51 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <sdkddkver.h>
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <array>
#include <atomic>
#include <chrono>
#include <chrono>
#include <exception>
#include <future>
#include <initializer_list>
#include <memory>
#include <pathcch.h>
#include <set>
#include <string>
#include <tuple>
#include <vector>
#include <d3d11_2.h>
#include <DirectXColors.h>
#define XR_USE_PLATFORM_WIN32
#define XR_USE_GRAPHICS_API_D3D11
#include <openxr/openxr.h>
#include <openxr/openxr_platform.h>
#include <XrUtility/XrError.h>
#include <XrUtility/XrMath.h>
#include <SampleShared/Trace.h>
#include <SampleShared/ScopeGuard.h>
#include <fmt/format.h>

Просмотреть файл

@ -0,0 +1,44 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "App.h"
std::unique_ptr<Scene> CreateThreeCubesScene(SceneContext* sceneContext);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) {
try {
CHECK_HRCMD(::CoInitializeEx(nullptr, COINIT_MULTITHREADED));
auto on_exit = MakeScopeGuard([] { ::CoUninitialize(); });
const std::vector<const char*> requiredExtensions = {
XR_MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME,
XR_MSFT_SPATIAL_ANCHOR_EXTENSION_NAME,
XR_MSFT_HAND_INTERACTION_PREVIEW_EXTENSION_NAME,
};
auto app = CreateXrApp({"ThreeCubesUwp", 1}, requiredExtensions);
app->AddScene(CreateThreeCubesScene(app->SceneContext()));
app->Run();
} catch (const std::exception& ex) {
sample::Trace("Unhandled Exception: {}\n", ex.what());
return 1;
} catch (...) {
sample::Trace(L"Unhandled Exception\n");
return 1;
}
return 0;
}

Просмотреть файл

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:uap2="http://schemas.microsoft.com/appx/manifest/uap/windows10/2" IgnorableNamespaces="uap mp uap2">
<Identity Name="ThreeCubesUwp" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="309c7a45-edf9-45bd-8df1-eab43feff765" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
<Properties>
<DisplayName>ThreeCubesUwp</DisplayName>
<PublisherDisplayName>Microsoft Corporation</PublisherDisplayName>
<Logo>SampleShared_uwp\UWPAssets\storelogo-sdk.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.18295.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="App.App">
<uap:VisualElements DisplayName="ThreeCubesUwp" Square150x150Logo="SampleShared_uwp\UWPAssets\squareTile-sdk.png" Square44x44Logo="SampleShared_uwp\UWPAssets\smallTile-sdk.png" Description="ThreeCubesUwp" BackgroundColor="#00B2F0">
<uap:SplashScreen Image="SampleShared_uwp\UWPAssets\splash-sdk.png" />
<uap:DefaultTile>
<uap:ShowNameOnTiles>
<uap:ShowOn Tile="square150x150Logo" />
</uap:ShowNameOnTiles>
</uap:DefaultTile>
</uap:VisualElements>
</Application>
</Applications>
<Capabilities>
<uap2:Capability Name="spatialPerception" />
</Capabilities>
</Package>

Просмотреть файл

@ -0,0 +1,234 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "PbrModelObject.h"
#include "Scene.h"
using namespace DirectX;
using namespace xr::math;
using namespace std::chrono;
using namespace std::chrono_literals;
namespace {
//
// This sample shows different tracking behaviors across local, unbounded and anchor spaces.
// The user can air-tap to create 3 cubes next to each other located precisely edge to edge when they are created.
// The red cube is locked to the local space, the green to the unbounded space, and the blue to a newly created anchor space.
// When the user walked tens of meters away and creating "three cubes" along the road,
// she/he can observe the different behaviors of different type of spaces.
// Typically each three-cubes will gradually tear apart due to different optimization of the underlying tracking techs.
//
struct ThreeCubesScene : public Scene {
ThreeCubesScene(SceneContext* sceneContext)
: Scene(sceneContext, L"Three Cubes", true) {
xr::ActionSet& actionSet =
m_sceneContext->ActionContext.CreateActionSet("three_cubes_scene_actions", "Three Cubes Scene Actions");
const std::vector<std::string> subactionPathBothHands = {"/user/hand/right", "/user/hand/left"};
m_selectAction = actionSet.CreateAction("select_action", "Select Action", XR_ACTION_TYPE_BOOLEAN_INPUT, subactionPathBothHands);
m_aimPoseAction = actionSet.CreateAction("aim_pose", "Aim Pose", XR_ACTION_TYPE_POSE_INPUT, subactionPathBothHands);
m_sceneContext->ActionContext.SuggestInteractionProfileBindings("/interaction_profiles/khr/simple_controller",
{
{m_selectAction, "/user/hand/right/input/select/click"},
{m_selectAction, "/user/hand/left/input/select/click"},
{m_aimPoseAction, "/user/hand/left/input/aim/pose"},
{m_aimPoseAction, "/user/hand/right/input/aim/pose"},
});
if (sceneContext->Extensions.SupportsHandInteraction) {
m_sceneContext->ActionContext.SuggestInteractionProfileBindings("/interaction_profiles/microsoft/hand_interaction_preview",
{
{m_selectAction, "/user/hand/left/input/select/value"},
{m_selectAction, "/user/hand/right/input/select/value"},
{m_aimPoseAction, "/user/hand/left/input/aim/pose"},
{m_aimPoseAction, "/user/hand/right/input/aim/pose"},
});
}
XrReferenceSpaceCreateInfo referenceSpaceCreateInfo{XR_TYPE_REFERENCE_SPACE_CREATE_INFO};
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
referenceSpaceCreateInfo.poseInReferenceSpace = Pose::Identity();
CHECK_XRCMD(xrCreateReferenceSpace(m_sceneContext->Session, &referenceSpaceCreateInfo, m_localSpace.Put()));
if (m_sceneContext->Extensions.SupportsUnboundedSpace) {
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_UNBOUNDED_MSFT;
CHECK_XRCMD(xrCreateReferenceSpace(m_sceneContext->Session, &referenceSpaceCreateInfo, m_unboundedSpace.Put()));
}
XrActionSpaceCreateInfo spaceCreateInfo{XR_TYPE_ACTION_SPACE_CREATE_INFO};
spaceCreateInfo.poseInActionSpace = Pose::Identity();
spaceCreateInfo.action = m_aimPoseAction;
spaceCreateInfo.poseInActionSpace = Pose::Translation({0, 0, -0.2f});
spaceCreateInfo.subactionPath = m_sceneContext->RightHand;
CHECK_XRCMD(xrCreateActionSpace(m_sceneContext->Session, &spaceCreateInfo, m_rightAimSpace.Put()));
spaceCreateInfo.subactionPath = m_sceneContext->LeftHand;
CHECK_XRCMD(xrCreateActionSpace(m_sceneContext->Session, &spaceCreateInfo, m_leftAimSpace.Put()));
m_holograms.emplace_back(m_rightAimSpace.Get(),
AddSceneObject(MakeSphere(m_sceneContext->PbrResources, 0.05f, 20, Pbr::FromSRGB(Colors::Magenta))));
m_holograms.emplace_back(m_leftAimSpace.Get(),
AddSceneObject(MakeSphere(m_sceneContext->PbrResources, 0.05f, 20, Pbr::FromSRGB(Colors::Cyan))));
}
void OnUpdate(const FrameTime& frameTime) override {
XrActionStateBoolean selectState{XR_TYPE_ACTION_STATE_BOOLEAN};
XrActionStateGetInfo getInfo{XR_TYPE_ACTION_STATE_GET_INFO};
getInfo.action = m_selectAction;
getInfo.subactionPath = m_sceneContext->RightHand;
CHECK_XRCMD(xrGetActionStateBoolean(m_sceneContext->Session, &getInfo, &selectState));
if (selectState.isActive && selectState.changedSinceLastSync && selectState.currentState) {
PlaceThreeCubes(m_rightAimSpace.Get(), selectState.lastChangeTime);
}
getInfo.subactionPath = m_sceneContext->LeftHand;
CHECK_XRCMD(xrGetActionStateBoolean(m_sceneContext->Session, &getInfo, &selectState));
if (selectState.isActive && selectState.changedSinceLastSync && selectState.currentState) {
PlaceThreeCubes(m_leftAimSpace.Get(), selectState.lastChangeTime);
}
for (auto& hologram : m_holograms) {
UpdateHologramPlacement(hologram, frameTime.PredictedDisplayTime);
}
}
private:
struct Hologram;
void UpdateHologramPlacement(Hologram& hologram, XrTime time) {
if (!hologram.Object) {
return; // no visual to update.
}
XrSpaceLocation spaceLocation{XR_TYPE_SPACE_LOCATION};
CHECK_XRCMD(xrLocateSpace(hologram.Space, m_sceneContext->SceneSpace, time, &spaceLocation));
if (Pose::IsPoseValid(spaceLocation)) {
hologram.Object->SetVisible(true);
if (hologram.Pose.has_value()) {
hologram.Object->Pose() = Pose::Multiply(hologram.Pose.value(), spaceLocation.pose);
} else {
hologram.Object->Pose() = spaceLocation.pose;
}
} else {
hologram.Object->SetVisible(false);
}
}
void PlaceThreeCubes(XrSpace space, XrTime time) {
constexpr float cubeSize = 0.05f;
constexpr XMFLOAT3 sideLength = {cubeSize, cubeSize, cubeSize};
auto createHologram = [&](XrSpace baseSpace, const Pbr::RGBAColor& color, const XrVector3f& offset) {
if (baseSpace == XR_NULL_HANDLE) {
return; // If extension is not supported, skip creating a hologram
}
XrSpaceLocation spaceLocation{XR_TYPE_SPACE_LOCATION};
CHECK_XRCMD(xrLocateSpace(space, baseSpace, time, &spaceLocation));
Hologram hologram;
hologram.Object = AddSceneObject(MakeCube(m_sceneContext->PbrResources, sideLength, color));
hologram.Space = baseSpace;
hologram.Pose = Pose::Multiply(Pose::Translation(offset), spaceLocation.pose);
m_holograms.emplace_back(std::move(hologram));
};
createHologram(m_localSpace.Get(), Pbr::FromSRGB(Colors::Red), {-cubeSize, 0, 0});
createHologram(m_unboundedSpace.Get(), Pbr::FromSRGB(Colors::Green), {cubeSize, 0, 0});
createHologram(CreateSpacialAnchorSpace(space, time), Pbr::FromSRGB(Colors::Blue), {0, 0, -cubeSize});
}
XrSpace CreateSpacialAnchorSpace(XrSpace space, XrTime time) {
if (!m_sceneContext->Extensions.SupportsSpatialAnchor) {
return XR_NULL_HANDLE; // cannot create hologram on spatial anchor.
}
AnchorSpace anchorSpace;
XrSpaceLocation spaceLocation{XR_TYPE_SPACE_LOCATION};
CHECK_XRCMD(xrLocateSpace(space, m_sceneContext->SceneSpace, time, &spaceLocation));
if (Pose::IsPoseValid(spaceLocation)) {
XrSpatialAnchorCreateInfoMSFT createInfo{XR_TYPE_SPATIAL_ANCHOR_CREATE_INFO_MSFT};
createInfo.space = m_sceneContext->SceneSpace;
createInfo.pose = spaceLocation.pose;
createInfo.time = time;
XrResult result = m_sceneContext->Extensions.xrCreateSpatialAnchorMSFT(
m_sceneContext->Session, &createInfo, anchorSpace.Anchor.Put(m_sceneContext->Extensions.xrDestroySpatialAnchorMSFT));
if (result == XR_ERROR_CREATE_SPATIAL_ANCHOR_FAILED_MSFT) {
// Cannot create spatial anchor at this place
return XR_NULL_HANDLE;
} else {
CHECK_XRRESULT(result, "xrCreateSpatialAnchorMSFT");
}
}
if (anchorSpace.Anchor) {
XrSpatialAnchorSpaceCreateInfoMSFT createInfo{XR_TYPE_SPATIAL_ANCHOR_SPACE_CREATE_INFO_MSFT};
createInfo.anchor = anchorSpace.Anchor.Get();
createInfo.poseInAnchorSpace = Pose::Identity();
CHECK_XRCMD(m_sceneContext->Extensions.xrCreateSpatialAnchorSpaceMSFT(
m_sceneContext->Session, &createInfo, anchorSpace.Space.Put()));
}
// Keep a copy of the handles to keep the anchor and space alive.
return m_anchorSpaces.emplace_back(std::move(anchorSpace)).Space.Get();
}
private:
XrAction m_selectAction{XR_NULL_HANDLE};
XrAction m_aimPoseAction{XR_NULL_HANDLE};
xr::SpaceHandle m_rightAimSpace;
xr::SpaceHandle m_leftAimSpace;
struct Hologram {
Hologram() = default;
Hologram(Hologram&) = delete;
Hologram(Hologram&&) = default;
Hologram(XrSpace space, std::shared_ptr<SceneObject> object, std::optional<XrPosef> pose = {})
: Object(std::move(object))
, Space(space)
, Pose(pose) {
}
std::shared_ptr<SceneObject> Object;
XrSpace Space = XR_NULL_HANDLE;
std::optional<XrPosef> Pose = {};
};
std::vector<Hologram> m_holograms;
xr::SpaceHandle m_unboundedSpace;
xr::SpaceHandle m_localSpace;
struct AnchorSpace {
xr::SpatialAnchorHandle Anchor;
xr::SpaceHandle Space;
};
std::vector<AnchorSpace> m_anchorSpaces;
};
} // namespace
std::unique_ptr<Scene> CreateThreeCubesScene(SceneContext* sceneContext) {
return std::make_unique<ThreeCubesScene>(sceneContext);
}

Двоичные данные
samples/ThreeCubesUwp/TemporaryKey.pfx Normal file

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,174 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM64">
<Configuration>Debug</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM64">
<Configuration>Release</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{66973A07-2499-4DB1-B16B-7558C0FC87D9}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>ThreeCubesUwp</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.17763.0</WindowsTargetPlatformMinVersion>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
<EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
<PackageCertificateThumbprint>0071016DCE22933BB0F19305D78E0794B55121C8</PackageCertificateThumbprint>
<PackageCertificateKeyFile>TemporaryKey.pfx</PackageCertificateKeyFile>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<!-- PREfast builds only compile code, not link them. Set the uwp projects to static lib to skip package generation problems. -->
<ConfigurationType Condition="'$(LinkCompiled)'!='false'">Application</ConfigurationType>
<ConfigurationType Condition="'$(LinkCompiled)'=='false'">StaticLibrary</ConfigurationType>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<SpectreMitigation>false</SpectreMitigation>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup>
<IncludePath>$(SharedPath);$(SharedPath)\ext;$(OpenXrSdkPath)\include;$(IntDir)\CompiledShaders;$(ProjectDir)..\XrSceneLib;$(IncludePath);</IncludePath>
<AppxPackageSigningEnabled>True</AppxPackageSigningEnabled>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_WINDOWS;%(PreprocessorDefinitions);UWP</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
<AdditionalDependencies>OneCore.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
</ClCompile>
<Link>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="Main.cpp" />
<ClCompile Include="Scene_ThreeCubes.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="TemporaryKey.pfx" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<None Include="$(SharedPath)\pbr\brdf_lut.png">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(SharedPath)\SampleShared\Sample_DiffuseHDR.dds">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(SharedPath)\SampleShared\Sample_SpecularHDR.dds">
<DeploymentContent>true</DeploymentContent>
</None>
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest" Condition="'$(LinkCompiled)'!='false'">
<SubType>Designer</SubType>
</AppxManifest>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\XrSceneLib\XrSceneLib_uwp.vcxproj">
<Project>{56f1c3f4-8ab3-4518-9671-aa4219f56167}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="Main.cpp" />
<ClCompile Include="pch.cpp" />
<ClCompile Include="Scene_HandTracking.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="$(SharedPath)\pbr\brdf_lut.png">
<Filter>DeploymentContent</Filter>
</None>
<None Include="$(SharedPath)\SampleShared\Sample_DiffuseHDR.dds">
<Filter>DeploymentContent</Filter>
</None>
<None Include="$(SharedPath)\SampleShared\Sample_SpecularHDR.dds">
<Filter>DeploymentContent</Filter>
</None>
<None Include="TemporaryKey.pfx" />
</ItemGroup>
<ItemGroup>
<Filter Include="DeploymentContent">
<UniqueIdentifier>{f0e9b0db-7d42-4f9e-b789-fa0c1172575c}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenXR.Loader" version="1.0.6.2" targetFramework="native" />
</packages>

Просмотреть файл

@ -0,0 +1,16 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"

Просмотреть файл

@ -0,0 +1,51 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <sdkddkver.h>
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <array>
#include <atomic>
#include <chrono>
#include <chrono>
#include <exception>
#include <future>
#include <initializer_list>
#include <memory>
#include <pathcch.h>
#include <set>
#include <string>
#include <tuple>
#include <vector>
#include <d3d11_2.h>
#include <DirectXColors.h>
#define XR_USE_PLATFORM_WIN32
#define XR_USE_GRAPHICS_API_D3D11
#include <openxr/openxr.h>
#include <openxr/openxr_platform.h>
#include <XrUtility/XrError.h>
#include <XrUtility/XrMath.h>
#include <SampleShared/Trace.h>
#include <SampleShared/ScopeGuard.h>
#include <fmt/format.h>

641
samples/XrSceneLib/App.cpp Normal file
Просмотреть файл

@ -0,0 +1,641 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include <XrUtility/XrEnumerate.h>
#include <XrUtility/XrToString.h>
#include <SampleShared/FileUtility.h>
#include <SampleShared/DxUtility.h>
#include <SampleShared/Trace.h>
#include "App.h"
#include "CompositionLayers.h"
#include "VisibilityMask.h"
#include "SceneContext.h"
using namespace DirectX;
using namespace std::chrono_literals;
namespace {
const std::vector<DXGI_FORMAT> SupportedColorSwapchainFormats = {
DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
};
const std::vector<DXGI_FORMAT> SupportedDepthSwapchainFormats = {
DXGI_FORMAT_D32_FLOAT,
DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
DXGI_FORMAT_D24_UNORM_S8_UINT,
DXGI_FORMAT_D16_UNORM,
};
const XrViewConfigurationType PrimaryViewConfiguration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
const XrViewConfigurationType MRCViewConfiguration = XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT;
const std::vector<XrViewConfigurationType> SupportedViewConfigurations = {PrimaryViewConfiguration, MRCViewConfiguration};
std::vector<XrEnvironmentBlendMode> SupportedBlendModes = {
XR_ENVIRONMENT_BLEND_MODE_ADDITIVE,
XR_ENVIRONMENT_BLEND_MODE_OPAQUE,
XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND,
};
std::vector<const char*> AppendSceneLibRequiredExtensions(const std::vector<const char*>& extensions) {
std::vector<const char*> mergedExtensions = extensions;
for (auto extension : {
XR_KHR_D3D11_ENABLE_EXTENSION_NAME,
XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME,
XR_MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME,
XR_MSFT_SECONDARY_VIEW_CONFIGURATION_PREVIEW_EXTENSION_NAME,
XR_MSFT_FIRST_PERSON_OBSERVER_PREVIEW_EXTENSION_NAME,
}) {
if (std::find(mergedExtensions.begin(), mergedExtensions.end(), extension) == mergedExtensions.end()) {
mergedExtensions.push_back(extension);
}
}
return mergedExtensions;
}
bool IsRecommendedSwapchainSizeChanged(const std::vector<XrViewConfigurationView>& oldConfigs,
const std::vector<XrViewConfigurationView>& newConfigs) {
assert(oldConfigs.size() == newConfigs.size());
for (size_t i = 0; i < oldConfigs.size(); i++) {
if ((oldConfigs[i].recommendedImageRectWidth != newConfigs[i].recommendedImageRectWidth) ||
(oldConfigs[i].recommendedImageRectHeight != newConfigs[i].recommendedImageRectHeight)) {
return true;
}
}
return false;
}
class ImplementXrApp : public XrApp {
public:
ImplementXrApp(const xr::NameVersion& appInfo, const std::vector<const char*>& extensions, bool singleThreadedGraphics);
~ImplementXrApp();
::SceneContext* SceneContext() const override {
return m_sceneContext.get();
}
void AddScene(std::unique_ptr<Scene> scene) override;
const std::vector<std::unique_ptr<Scene>>& Scenes() const override;
void Run() override;
void Stop() override;
::ProjectionLayers& ProjectionLayers() override {
return m_projectionLayerCollection;
}
private:
xr::SessionHandle m_session;
xr::SpaceHandle m_sceneSpace;
// Make sure we declare projection layers after instance to ensure projection layers are destroyed before instance
::ProjectionLayers m_projectionLayerCollection = ::ProjectionLayers([this]() {
auto ensureSwapchainFormatSupportedFunction = [&](DXGI_FORMAT format, bool isDepth) {
// Validate the app supports this format
const std::vector<DXGI_FORMAT> appSupportedFormats =
isDepth ? SupportedDepthSwapchainFormats : SupportedColorSwapchainFormats;
if ((std::find(appSupportedFormats.begin(), appSupportedFormats.end(), format) == appSupportedFormats.end())) {
throw std::runtime_error(fmt::format("Unsupported swapchain format: {}", format).c_str());
}
// Validate the runtime supports this format
const std::vector<DXGI_FORMAT> formats = {format};
const auto systemSupportedFormats = xr::EnumerateSwapchainFormats(m_session.Get());
if (format != xr::PickSwapchainFormat(systemSupportedFormats, formats)) {
throw std::runtime_error(fmt::format("Unsupported swapchain format: {}", format).c_str());
}
};
return std::make_unique<ProjectionLayer>(ensureSwapchainFormatSupportedFunction,
m_colorSwapchainFormatDefault,
m_depthSwapchainFormatDefault,
PrimaryViewConfiguration,
m_supportedSecondaryViewConfigurations);
});
std::unique_ptr<::SceneContext> m_sceneContext;
std::unique_ptr<xr::ActionContext> m_actionContext;
winrt::com_ptr<ID3D11Device> m_d3d11Device;
struct ViewConfigStates {
std::vector<XrViewConfigurationView> ViewConfigViews;
std::vector<XrView> Views;
XrEnvironmentBlendMode BlendMode;
bool Active;
};
std::unordered_map<XrViewConfigurationType, ViewConfigStates> m_viewConfigStates;
std::mutex m_sceneMutex;
std::vector<std::unique_ptr<Scene>> m_scenes;
std::function<void(XrFrameEndInfo* endFrameInfo)> m_endFrameCallback;
std::atomic<bool> m_sessionRunning{false};
std::atomic<bool> m_appLoopRunning{false};
std::thread m_renderThread;
std::atomic<bool> m_renderThreadRunning{false};
std::condition_variable m_frameReadyToRenderNotify;
bool m_frameReadyToRender{false};
FrameTime m_currentFrameTime;
DXGI_FORMAT m_colorSwapchainFormatDefault;
DXGI_FORMAT m_depthSwapchainFormatDefault;
std::unique_ptr<IVisibilityMask> m_visibilityMask;
std::vector<XrViewConfigurationType> m_supportedSecondaryViewConfigurations;
private:
bool ProcessEvents();
void StartRenderThreadIfNotRunning();
void StopRenderThreadIfRunning();
void UpdateFrame();
void RenderFrame();
void BeginSession();
void EndSession();
};
ImplementXrApp::ImplementXrApp(const xr::NameVersion& appInfo,
const std::vector<const char*>& extensions,
bool singleThreadedGraphics) {
std::vector<const char*> mergedExtensions = AppendSceneLibRequiredExtensions(extensions);
xr::InstanceContext instance(appInfo, {"XrSceneLib", 1}, mergedExtensions);
std::optional<xr::SystemContext> systemOpt;
while (!(systemOpt = instance.TryGetSystem(XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY,
XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO,
{XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT}))) {
DEBUG_PRINT("Waiting for system plugin ...");
std::this_thread::sleep_for(500ms);
}
const xr::SystemContext& system = systemOpt.value();
// Create the D3D11 device for the adapter associated with the system.
_Analysis_assume_(m_extensionContext.xrGetD3D11GraphicsRequirementsKHR != nullptr);
XrGraphicsRequirementsD3D11KHR graphicsRequirements{XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR};
CHECK_XRCMD(instance.Extensions.xrGetD3D11GraphicsRequirementsKHR(instance.Handle(), system.Id, &graphicsRequirements));
const winrt::com_ptr<IDXGIAdapter1> adapter = sample::dx::GetAdapter(graphicsRequirements.adapterLuid);
// Create a list of feature levels which are both supported by the OpenXR runtime and this application.
std::vector<D3D_FEATURE_LEVEL> featureLevels = {
D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};
featureLevels.erase(std::remove_if(std::begin(featureLevels),
std::end(featureLevels),
[&](D3D_FEATURE_LEVEL fl) { return fl < graphicsRequirements.minFeatureLevel; }),
std::end(featureLevels));
if (featureLevels.size() == 0) {
throw std::runtime_error("Unsupported minimum feature level!");
}
winrt::com_ptr<ID3D11Device> device;
winrt::com_ptr<ID3D11DeviceContext> deviceContext;
sample::dx::CreateD3D11DeviceAndContext(adapter.get(), featureLevels, singleThreadedGraphics, device.put(), deviceContext.put());
XrGraphicsBindingD3D11KHR d3d11Binding{};
d3d11Binding.type = XR_TYPE_GRAPHICS_BINDING_D3D11_KHR;
d3d11Binding.device = device.get();
XrSessionCreateInfo createInfo{XR_TYPE_SESSION_CREATE_INFO};
createInfo.next = &d3d11Binding;
createInfo.systemId = system.Id;
CHECK_XRCMD(xrCreateSession(instance.Handle(), &createInfo, m_session.Put()));
// Cache view related properties for each view config
for (const auto& [type, viewConfiguration] : system.ViewConfigurations) {
if (std::find(SupportedViewConfigurations.begin(), SupportedViewConfigurations.end(), type) ==
SupportedViewConfigurations.end()) {
continue; // Not supported by this app
}
m_viewConfigStates[type].ViewConfigViews = xr::EnumerateViewConfigurationViews(instance.Handle(), system.Id, type);
m_viewConfigStates[type].Views.resize(m_viewConfigStates[type].ViewConfigViews.size(), {XR_TYPE_VIEW});
m_viewConfigStates[type].BlendMode = xr::PickEnvironmentBlendMode(viewConfiguration.BlendModes, SupportedBlendModes);
const bool isPrimaryViewConfiguration = (type == PrimaryViewConfiguration);
m_viewConfigStates[type].Active = isPrimaryViewConfiguration; // Primary view configuration is always active
if (!isPrimaryViewConfiguration) {
m_supportedSecondaryViewConfigurations.push_back(type);
}
}
const auto systemSupportedFormats = xr::EnumerateSwapchainFormats(m_session.Get());
m_colorSwapchainFormatDefault = xr::PickSwapchainFormat(systemSupportedFormats, SupportedColorSwapchainFormats);
m_depthSwapchainFormatDefault = xr::PickSwapchainFormat(systemSupportedFormats, SupportedDepthSwapchainFormats);
// Create main app space
XrReferenceSpaceCreateInfo spaceCreateInfo{XR_TYPE_REFERENCE_SPACE_CREATE_INFO};
spaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
spaceCreateInfo.poseInReferenceSpace = xr::math::Pose::Identity();
CHECK_XRCMD(xrCreateReferenceSpace(m_session.Get(), &spaceCreateInfo, m_sceneSpace.Put()));
Pbr::Resources pbrResources = sample::InitializePbrResources(device.get());
m_actionContext = std::make_unique<xr::ActionContext>(instance.Handle());
m_sceneContext = std::make_unique<::SceneContext>(std::move(instance),
std::move(system),
m_session.Get(),
m_sceneSpace.Get(),
std::move(pbrResources),
device,
deviceContext,
*m_actionContext,
m_viewConfigStates.at(PrimaryViewConfiguration).BlendMode);
m_projectionLayerCollection.Resize(1, true /*forceReset*/);
// Only create visibility mask if app has enabled the extension
if (m_sceneContext->Extensions.SupportsVisibilityMask) {
m_visibilityMask = CreateStereoVisibilityMask(m_sceneContext.get());
}
}
ImplementXrApp::~ImplementXrApp() {
StopRenderThreadIfRunning();
{
std::lock_guard lock(m_sceneMutex);
m_scenes.clear();
}
}
void ImplementXrApp::AddScene(std::unique_ptr<Scene> scene) {
if (!scene) {
return; // Some scenes might skip creation due to extension unavailability.
}
std::lock_guard lock(m_sceneMutex);
assert(!m_appLoopRunning); // Cannot add scene after app loop is running
m_scenes.push_back(std::move(scene));
}
const std::vector<std::unique_ptr<Scene>>& ImplementXrApp::Scenes() const {
return m_scenes;
}
void ImplementXrApp::Run() {
::SetThreadDescription(::GetCurrentThread(), L"App Thread");
m_appLoopRunning = true;
m_actionContext->AttachActionsToSession(m_session.Get());
while (m_appLoopRunning) {
if (!ProcessEvents()) {
break;
}
if (m_sessionRunning) {
StartRenderThreadIfNotRunning();
UpdateFrame();
m_frameReadyToRender = true;
m_frameReadyToRenderNotify.notify_all();
} else {
std::this_thread::sleep_for(0.1s);
}
}
}
void ImplementXrApp::StartRenderThreadIfNotRunning() {
bool alreadyRunning = false;
if (m_renderThreadRunning.compare_exchange_strong(alreadyRunning, true)) {
m_renderThread = std::thread([this]() {
::SetThreadDescription(::GetCurrentThread(), L"Render Thread");
std::mutex frameReadyToRenderMutex;
std::unique_lock<std::mutex> lock(frameReadyToRenderMutex);
while (m_renderThreadRunning && m_sessionRunning) {
m_frameReadyToRenderNotify.wait(lock, [this] { return m_frameReadyToRender; });
m_frameReadyToRender = false;
if (!m_renderThreadRunning || !m_sessionRunning) {
break; // check again after waiting
}
RenderFrame();
}
});
}
}
void ImplementXrApp::StopRenderThreadIfRunning() {
bool alreadyRunning = true;
if (m_renderThreadRunning.compare_exchange_strong(alreadyRunning, false)) {
// Notify "frameReadyToRender" with "renderThreadRunning = false" to exit render thread.
m_frameReadyToRender = true;
m_frameReadyToRenderNotify.notify_all();
if (m_renderThread.joinable()) {
m_renderThread.join();
}
}
}
void ImplementXrApp::Stop() {
if (m_sessionRunning) {
CHECK_XRCMD(xrRequestExitSession(m_sceneContext->Session));
} else {
m_appLoopRunning = false; // quit app message loop
}
}
bool ImplementXrApp::ProcessEvents() {
XrEventDataBuffer eventData;
while (true) {
eventData.type = XR_TYPE_EVENT_DATA_BUFFER;
eventData.next = nullptr;
XrResult res = xrPollEvent(m_sceneContext->Instance.Handle(), &eventData);
CHECK_XRCMD(res);
if (res == XR_EVENT_UNAVAILABLE) {
return true;
} else if (eventData.type == XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED) {
auto sessionStateChanged = reinterpret_cast<XrEventDataSessionStateChanged*>(&eventData);
if (sessionStateChanged->session == m_sceneContext->Session) {
m_sceneContext->SessionState = sessionStateChanged->state;
switch (m_sceneContext->SessionState) {
case XR_SESSION_STATE_EXITING:
return false; // User's intended to quit
case XR_SESSION_STATE_LOSS_PENDING:
return false; // Runtime's intend to quit
case XR_SESSION_STATE_READY:
BeginSession();
break;
case XR_SESSION_STATE_STOPPING:
EndSession();
break;
}
}
} else if (eventData.type == XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED) {
if (m_sessionRunning) {
std::lock_guard lock(m_sceneMutex);
for (const std::unique_ptr<Scene>& scene : m_scenes) {
scene->NotifyInteractionProfileChangedEvent();
}
}
} else if (eventData.type == XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING) {
auto spaceChangingEvent = reinterpret_cast<XrEventDataReferenceSpaceChangePending*>(&eventData);
std::optional<XrPosef> pose{};
if (spaceChangingEvent->poseValid) {
pose = spaceChangingEvent->poseInPreviousSpace;
}
if (m_sessionRunning) {
std::lock_guard lock(m_sceneMutex);
for (const std::unique_ptr<Scene>& scene : m_scenes) {
scene->NotifySpaceChangingEvent(spaceChangingEvent->referenceSpaceType, spaceChangingEvent->changeTime, pose);
}
}
} else if (eventData.type == XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR) {
if (m_visibilityMask) {
auto visibilityMaskChangeEvent = reinterpret_cast<XrEventDataVisibilityMaskChangedKHR*>(&eventData);
assert(visibilityMaskChangeEvent->viewConfigurationType == XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO);
m_visibilityMask->NotifyMaskChanged(visibilityMaskChangeEvent->viewIndex);
}
}
}
}
void ImplementXrApp::BeginSession() {
XrSessionBeginInfo sessionBeginInfo{XR_TYPE_SESSION_BEGIN_INFO};
sessionBeginInfo.primaryViewConfigurationType = PrimaryViewConfiguration;
// Need this variable to be outside the scope of the if block below to be properly referenced by sessionBeginInfo.next.
// Otherwise, it gets deallocated when if block ends
XrSessionBeginSecondaryViewConfigurationInfoMSFT sessionBeginSecondaryViewConfigInfo{
XR_TYPE_SESSION_BEGIN_SECONDARY_VIEW_CONFIGURATION_INFO_MSFT,
nullptr,
(uint32_t)m_supportedSecondaryViewConfigurations.size(),
m_supportedSecondaryViewConfigurations.data()};
if (!m_supportedSecondaryViewConfigurations.empty()) {
sessionBeginInfo.next = &sessionBeginSecondaryViewConfigInfo;
}
CHECK_XRCMD(xrBeginSession(m_sceneContext->Session, &sessionBeginInfo));
m_sessionRunning = true;
}
void ImplementXrApp::EndSession() {
StopRenderThreadIfRunning();
m_sessionRunning = false;
CHECK_XRCMD(xrEndSession(m_sceneContext->Session));
}
void ImplementXrApp::UpdateFrame() {
XrFrameWaitInfo waitFrameInfo{XR_TYPE_FRAME_WAIT_INFO};
XrFrameState frameState{XR_TYPE_FRAME_STATE};
// Need these variables to be outside the scope of the if block below to be properly referenced by sessionBeginInfo.next.
// Otherwise, it gets deallocated when if block ends
std::vector<XrSecondaryViewConfigurationStateMSFT> secondaryViewConfigStateData;
for (XrViewConfigurationType type : m_supportedSecondaryViewConfigurations) {
secondaryViewConfigStateData.emplace_back(
XrSecondaryViewConfigurationStateMSFT{XR_TYPE_SECONDARY_VIEW_CONFIGURATION_STATE_MSFT, nullptr, type, XR_FALSE});
}
XrFrameSecondaryViewConfigurationsStateMSFT secondaryViewConfigStates{XR_TYPE_FRAME_SECONDARY_VIEW_CONFIGURATIONS_STATE_MSFT,
nullptr,
(uint32_t)secondaryViewConfigStateData.size(),
secondaryViewConfigStateData.data()};
if (!secondaryViewConfigStateData.empty()) {
frameState.next = &secondaryViewConfigStates;
}
CHECK_XRCMD(xrWaitFrame(m_sceneContext->Session, &waitFrameInfo, &frameState));
m_actionContext->SyncActions(m_sceneContext->Session);
{
std::lock_guard lock(m_sceneMutex);
for (const XrSecondaryViewConfigurationStateMSFT& state : secondaryViewConfigStateData) {
const bool active = static_cast<bool>(state.active);
const XrViewConfigurationType secondaryViewConfigType = state.viewConfigurationType;
if (m_viewConfigStates.at(state.viewConfigurationType).Active != active) {
sample::Trace(
"ViewConfiguration {} becomes {}\n", xr::ToString(secondaryViewConfigType), active ? "Active" : "Inactive");
if (active) {
// When a secondary view configuration is turned active, detect if recommended swapchain size is changed.
// If so, reset resources in layers related to this secondary view configuration.
std::vector<XrViewConfigurationView> newViewConfigViews = xr::EnumerateViewConfigurationViews(
m_sceneContext->Instance.Handle(), m_sceneContext->System.Id, secondaryViewConfigType);
if (IsRecommendedSwapchainSizeChanged(m_viewConfigStates.at(secondaryViewConfigType).ViewConfigViews,
newViewConfigViews)) {
m_projectionLayerCollection.ForEachLayerWithLock(
[secondaryViewConfigType](auto&& layer) { layer.Config(secondaryViewConfigType).ForceReset = true; });
m_viewConfigStates.at(secondaryViewConfigType).ViewConfigViews = newViewConfigViews;
}
}
m_viewConfigStates[state.viewConfigurationType].Active = active;
}
}
m_currentFrameTime.Update(frameState);
for (auto& scene : m_scenes) {
if (scene->IsActive()) {
scene->Update(m_currentFrameTime);
}
}
m_projectionLayerCollection.ForEachLayerWithLock([this](auto&& layer) {
for (auto& [viewConfigType, states] : m_viewConfigStates) {
layer.PrepareRendering(m_sceneContext.get(), viewConfigType, states.ViewConfigViews, states.Active);
}
});
}
}
void ImplementXrApp::RenderFrame() {
XrFrameBeginInfo beginFrameDescription{XR_TYPE_FRAME_BEGIN_INFO};
CHECK_XRCMD(xrBeginFrame(m_sceneContext->Session, &beginFrameDescription));
size_t viewConfigCount = 1 + m_supportedSecondaryViewConfigurations.size();
std::vector<CompositionLayers> layersForAllViewConfigs(viewConfigCount); // Need same lifetime as XrFrameEndInfo;
XrFrameEndInfo endFrameInfo{XR_TYPE_FRAME_END_INFO};
endFrameInfo.environmentBlendMode = m_sceneContext->PrimaryViewConfigEnvironmentBlendMode;
endFrameInfo.displayTime = m_currentFrameTime.PredictedDisplayTime;
std::vector<XrViewConfigurationType> allViewConfigurationTypes{PrimaryViewConfiguration};
std::vector<XrSecondaryViewConfigurationLayerInfoMSFT> secondaryViewConfigLayerInfos;
for (XrViewConfigurationType viewConfigurationType : m_supportedSecondaryViewConfigurations) {
secondaryViewConfigLayerInfos.emplace_back(
XrSecondaryViewConfigurationLayerInfoMSFT{XR_TYPE_SECONDARY_VIEW_CONFIGURATION_LAYER_INFO_MSFT,
nullptr,
viewConfigurationType,
m_viewConfigStates.at(viewConfigurationType).BlendMode});
allViewConfigurationTypes.push_back(viewConfigurationType);
}
assert(allViewConfigurationTypes.size() == secondaryViewConfigLayerInfos.size() + 1 &&
allViewConfigurationTypes.size() == viewConfigCount);
// Need same lifetime as XrFrameEndInfo
const XrFrameEndSecondaryViewConfigurationInfoMSFT frameEndSecondaryViewConfigInfo{
XR_TYPE_FRAME_END_SECONDARY_VIEW_CONFIGURATION_INFO_MSFT,
nullptr,
(uint32_t)secondaryViewConfigLayerInfos.size(),
secondaryViewConfigLayerInfos.data()};
if (!secondaryViewConfigLayerInfos.empty()) {
endFrameInfo.next = &frameEndSecondaryViewConfigInfo;
}
if (m_currentFrameTime.ShouldRender) {
for (size_t i = 0; i < viewConfigCount; i++) {
const XrViewConfigurationType viewConfigurationType = allViewConfigurationTypes.at(i);
CompositionLayers& layers = layersForAllViewConfigs.at(i);
ViewConfigStates& states = m_viewConfigStates.at(viewConfigurationType);
// Guarding states.Active change and swapchain creation as a result in UpdateFrame()
std::lock_guard sceneLock(m_sceneMutex);
if (states.Active) {
XrViewLocateInfo viewLocateInfo{XR_TYPE_VIEW_LOCATE_INFO};
viewLocateInfo.viewConfigurationType = viewConfigurationType;
viewLocateInfo.displayTime = m_currentFrameTime.PredictedDisplayTime;
viewLocateInfo.space = m_sceneContext->SceneSpace;
uint32_t viewCount = 0;
XrViewState viewState{XR_TYPE_VIEW_STATE};
std::vector<XrView>& views = states.Views;
CHECK_XRCMD(xrLocateViews(
m_sceneContext->Session, &viewLocateInfo, &viewState, (uint32_t)views.size(), &viewCount, views.data()));
if (xr::math::Pose::IsPoseValid(viewState)) {
std::vector<std::shared_ptr<QuadLayerObject>> underlays, overlays;
{
// Collect all quad layers in active scenes
for (const std::unique_ptr<Scene>& scene : m_scenes) {
if (!scene->IsActive()) {
continue;
}
for (const std::shared_ptr<QuadLayerObject>& quad : scene->GetQuadLayerObjects()) {
if (!quad->IsRenderable()) {
continue;
}
if (quad->LayerGroup == LayerGrouping::Underlay) {
underlays.push_back(quad);
} else if (quad->LayerGroup == LayerGrouping::Overlay) {
overlays.push_back(quad);
}
}
}
}
for (const std::shared_ptr<QuadLayerObject>& quad : underlays) {
AppendQuadLayer(layers, quad.get());
}
m_projectionLayerCollection.ForEachLayerWithLock(
[this, &layers, &views, viewConfigurationType](ProjectionLayer& projectionLayer) {
const bool shouldSubmitProjectionLayer = projectionLayer.Render(m_sceneContext.get(),
m_currentFrameTime,
m_sceneContext->SceneSpace,
views,
m_scenes,
m_visibilityMask.get(),
viewConfigurationType);
// Create the multi projection layer
if (shouldSubmitProjectionLayer) {
AppendProjectionLayer(layers, &projectionLayer, viewConfigurationType);
}
});
for (const std::shared_ptr<QuadLayerObject>& quad : overlays) {
AppendQuadLayer(layers, quad.get());
}
}
if (viewConfigurationType == PrimaryViewConfiguration) {
endFrameInfo.layerCount = layers.LayerCount();
endFrameInfo.layers = layers.LayerData();
} else {
const size_t layerIndex = i - 1;
secondaryViewConfigLayerInfos.at(layerIndex).layerCount = layers.LayerCount();
secondaryViewConfigLayerInfos.at(layerIndex).layers = layers.LayerData();
}
}
}
}
if (m_endFrameCallback) {
m_endFrameCallback(&endFrameInfo);
}
CHECK_XRCMD(xrEndFrame(m_sceneContext->Session, &endFrameInfo));
}
} // namespace
std::unique_ptr<XrApp> CreateXrApp(const xr::NameVersion& appInfo,
const std::vector<const char*>& extensions,
bool singleThreadedGraphics) {
return std::make_unique<ImplementXrApp>(appInfo, extensions, singleThreadedGraphics);
}

41
samples/XrSceneLib/App.h Normal file
Просмотреть файл

@ -0,0 +1,41 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include "Scene.h"
#include "SceneContext.h"
#include "ProjectionLayer.h"
class XrApp {
public:
virtual ~XrApp() = default;
virtual SceneContext* SceneContext() const = 0;
virtual void AddScene(std::unique_ptr<Scene> scene) = 0;
virtual const std::vector<std::unique_ptr<Scene>>& Scenes() const = 0;
virtual void Run() = 0;
virtual void Stop() = 0;
virtual ProjectionLayers& ProjectionLayers() = 0;
};
std::unique_ptr<XrApp> CreateXrApp(const xr::NameVersion& appInfo,
const std::vector<const char*>& extensions,
bool singleThreadedGraphics = false);

Просмотреть файл

@ -0,0 +1,56 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
struct QuadLayerObject;
class ProjectionLayer;
class CompositionLayers;
void AppendQuadLayer(CompositionLayers& layers, QuadLayerObject* quad);
void AppendProjectionLayer(CompositionLayers& layers, const ProjectionLayer* layer, XrViewConfigurationType type);
class CompositionLayers {
public:
XrCompositionLayerQuad& AddQuadLayer() {
XrCompositionLayerQuad& quadLayer = m_quadLayers.emplace_back();
quadLayer.type = XR_TYPE_COMPOSITION_LAYER_QUAD;
m_compositionLayers.push_back(reinterpret_cast<const XrCompositionLayerBaseHeader*>(&quadLayer));
return m_quadLayers.back();
}
XrCompositionLayerProjection& AddProjectionLayer(XrCompositionLayerFlags layerFlags) {
XrCompositionLayerProjection& projectionLayer = m_projectionLayers.emplace_back();
projectionLayer.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION;
projectionLayer.layerFlags = layerFlags;
m_compositionLayers.push_back(reinterpret_cast<const XrCompositionLayerBaseHeader*>(&projectionLayer));
return m_projectionLayers.back();
}
uint32_t LayerCount() const {
return (uint32_t)m_compositionLayers.size();
}
const XrCompositionLayerBaseHeader* const* LayerData() const {
return m_compositionLayers.data();
}
private:
std::list<XrCompositionLayerQuad> m_quadLayers;
std::list<XrCompositionLayerProjection> m_projectionLayers;
std::vector<XrCompositionLayerBaseHeader const*> m_compositionLayers;
};

Просмотреть файл

@ -0,0 +1,43 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
// Information of frame timing
struct FrameTime {
using clock = std::chrono::high_resolution_clock;
uint64_t FrameIndex = 0;
const clock::time_point StartTime = clock::now();
clock::time_point Now = StartTime;
clock::duration Elapsed = {};
clock::duration TotalElapsed = {};
XrTime PredictedDisplayTime = {};
XrDuration PredictedDisplayPeriod = {};
bool ShouldRender = {};
void Update(const XrFrameState& frameState) {
FrameIndex++;
PredictedDisplayTime = frameState.predictedDisplayTime;
PredictedDisplayPeriod = frameState.predictedDisplayPeriod;
ShouldRender = frameState.shouldRender;
const auto now = FrameTime::clock::now();
Elapsed = now - Now;
TotalElapsed = now - StartTime;
Now = now;
}
};

Просмотреть файл

@ -0,0 +1,105 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include <pbr/PbrModel.h>
#include "PbrModelObject.h"
using namespace DirectX;
PbrModelObject::PbrModelObject(std::shared_ptr<Pbr::Model> pbrModel, Pbr::ShadingMode shadingMode, Pbr::FillMode fillMode)
: m_pbrModel(std::move(pbrModel))
, m_shadingMode(shadingMode)
, m_fillMode(fillMode) {
}
void PbrModelObject::SetModel(std::shared_ptr<Pbr::Model> model) {
m_pbrModel = std::move(model);
}
std::shared_ptr<Pbr::Model> PbrModelObject::GetModel() const {
return m_pbrModel;
}
void PbrModelObject::Render(SceneContext& sceneContext) const {
if (!IsVisible() || !m_pbrModel) {
return;
}
sceneContext.PbrResources.SetShadingMode(m_shadingMode);
sceneContext.PbrResources.SetFillMode(m_fillMode);
sceneContext.PbrResources.SetModelToWorld(WorldTransform(), sceneContext.DeviceContext.get());
sceneContext.PbrResources.Bind(sceneContext.DeviceContext.get());
m_pbrModel->Render(sceneContext.PbrResources, sceneContext.DeviceContext.get());
}
void PbrModelObject::SetShadingMode(const Pbr::ShadingMode& shadingMode) {
m_shadingMode = shadingMode;
}
void PbrModelObject::SetFillMode(const Pbr::FillMode& fillMode) {
m_fillMode = fillMode;
}
void PbrModelObject::SetBaseColorFactor(const Pbr::RGBAColor color) {
for (uint32_t k = 0; k < GetModel()->GetPrimitiveCount(); k++) {
auto& material = GetModel()->GetPrimitive(k).GetMaterial();
material->Parameters().BaseColorFactor = color;
}
}
std::shared_ptr<PbrModelObject> MakeCube(const Pbr::Resources& pbrResources,
XMFLOAT3 sideLengths,
const Pbr::RGBAColor color,
float roughness /*= 1.0f*/,
float metallic /*= 0.0f*/) {
auto material = Pbr::Material::CreateFlat(pbrResources, color, roughness, metallic);
auto cubeModel = std::make_shared<Pbr::Model>();
cubeModel->AddPrimitive(Pbr::Primitive(pbrResources, Pbr::PrimitiveBuilder().AddCube(sideLengths), std::move(material)));
return std::make_shared<PbrModelObject>(std::move(cubeModel));
}
std::shared_ptr<PbrModelObject> MakeQuad(const Pbr::Resources& pbrResources,
XMFLOAT2 sideLengths,
std::shared_ptr<Pbr::Material> material) {
auto quadModel = std::make_shared<Pbr::Model>();
quadModel->AddPrimitive(Pbr::Primitive(pbrResources, Pbr::PrimitiveBuilder().AddQuad(sideLengths), std::move(material)));
return std::make_shared<PbrModelObject>(std::move(quadModel));
}
std::shared_ptr<PbrModelObject> MakeSphere(const Pbr::Resources& pbrResources,
float size,
uint32_t tesselation,
Pbr::RGBAColor color,
float roughness /*= 1.0f*/,
float metallic /*= 0.0f*/) {
auto material = Pbr::Material::CreateFlat(pbrResources, color, roughness, metallic);
auto sphereModel = std::make_shared<Pbr::Model>();
sphereModel->AddPrimitive(Pbr::Primitive(pbrResources, Pbr::PrimitiveBuilder().AddSphere(size, tesselation), std::move(material)));
return std::make_shared<PbrModelObject>(std::move(sphereModel));
}
std::shared_ptr<PbrModelObject> MakeAxis(const Pbr::Resources& pbrResources,
float axisLength /*= 1.0f*/,
float axisThickness /*= 0.01f*/,
float roughness /*= 0.85f*/,
float metallic /*= 0.01f*/) {
auto material = Pbr::Material::CreateFlat(pbrResources, Pbr::RGBA::White, roughness, metallic);
auto axisModel = std::make_shared<Pbr::Model>();
axisModel->AddPrimitive(Pbr::Primitive(pbrResources, Pbr::PrimitiveBuilder().AddAxis(axisLength, axisThickness), material));
return std::make_shared<PbrModelObject>(std::move(axisModel));
}

Просмотреть файл

@ -0,0 +1,65 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include "Scene.h"
#include "SceneContext.h"
#include <pbr/PbrModel.h>
#include <pbr/PbrMaterial.h>
class PbrModelObject : public SceneObject {
public:
PbrModelObject(std::shared_ptr<Pbr::Model> pbrModel = nullptr,
Pbr::ShadingMode shadingMode = Pbr::ShadingMode::Regular,
Pbr::FillMode fillMode = Pbr::FillMode::Solid);
void SetModel(std::shared_ptr<Pbr::Model> model);
std::shared_ptr<Pbr::Model> GetModel() const;
void SetShadingMode(const Pbr::ShadingMode& shadingMode);
void SetFillMode(const Pbr::FillMode& fillMode);
void SetBaseColorFactor(Pbr::RGBAColor color);
void Render(SceneContext& sceneContext) const override;
private:
std::shared_ptr<Pbr::Model> m_pbrModel;
Pbr::ShadingMode m_shadingMode;
Pbr::FillMode m_fillMode;
};
std::shared_ptr<PbrModelObject> MakeCube(const Pbr::Resources& pbrResources,
DirectX::XMFLOAT3 sideLengths,
Pbr::RGBAColor color,
float roughness = 1.0f,
float metallic = 0.0f);
std::shared_ptr<PbrModelObject> MakeQuad(const Pbr::Resources& pbrResources,
DirectX::XMFLOAT2 sideLengths,
std::shared_ptr<Pbr::Material> material);
std::shared_ptr<PbrModelObject> MakeSphere(const Pbr::Resources& pbrResources,
float size,
uint32_t tesselation,
Pbr::RGBAColor color,
float roughness = 1.0f,
float metallic = 0.0f);
std::shared_ptr<PbrModelObject> MakeAxis(const Pbr::Resources& pbrResources,
float axisLength = 1.0f,
float axisThickness = 0.01f,
float roughness = 0.85f,
float metallic = 0.01f);

Просмотреть файл

@ -0,0 +1,388 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "Scene.h"
#include "ProjectionLayer.h"
#include "CompositionLayers.h"
#include "SceneContext.h"
#include "VisibilityMask.h"
#include <SampleShared/DxUtility.h>
#include <SampleShared/Trace.h>
#include <XrUtility/XrMath.h>
using namespace DirectX;
ProjectionLayer::ProjectionLayer(std::function<void(DXGI_FORMAT, bool /*isDepth*/)> ensureSupportSwapchainFormat,
DXGI_FORMAT colorSwapchainFormat,
DXGI_FORMAT depthSwapchainFormat,
XrViewConfigurationType primaryViewConfiguraionType,
const std::vector<XrViewConfigurationType>& secondaryViewConfiguraionTypes)
: m_ensureSupportSwapchainFormat(ensureSupportSwapchainFormat) {
m_defaultViewConfigurationType = primaryViewConfiguraionType;
m_viewConfigComponents[primaryViewConfiguraionType].PendingConfig.ColorSwapchainFormat = colorSwapchainFormat;
m_viewConfigComponents[primaryViewConfiguraionType].PendingConfig.DepthSwapchainFormat = depthSwapchainFormat;
for (const XrViewConfigurationType type : secondaryViewConfiguraionTypes) {
m_viewConfigComponents[type].PendingConfig.ColorSwapchainFormat = colorSwapchainFormat;
m_viewConfigComponents[type].PendingConfig.DepthSwapchainFormat = depthSwapchainFormat;
if (type == XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT) {
m_viewConfigComponents[type].PendingConfig.LayerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
}
}
}
void ProjectionLayer::PrepareRendering(const SceneContext* sceneContext,
XrViewConfigurationType viewConfigType,
const std::vector<XrViewConfigurationView>& viewConfigViews,
bool canCreateSwapchain) {
ViewConfigComponent& viewConfigComponent = m_viewConfigComponents.at(viewConfigType);
ProjectionLayerConfig& layerPendingConfig = viewConfigComponent.PendingConfig;
ProjectionLayerConfig& layerCurrentConfig = viewConfigComponent.CurrentConfig;
bool shouldResetSwapchain = layerPendingConfig.ForceReset || layerCurrentConfig.DoubleWideMode != layerPendingConfig.DoubleWideMode ||
layerCurrentConfig.SwapchainSampleCount != layerPendingConfig.SwapchainSampleCount ||
layerCurrentConfig.SwapchainSizeScale.width != layerPendingConfig.SwapchainSizeScale.width ||
layerCurrentConfig.SwapchainSizeScale.height != layerPendingConfig.SwapchainSizeScale.height ||
layerCurrentConfig.ContentProtected != layerPendingConfig.ContentProtected;
if (layerCurrentConfig.ColorSwapchainFormat != layerPendingConfig.ColorSwapchainFormat) {
m_ensureSupportSwapchainFormat(layerPendingConfig.ColorSwapchainFormat, false /*isDepth*/);
shouldResetSwapchain = true;
}
if (layerCurrentConfig.DepthSwapchainFormat != layerPendingConfig.DepthSwapchainFormat) {
m_ensureSupportSwapchainFormat(layerPendingConfig.DepthSwapchainFormat, true /*isDepth*/);
shouldResetSwapchain = true;
}
if (!viewConfigComponent.ColorSwapchain.Handle || !viewConfigComponent.DepthSwapchain.Handle) {
shouldResetSwapchain = true;
}
layerPendingConfig.ForceReset = false;
layerCurrentConfig = layerPendingConfig;
// SceneLib only supports identical sized swapchain images for left and right eyes (texture array/double wide).
// Thus if runtime gives us different image rect sizes for left/right eyes,
// we use the maximum left/right imageRect extent for recommendedImageRectExtent
assert(!viewConfigViews.empty());
uint32_t recommendedImageRectWidth = 0;
uint32_t recommendedImageRectHeight = 0;
for (const XrViewConfigurationView& view : viewConfigViews) {
recommendedImageRectWidth = std::max(recommendedImageRectWidth, view.recommendedImageRectWidth);
recommendedImageRectHeight = std::max(recommendedImageRectHeight, view.recommendedImageRectHeight);
}
assert(recommendedImageRectWidth != 0 && recommendedImageRectHeight != 0);
uint32_t swapchainImageWidth =
static_cast<uint32_t>(std::ceil(recommendedImageRectWidth * layerCurrentConfig.SwapchainSizeScale.width));
uint32_t swapchainImageHeight =
static_cast<uint32_t>(std::ceil(recommendedImageRectHeight * layerCurrentConfig.SwapchainSizeScale.height));
const uint32_t swapchainSampleCount = layerCurrentConfig.SwapchainSampleCount < 1
? viewConfigViews[xr::StereoView::Left].recommendedSwapchainSampleCount
: layerCurrentConfig.SwapchainSampleCount;
viewConfigComponent.Viewports.resize(viewConfigViews.size());
for (uint32_t viewIndex = 0; viewIndex < (uint32_t)viewConfigViews.size(); viewIndex++) {
viewConfigComponent.Viewports[viewIndex] = CD3D11_VIEWPORT(
layerCurrentConfig.DoubleWideMode ? static_cast<float>(swapchainImageWidth * viewIndex + layerCurrentConfig.ViewportOffset.x)
: static_cast<float>(layerCurrentConfig.ViewportOffset.x),
static_cast<float>(layerCurrentConfig.ViewportOffset.y),
static_cast<float>(swapchainImageWidth * layerCurrentConfig.ViewportSizeScale.width),
static_cast<float>(swapchainImageHeight * layerCurrentConfig.ViewportSizeScale.height));
const int32_t doubleWideOffsetX = static_cast<int32_t>(swapchainImageWidth * viewIndex);
const XrOffset2Di colorImageRectForDoubleWide = {doubleWideOffsetX + layerCurrentConfig.ColorLayerOffset.x,
layerCurrentConfig.ColorLayerOffset.y};
viewConfigComponent.LayerColorImageRect[viewIndex] = {
layerCurrentConfig.DoubleWideMode ? colorImageRectForDoubleWide : layerCurrentConfig.ColorLayerOffset,
{static_cast<int32_t>(std::ceil(swapchainImageWidth * layerCurrentConfig.ColorLayerSizeScale.width)),
static_cast<int32_t>(std::ceil(swapchainImageHeight * layerCurrentConfig.ColorLayerSizeScale.height))}};
const XrOffset2Di depthImageRectForDoubleWide = {doubleWideOffsetX + layerCurrentConfig.DepthLayerOffset.x,
layerCurrentConfig.DepthLayerOffset.y};
viewConfigComponent.LayerDepthImageRect[viewIndex] = {
layerCurrentConfig.DoubleWideMode ? depthImageRectForDoubleWide : layerCurrentConfig.DepthLayerOffset,
{static_cast<int32_t>(std::ceil(swapchainImageWidth * layerCurrentConfig.DepthLayerSizeScale.width)),
static_cast<int32_t>(std::ceil(swapchainImageHeight * layerCurrentConfig.DepthLayerSizeScale.height))}};
}
if (!shouldResetSwapchain || !canCreateSwapchain) {
return;
}
const uint32_t wideScale = layerCurrentConfig.DoubleWideMode ? 2 : 1;
const uint32_t arrayLength = layerCurrentConfig.DoubleWideMode ? 1 : (uint32_t)viewConfigViews.size();
// Create color swapchain with recommended properties.
viewConfigComponent.ColorSwapchain =
sample::dx::CreateSwapchainD3D11(sceneContext->Session,
layerCurrentConfig.ColorSwapchainFormat,
swapchainImageWidth * wideScale,
swapchainImageHeight,
arrayLength,
swapchainSampleCount,
layerCurrentConfig.ContentProtected ? XR_SWAPCHAIN_CREATE_PROTECTED_CONTENT_BIT : 0,
XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT,
viewConfigType);
// Create depth swapchain with recommended properties.
viewConfigComponent.DepthSwapchain =
sample::dx::CreateSwapchainD3D11(sceneContext->Session,
layerCurrentConfig.DepthSwapchainFormat,
swapchainImageWidth * wideScale,
swapchainImageHeight,
arrayLength,
swapchainSampleCount,
layerCurrentConfig.ContentProtected ? XR_SWAPCHAIN_CREATE_PROTECTED_CONTENT_BIT : 0,
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
viewConfigType);
{
CD3D11_DEPTH_STENCIL_DESC depthStencilDesc(CD3D11_DEFAULT{});
depthStencilDesc.DepthEnable = false;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_REPLACE; // Set stencil buffer to ref val on succeeded pixels
m_noDepthWithStencilWrite = nullptr;
CHECK_HRCMD(sceneContext->Device->CreateDepthStencilState(&depthStencilDesc, m_noDepthWithStencilWrite.put()));
// Pass stencil test if stencil buffer's value == ref value; do not modify stencil buffer
const D3D11_DEPTH_STENCILOP_DESC stencilTestOp = {
D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_COMPARISON_EQUAL};
depthStencilDesc.StencilEnable = true;
depthStencilDesc.DepthEnable = true;
depthStencilDesc.FrontFace = stencilTestOp;
m_forwardZWithStencilTest = nullptr;
CHECK_HRCMD(sceneContext->Device->CreateDepthStencilState(&depthStencilDesc, m_forwardZWithStencilTest.put()));
depthStencilDesc.StencilEnable = false;
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_GREATER;
m_reversedZDepthNoStencilTest = nullptr;
CHECK_HRCMD(sceneContext->Device->CreateDepthStencilState(&depthStencilDesc, m_reversedZDepthNoStencilTest.put()));
depthStencilDesc.StencilEnable = true;
m_reversedZDepthWithStencilTest = nullptr;
CHECK_HRCMD(sceneContext->Device->CreateDepthStencilState(&depthStencilDesc, m_reversedZDepthWithStencilTest.put()));
}
viewConfigComponent.ProjectionViews.resize(viewConfigViews.size());
viewConfigComponent.DepthElements.resize(viewConfigViews.size());
}
bool ProjectionLayer::Render(SceneContext* sceneContext,
const FrameTime& frameTime,
XrSpace layerSpace,
const std::vector<XrView>& views,
const std::vector<std::unique_ptr<Scene>>& activeScenes,
const IVisibilityMask* visibilityMask,
XrViewConfigurationType viewConfig) {
if (m_pause) {
return true; // submit previous frame.
}
ViewConfigComponent& viewConfigComponent = m_viewConfigComponents.at(viewConfig);
const sample::dx::SwapchainD3D11& colorSwapchain = viewConfigComponent.ColorSwapchain;
const sample::dx::SwapchainD3D11& depthSwapchain = viewConfigComponent.DepthSwapchain;
std::vector<XrCompositionLayerProjectionView>& projectionViews = viewConfigComponent.ProjectionViews;
std::vector<XrCompositionLayerDepthInfoKHR>& depthElements = viewConfigComponent.DepthElements;
std::vector<D3D11_VIEWPORT>& viewports = viewConfigComponent.Viewports;
const ProjectionLayerConfig& currentConfig = viewConfigComponent.CurrentConfig;
bool submitProjectionLayer = false;
const XrSwapchainImageAcquireInfo acquireInfo{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
uint32_t colorSwapchainImageIndex{};
CHECK_XRCMD(xrAcquireSwapchainImage(colorSwapchain.Handle.Get(), &acquireInfo, &colorSwapchainImageIndex));
uint32_t depthSwapchainImageIndex{};
CHECK_XRCMD(xrAcquireSwapchainImage(depthSwapchain.Handle.Get(), &acquireInfo, &depthSwapchainImageIndex));
XrSwapchainImageWaitInfo waitInfo{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO};
waitInfo.timeout = XR_INFINITE_DURATION;
const XrResult colorSwapchainWait = CHECK_XRCMD(xrWaitSwapchainImage(colorSwapchain.Handle.Get(), &waitInfo));
const XrResult depthSwapchainWait = CHECK_XRCMD(xrWaitSwapchainImage(depthSwapchain.Handle.Get(), &waitInfo));
if ((colorSwapchainWait != XR_SUCCESS) || (depthSwapchainWait != XR_SUCCESS)) {
// Swapchain image timeout, don't submit this multi projection layer
submitProjectionLayer = false;
} else {
const uint32_t viewCount = (uint32_t)views.size();
for (uint32_t viewIndex = 0; viewIndex < viewCount; viewIndex++) {
const XrView& projection = views[viewIndex];
XrFovf fov;
fov.angleLeft = projection.fov.angleLeft * currentConfig.FovScale.angleLeft;
fov.angleRight = projection.fov.angleRight * currentConfig.FovScale.angleRight;
fov.angleUp = projection.fov.angleUp * currentConfig.FovScale.angleUp;
fov.angleDown = projection.fov.angleDown * currentConfig.FovScale.angleDown;
viewConfigComponent.LayerSpace = layerSpace;
projectionViews[viewIndex] = {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW};
projectionViews[viewIndex].pose = xr::math::Pose::Multiply(projection.pose, currentConfig.ViewPoseOffsets[viewIndex]);
projectionViews[viewIndex].fov.angleLeft = fov.angleLeft * currentConfig.SwapchainFovScale.width;
projectionViews[viewIndex].fov.angleRight = fov.angleRight * currentConfig.SwapchainFovScale.width;
projectionViews[viewIndex].fov.angleUp = fov.angleUp * currentConfig.SwapchainFovScale.height;
projectionViews[viewIndex].fov.angleDown = fov.angleDown * currentConfig.SwapchainFovScale.height;
projectionViews[viewIndex].subImage.swapchain = colorSwapchain.Handle.Get();
projectionViews[viewIndex].subImage.imageArrayIndex =
currentConfig.DoubleWideMode ? 0 : currentConfig.ColorImageArrayIndices[viewIndex];
projectionViews[viewIndex].subImage.imageRect = viewConfigComponent.LayerColorImageRect[viewIndex];
uint32_t depthImageArrayIndex = currentConfig.DoubleWideMode ? 0 : currentConfig.DepthImageArrayIndices[viewIndex];
D3D11_VIEWPORT viewport = viewports[viewIndex];
if (currentConfig.IgnoreDepthLayer) {
projectionViews[viewIndex].next = nullptr;
} else {
depthElements[viewIndex] = {XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR};
depthElements[viewIndex].minDepth = viewport.MinDepth = currentConfig.minDepth;
depthElements[viewIndex].maxDepth = viewport.MaxDepth = currentConfig.maxDepth;
depthElements[viewIndex].nearZ = currentConfig.NearFar.Near;
depthElements[viewIndex].farZ = currentConfig.NearFar.Far;
depthElements[viewIndex].subImage.swapchain = depthSwapchain.Handle.Get();
depthElements[viewIndex].subImage.imageArrayIndex = depthImageArrayIndex;
depthElements[viewIndex].subImage.imageRect = viewConfigComponent.LayerDepthImageRect[viewIndex];
projectionViews[viewIndex].next = &depthElements[viewIndex];
}
// Render for this view pose.
{
// Set the Viewport.
sceneContext->DeviceContext->RSSetViewports(1, &viewport);
const uint32_t firstArraySliceForColor = projectionViews[viewIndex].subImage.imageArrayIndex;
// Create a render target view into the appropriate slice of the color texture from this swapchain image.
// This is a lightweight operation which can be done for each viewport projection.
winrt::com_ptr<ID3D11RenderTargetView> renderTargetView;
const CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc(
currentConfig.SwapchainSampleCount > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY : D3D11_RTV_DIMENSION_TEXTURE2DARRAY,
currentConfig.ColorSwapchainFormat,
0 /* mipSlice */,
firstArraySliceForColor,
1 /* arraySize */);
CHECK_HRCMD(sceneContext->Device->CreateRenderTargetView(
colorSwapchain.Images[colorSwapchainImageIndex].texture, &renderTargetViewDesc, renderTargetView.put()));
const uint32_t firstArraySliceForDepth = depthImageArrayIndex;
// Create a depth stencil view into the slice of the depth stencil texture array for this swapchain image.
// This is a lightweight operation which can be done for each viewport projection.
winrt::com_ptr<ID3D11DepthStencilView> depthStencilView;
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(
currentConfig.SwapchainSampleCount > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY : D3D11_DSV_DIMENSION_TEXTURE2DARRAY,
currentConfig.DepthSwapchainFormat,
0 /* mipSlice */,
firstArraySliceForDepth,
1 /* arraySize */);
CHECK_HRCMD(sceneContext->Device->CreateDepthStencilView(
depthSwapchain.Images[depthSwapchainImageIndex].texture, &depthStencilViewDesc, depthStencilView.put()));
const bool reversedZ = (currentConfig.NearFar.Near > currentConfig.NearFar.Far);
// Clear and render to the render target.
ID3D11RenderTargetView* const renderTargets[] = {renderTargetView.get()};
sceneContext->DeviceContext->OMSetRenderTargets(1, renderTargets, depthStencilView.get());
// In double wide mode, the first projection clears the whole RTV and DSV.
if ((viewIndex == 0) || !currentConfig.DoubleWideMode) {
XMVECTORF32 clearColor = sceneContext->PrimaryViewConfigEnvironmentBlendMode == XR_ENVIRONMENT_BLEND_MODE_OPAQUE
? DirectX::Colors::CornflowerBlue
: DirectX::Colors::Transparent;
clearColor.v = DirectX::XMColorSRGBToRGB(clearColor.v);
sceneContext->DeviceContext->ClearRenderTargetView(renderTargets[0], clearColor);
const float clearDepthValue = reversedZ ? 0.f : 1.f;
sceneContext->DeviceContext->ClearDepthStencilView(
depthStencilView.get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, clearDepthValue, 0);
}
const DirectX::XMMATRIX projectionMatrix = xr::math::ComposeProjectionMatrix(fov, currentConfig.NearFar);
const bool visibilityMaskEnabled = currentConfig.VisibilityMaskEnabled;
const UINT stencilTestRef = 1;
bool shouldUseStencil = false;
if (visibilityMask && visibilityMaskEnabled) {
sceneContext->DeviceContext->OMSetDepthStencilState(m_noDepthWithStencilWrite.get(), stencilTestRef);
shouldUseStencil = visibilityMask->RenderMask(viewIndex, projectionMatrix);
}
if (reversedZ) {
if (shouldUseStencil) {
sceneContext->DeviceContext->OMSetDepthStencilState(m_reversedZDepthWithStencilTest.get(), stencilTestRef);
} else {
sceneContext->DeviceContext->OMSetDepthStencilState(m_reversedZDepthNoStencilTest.get(), 0);
}
} else {
if (shouldUseStencil) {
sceneContext->DeviceContext->OMSetDepthStencilState(m_forwardZWithStencilTest.get(), stencilTestRef);
} else {
sceneContext->DeviceContext->OMSetDepthStencilState(nullptr, 0);
}
}
// Set state for any objects which use PBR rendering.
// PBR library expects traditional view transform (world to view).
DirectX::XMMATRIX worldToViewMatrix = xr::math::LoadInvertedXrPose(projectionViews[viewIndex].pose);
if (currentConfig.YFlipViewAxis) {
DirectX::XMMATRIX yFlip = DirectX::XMMatrixIdentity();
yFlip.r[1] = XMVectorSet(0, -1, 0, 0);
worldToViewMatrix *= yFlip;
}
sceneContext->PbrResources.SetViewProjection(worldToViewMatrix, projectionMatrix);
sceneContext->PbrResources.Bind(sceneContext->DeviceContext.get());
sceneContext->PbrResources.SetDepthFuncReversed(reversedZ);
sceneContext->PbrResources.SetFrontFaceWindingOrder(currentConfig.FrontFaceCounterClockwise
? Pbr::FrontFaceWindingOrder::CounterClockWise
: Pbr::FrontFaceWindingOrder::ClockWise);
// Render all active scenes.
for (const std::unique_ptr<Scene>& scene : activeScenes) {
if (scene->HasSceneObjects() && scene->IsActive()) {
submitProjectionLayer = true;
scene->Render(frameTime);
}
}
}
}
}
// Now that the scene is done writing to the swapchain, it must be released in order to be made available for
// xrEndFrame.
const XrSwapchainImageReleaseInfo releaseInfo{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
CHECK_XRCMD(xrReleaseSwapchainImage(colorSwapchain.Handle.Get(), &releaseInfo));
CHECK_XRCMD(xrReleaseSwapchainImage(depthSwapchain.Handle.Get(), &releaseInfo));
sceneContext->PbrResources.UpdateAnimationTime(frameTime.TotalElapsed);
return submitProjectionLayer;
}
void AppendProjectionLayer(CompositionLayers& layers, const ProjectionLayer* layer, XrViewConfigurationType viewConfig) {
XrCompositionLayerProjection& projectionLayer = layers.AddProjectionLayer(layer->Config(viewConfig).LayerFlags);
projectionLayer.space = layer->LayerSpace(viewConfig);
projectionLayer.viewCount = (uint32_t)layer->ProjectionViews(viewConfig).size();
projectionLayer.views = layer->ProjectionViews(viewConfig).data();
}

Просмотреть файл

@ -0,0 +1,184 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <XrUtility/XrStereoView.h>
#include <XrUtility/XrHandle.h>
#include <XrUtility/XrMath.h>
#include <SampleShared/DxUtility.h>
struct ProjectionLayerConfig {
// FovScale = (TargetFov / HmdFov)
XrFovf FovScale = {1.0f, 1.0f, 1.0f, 1.0f};
xr::math::NearFar NearFar = {1000, 0.02f};
XrPosef ViewPoseOffsets[xr::StereoView::Count] = {{{0, 0, 0, 1}, {0, 0, 0}}, {{0, 0, 0, 1}, {0, 0, 0}}};
// SwapchainSizeScale applied on recommended image rect
XrExtent2Df SwapchainSizeScale = {1, 1};
XrExtent2Df SwapchainFovScale = {1, 1};
// ViewportSizeScale applied on swapchain image size with SwapchainSizeScale applied
XrExtent2Df ViewportSizeScale = {1, 1};
// ViewportOffset relative to (0, 0) of the swapchain
XrOffset2Di ViewportOffset = {0, 0};
uint32_t SwapchainSampleCount = 1;
bool DoubleWideMode = false;
bool IgnoreDepthLayer = false;
bool ContentProtected = false;
bool ForceReset = false;
bool VisibilityMaskEnabled = false;
bool YFlipViewAxis = false;
bool FrontFaceCounterClockwise = false;
DXGI_FORMAT ColorSwapchainFormat{};
DXGI_FORMAT DepthSwapchainFormat{};
// Layer's Color/Depth Offset/Scale swapchain image size with SwapchainSizeScale applied
XrOffset2Di ColorLayerOffset = {0, 0};
XrOffset2Di DepthLayerOffset = {0, 0};
XrExtent2Df ColorLayerSizeScale = {1, 1};
XrExtent2Df DepthLayerSizeScale = {1, 1};
XrCompositionLayerFlags LayerFlags = 0;
std::array<uint32_t, xr::StereoView::Count> ColorImageArrayIndices = {xr::StereoView::Left, xr::StereoView::Right};
std::array<uint32_t, xr::StereoView::Count> DepthImageArrayIndices = {xr::StereoView::Left, xr::StereoView::Right};
float minDepth = 0.0f;
float maxDepth = 1.0f;
};
struct IVisibilityMask;
class ProjectionLayer {
public:
public:
ProjectionLayer()
: m_ensureSupportSwapchainFormat(nullptr){};
ProjectionLayer(std::function<void(DXGI_FORMAT, bool /*isDepth*/)> ensureSupportSwapchainFormat,
DXGI_FORMAT colorSwapchainFormat,
DXGI_FORMAT depthSwapchainFormat,
XrViewConfigurationType primaryViewConfiguraionType,
const std::vector<XrViewConfigurationType>& secondaryViewConfiguraionTypes);
ProjectionLayer(ProjectionLayer&&) = default;
void SetPause(bool pause) {
m_pause = pause;
}
ProjectionLayerConfig& Config(std::optional<XrViewConfigurationType> viewConfig = std::nullopt) {
return m_viewConfigComponents.at(viewConfig.value_or(m_defaultViewConfigurationType)).PendingConfig;
}
const ProjectionLayerConfig& Config(std::optional<XrViewConfigurationType> viewConfig = std::nullopt) const {
return m_viewConfigComponents.at(viewConfig.value_or(m_defaultViewConfigurationType)).PendingConfig;
}
const std::vector<XrCompositionLayerProjectionView>&
ProjectionViews(std::optional<XrViewConfigurationType> viewConfig = std::nullopt) const {
return m_viewConfigComponents.at(viewConfig.value_or(m_defaultViewConfigurationType)).ProjectionViews;
}
const XrSpace LayerSpace(std::optional<XrViewConfigurationType> viewConfig = std::nullopt) const {
return m_viewConfigComponents.at(viewConfig.value_or(m_defaultViewConfigurationType)).LayerSpace;
}
void PrepareRendering(const SceneContext* sceneContext,
XrViewConfigurationType viewConfigType,
const std::vector<XrViewConfigurationView>& viewConfigViews,
bool canCreateSwapchain);
bool Render(SceneContext* sceneContext,
const FrameTime& frameTime,
XrSpace layerSpace,
const std::vector<XrView>& Views,
const std::vector<std::unique_ptr<Scene>>& activeScenes,
const IVisibilityMask* visibilityMask,
XrViewConfigurationType viewConfig);
private:
ProjectionLayer(const ProjectionLayer&) = delete;
ProjectionLayer& operator=(const ProjectionLayer&) = delete;
ProjectionLayer& operator=(ProjectionLayer&&) = default;
struct ViewConfigComponent {
ProjectionLayerConfig CurrentConfig;
ProjectionLayerConfig PendingConfig;
XrSpace LayerSpace{XR_NULL_HANDLE};
std::vector<XrCompositionLayerProjectionView> ProjectionViews; // Pre-allocated and reused for each frame.
std::vector<XrCompositionLayerDepthInfoKHR> DepthElements; // Pre-allocated and reused for each frame.
std::vector<D3D11_VIEWPORT> Viewports;
XrRect2Di LayerColorImageRect[xr::StereoView::Count];
XrRect2Di LayerDepthImageRect[xr::StereoView::Count];
sample::dx::SwapchainD3D11 ColorSwapchain;
sample::dx::SwapchainD3D11 DepthSwapchain;
};
std::unordered_map<XrViewConfigurationType, ViewConfigComponent> m_viewConfigComponents;
XrViewConfigurationType m_defaultViewConfigurationType;
bool m_pause = false;
winrt::com_ptr<ID3D11DepthStencilState> m_noDepthWithStencilWrite;
winrt::com_ptr<ID3D11DepthStencilState> m_forwardZWithStencilTest;
winrt::com_ptr<ID3D11DepthStencilState> m_reversedZDepthNoStencilTest;
winrt::com_ptr<ID3D11DepthStencilState> m_reversedZDepthWithStencilTest;
std::function<void(DXGI_FORMAT format, bool isDepth)> m_ensureSupportSwapchainFormat;
};
class ProjectionLayers {
public:
ProjectionLayers(std::function<std::unique_ptr<ProjectionLayer>()> createLayerFunction)
: m_createLayerFunction(createLayerFunction) {
}
~ProjectionLayers() {
std::lock_guard lock(m_mutex);
m_projectionLayers.clear();
}
uint32_t Size() const {
std::lock_guard lock(m_mutex);
return (uint32_t)m_projectionLayers.size();
}
ProjectionLayer& At(uint32_t index) {
std::lock_guard lock(m_mutex);
return *m_projectionLayers.at(index);
}
void Resize(uint32_t size, bool forceReset = false) {
std::lock_guard lock(m_mutex);
if (forceReset || m_projectionLayers.size() != size) {
m_projectionLayers.clear();
m_projectionLayers.reserve(size);
for (uint32_t i = 0; i < size; i++) {
m_projectionLayers.emplace_back(m_createLayerFunction());
m_projectionLayers.back()->Config().ForceReset = true;
}
}
}
void ForEachLayerWithLock(std::function<void(ProjectionLayer&)> function) {
std::lock_guard lock(m_mutex);
for (std::unique_ptr<ProjectionLayer>& layer : m_projectionLayers) {
function(*layer);
}
}
private:
mutable std::mutex m_mutex;
std::vector<std::unique_ptr<ProjectionLayer>> m_projectionLayers;
std::function<std::unique_ptr<ProjectionLayer>()> m_createLayerFunction;
};

Просмотреть файл

@ -0,0 +1,48 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "QuadLayerObject.h"
#include "CompositionLayers.h"
using namespace DirectX;
std::shared_ptr<QuadLayerObject> MakeQuadLayerObject(XrSpace space, XrSwapchainSubImage image) {
auto result = std::make_shared<QuadLayerObject>();
result->Image = std::move(image);
result->Space = space;
return result;
}
void AppendQuadLayer(CompositionLayers& layers, QuadLayerObject* quad) {
XrCompositionLayerQuad& quadLayer = layers.AddQuadLayer();
quadLayer.type = XR_TYPE_COMPOSITION_LAYER_QUAD;
quadLayer.subImage = quad->Image;
quadLayer.space = quad->Space;
quadLayer.layerFlags = quad->CompositionLayerFlags;
quadLayer.eyeVisibility = quad->EyeVisibility;
XMVECTOR scale, position, orientation;
if (!DirectX::XMMatrixDecompose(&scale, &orientation, &position, quad->WorldTransform())) {
throw std::runtime_error("Failed to decompose quad layer world transform");
}
xr::math::StoreXrQuaternion(&quadLayer.pose.orientation, orientation);
xr::math::StoreXrVector3(&quadLayer.pose.position, position);
xr::math::StoreXrExtent(&quadLayer.size, scale); // Use x and y but ignore z.
};

Просмотреть файл

@ -0,0 +1,36 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include "SceneObject.h"
#include "SceneContext.h"
enum class LayerGrouping {
Underlay, // Behind all projection layers
Overlay // In front of all projection layers
};
struct QuadLayerObject : public SceneObject {
XrSwapchainSubImage Image;
XrSpace Space{XR_NULL_HANDLE};
XrCompositionLayerFlags CompositionLayerFlags{};
XrEyeVisibility EyeVisibility{XR_EYE_VISIBILITY_BOTH};
LayerGrouping LayerGroup = LayerGrouping::Overlay;
};
std::shared_ptr<QuadLayerObject> MakeQuadLayerObject(XrSpace space, XrSwapchainSubImage image);

Просмотреть файл

@ -0,0 +1,79 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "Scene.h"
using namespace DirectX;
Scene::Scene(::SceneContext* sceneContext, std::wstring sceneName, bool defaultActive)
: m_sceneContext(sceneContext)
, m_sceneName(std::move(sceneName))
, m_defaultActive(defaultActive) {
}
template <typename T>
void AddPendingObjects(std::vector<std::shared_ptr<T>>* objects, std::vector<std::shared_ptr<T>>&& uninitializedObjects) {
for (auto& object : uninitializedObjects) {
if (object->State == SceneObjectState::InitializePending) {
object->State = SceneObjectState::Initialized;
objects->push_back(std::move(object));
}
}
uninitializedObjects.clear();
}
template <typename T>
void RemoveDestroyedObjects(std::vector<std::shared_ptr<T>>* objects) {
auto newEnd =
std::remove_if(objects->begin(), objects->end(), [](auto&& object) { return object->State == SceneObjectState::RemovePending; });
objects->erase(newEnd, objects->end());
}
template <typename T>
void UpdateObjects(std::vector<std::shared_ptr<T>> const& objects, FrameTime const& frameTime) {
for (const auto& object : objects) {
object->Update(frameTime);
}
}
template <typename T>
void RenderObjects(std::vector<std::shared_ptr<T>> const& objects, SceneContext& sceneContext) {
for (const auto& object : objects) {
object->Render(sceneContext);
}
}
void Scene::Update(const FrameTime& frameTime) {
AddPendingObjects(&m_sceneObjects, std::move(m_uninitializedSceneObjects));
AddPendingObjects(&m_quadLayerObjects, std::move(m_uninitializedQuadLayerObjects));
RemoveDestroyedObjects(&m_sceneObjects);
RemoveDestroyedObjects(&m_quadLayerObjects);
UpdateObjects(m_sceneObjects, frameTime);
UpdateObjects(m_quadLayerObjects, frameTime);
OnUpdate(frameTime);
}
void Scene::Render(const FrameTime& frameTime) const {
RenderObjects(m_sceneObjects, *m_sceneContext);
RenderObjects(m_quadLayerObjects, *m_sceneContext);
OnRender(frameTime);
}

140
samples/XrSceneLib/Scene.h Normal file
Просмотреть файл

@ -0,0 +1,140 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include "SceneContext.h"
#include "SceneObject.h"
#include "QuadLayerObject.h"
#include <optional>
namespace scenes::priorities {
constexpr uint32_t Default = 0;
constexpr uint32_t ControllerRendering = 0;
constexpr uint32_t Menu = 1;
} // namespace scenes::priorities
struct Scene {
virtual ~Scene() = default;
Scene(SceneContext* sceneContext, std::wstring sceneName, bool defaultActive);
#pragma region Scene objects will be rendered into projection layers
template <typename T>
std::shared_ptr<T> AddSceneObject(const std::shared_ptr<T>& sceneObject) {
sceneObject->State = SceneObjectState::InitializePending;
m_uninitializedSceneObjects.push_back(sceneObject);
return sceneObject;
}
template <typename T>
void RemoveSceneObject(const std::shared_ptr<T>& sceneObject) {
sceneObject->State = SceneObjectState::RemovePending;
}
std::vector<std::shared_ptr<SceneObject>> GetSceneObjects() const {
return m_sceneObjects;
}
#pragma endregion
#pragma region Quad layer objects will be rendered into quad layers, and will not affect projection layers
std::shared_ptr<QuadLayerObject> AddQuadLayerObject(const std::shared_ptr<QuadLayerObject>& sceneObject) {
sceneObject->State = SceneObjectState::InitializePending;
m_uninitializedQuadLayerObjects.push_back(sceneObject);
return sceneObject;
}
std::vector<std::shared_ptr<QuadLayerObject>> GetQuadLayerObjects() const {
return m_quadLayerObjects;
}
bool HasSceneObjects() const {
return !m_sceneObjects.empty();
}
#pragma endregion
void Update(const FrameTime& frameTime);
void Render(const FrameTime& frameTime) const;
void NotifyInteractionProfileChangedEvent() {
OnInteractionProfileChanged();
}
void NotifySpaceChangingEvent(XrReferenceSpaceType referenceSpaceType, XrTime changeTime, std::optional<XrPosef> pose) {
OnSpaceChanging(referenceSpaceType, changeTime, pose);
}
void NotifyMenuButtonPressed() {
OnMenuButtonPressed();
}
virtual DirectX::XMFLOAT4 ColorScale() const {
return {1.0f, 1.0f, 1.0f, 1.0f};
}
bool IsActive() const {
return m_isActive;
}
void SetActive(bool active) {
if (m_isActive != active) {
OnActiveChanged(active);
}
m_isActive = active;
}
bool ActiveByDefault() const {
return m_defaultActive;
}
const std::wstring& Name() const {
return m_sceneName;
}
const std::wstring& Description() const {
return m_sceneDescription;
}
protected:
::SceneContext* const m_sceneContext;
virtual void OnUpdate(const FrameTime& frameTime) {
}
virtual void OnRender(const FrameTime& frameTime) const {
}
virtual void OnInteractionProfileChanged() {
}
virtual void OnSpaceChanging(XrReferenceSpaceType referenceSpaceType, XrTime changeTime, const std::optional<XrPosef>& pose) {
}
virtual void OnActiveChanged(bool toActive) {
}
virtual void OnMenuButtonPressed() {
SetActive(!IsActive());
}
void SetSceneDescription(std::wstring description) {
m_sceneDescription = std::move(description);
}
private:
const bool m_defaultActive{false};
const std::wstring m_sceneName;
std::wstring m_sceneDescription;
std::atomic<bool> m_isActive{true};
std::vector<std::shared_ptr<SceneObject>> m_sceneObjects;
std::vector<std::shared_ptr<SceneObject>> m_uninitializedSceneObjects;
std::vector<std::shared_ptr<QuadLayerObject>> m_quadLayerObjects;
std::vector<std::shared_ptr<QuadLayerObject>> m_uninitializedQuadLayerObjects;
};

Просмотреть файл

@ -0,0 +1,82 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <pbr/PbrResources.h>
#include <XrUtility/XrString.h>
#include <XrUtility/XrExtensions.h>
#include <XrUtility/XrInstanceContext.h>
#include <XrUtility/XrActionContext.h>
// Session-related resources shared across multiple Scenes.
struct SceneContext final {
SceneContext(xr::InstanceContext instance,
xr::SystemContext system,
XrSession session,
XrSpace sceneSpace,
Pbr::Resources pbrResources,
winrt::com_ptr<ID3D11Device> device,
winrt::com_ptr<ID3D11DeviceContext> deviceContext,
xr::ActionContext& actionContext,
XrEnvironmentBlendMode primaryViewConfigEnvironmentBlendMode)
: Instance(std::move(instance))
, System(std::move(system))
, Extensions(std::cref(Instance.Extensions))
, Session(session)
, SceneSpace(sceneSpace)
, PbrResources(std::move(pbrResources))
, Device(std::move(device))
, DeviceContext(std::move(deviceContext))
, PrimaryViewConfigEnvironmentBlendMode(primaryViewConfigEnvironmentBlendMode)
, ActionContext(actionContext)
, LeftHand(xr::StringToPath(Instance.Handle(), "/user/hand/left"))
, RightHand(xr::StringToPath(Instance.Handle(), "/user/hand/right"))
, GamePad(xr::StringToPath(Instance.Handle(), "/user/gamepad")) {
}
const xr::InstanceContext Instance;
const xr::SystemContext System;
const xr::ExtensionContext& Extensions;
const XrSession Session;
const XrEnvironmentBlendMode PrimaryViewConfigEnvironmentBlendMode;
const XrSpace SceneSpace;
const winrt::com_ptr<ID3D11DeviceContext> DeviceContext;
const winrt::com_ptr<ID3D11Device> Device;
Pbr::Resources PbrResources;
xr::ActionContext& ActionContext;
std::atomic<XrSessionState> SessionState;
const XrPath RightHand;
const XrPath LeftHand;
const XrPath GamePad;
XrPath PrimaryHand() const {
return m_primaryIsRight ? RightHand : LeftHand;
}
XrPath SecondaryHand() const {
return m_primaryIsRight ? LeftHand : RightHand;
}
void SetPrimaryHand(XrPath path) {
assert(path == RightHand || path == LeftHand);
m_primaryIsRight = (path == RightHand);
}
private:
bool m_primaryIsRight{true};
};

Просмотреть файл

@ -0,0 +1,75 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "SceneObject.h"
void SceneObject::Update(const FrameTime& frameTime) {
ApplyRigidbodyPhysics(frameTime.Elapsed);
}
void SceneObject::Render(SceneContext& sceneContext) const {
}
void SceneObject::ApplyRigidbodyPhysics(std::chrono::duration<float> duration) {
using namespace DirectX;
if (!Physics.Enabled) {
return;
}
const float dt = duration.count();
const auto position = xr::math::LoadXrVector3(m_pose.position);
const auto orientation = xr::math::LoadXrQuaternion(m_pose.orientation);
const auto linearVelocity = XMLoadFloat3(&Physics.LinearVelocity);
const auto angularVelocity = XMLoadFloat3(&Physics.AngularVelocity);
const auto linearAcceleration = XMLoadFloat3(&Physics.LinearAcceleration);
const auto angularAcceleration = XMLoadFloat3(&Physics.AngularAcceleration);
XMStoreFloat3(&Physics.LinearVelocity, linearVelocity + XMVectorScale(linearAcceleration, dt));
XMStoreFloat3(&Physics.AngularVelocity, angularVelocity + XMVectorScale(angularAcceleration, dt));
xr::math::StoreXrVector3(&m_pose.position, position + XMVectorScale(linearVelocity, dt));
// To implicit app space
auto adjustedAngularVelocity = XMVector3Rotate(angularVelocity, XMQuaternionInverse(orientation));
auto angle = XMVectorGetX(XMVector3Length(adjustedAngularVelocity));
if (angle > 0.0f) {
xr::math::StoreXrQuaternion(&m_pose.orientation,
XMQuaternionMultiply(XMQuaternionRotationAxis(adjustedAngularVelocity, angle * dt), orientation));
}
}
DirectX::XMMATRIX SceneObject::LocalTransform() const {
if (!m_localTransformDirty) {
return DirectX::XMLoadFloat4x4(&m_localTransform);
}
const DirectX::XMMATRIX modelScale = DirectX::XMMatrixScalingFromVector(xr::math::LoadXrVector3(m_scale));
const DirectX::XMMATRIX modelRotation = DirectX::XMMatrixRotationQuaternion(xr::math::LoadXrQuaternion(m_pose.orientation));
const DirectX::XMMATRIX modelTranslation = DirectX::XMMatrixTranslationFromVector(xr::math::LoadXrVector3(m_pose.position));
const DirectX::XMMATRIX localTransform = modelScale * modelRotation * modelTranslation;
DirectX::XMStoreFloat4x4(&m_localTransform, localTransform);
m_localTransformDirty = false;
return localTransform;
}
DirectX::XMMATRIX SceneObject::WorldTransform() const {
return m_parent ? XMMatrixMultiply(LocalTransform(), m_parent->WorldTransform()) : LocalTransform();
}

Просмотреть файл

@ -0,0 +1,91 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <XrUtility/XrMath.h>
#include "SceneContext.h"
#include "FrameTime.h"
enum class SceneObjectState { InitializePending, Initialized, RemovePending };
struct PhysicsData {
bool Enabled{false};
DirectX::XMFLOAT3 LinearVelocity{0, 0, 0};
DirectX::XMFLOAT3 LinearAcceleration{0, -9.8f, 0};
DirectX::XMFLOAT3 AngularVelocity{0, 0, 0};
DirectX::XMFLOAT3 AngularAcceleration{0, 0, 0};
};
class SceneObject {
public:
virtual ~SceneObject() = default;
SceneObjectState State;
PhysicsData Physics;
public:
void SetParent(std::shared_ptr<SceneObject> parent) {
m_parent = std::move(parent);
}
void SetVisible(bool visible) {
m_isVisible = visible;
}
bool IsVisible() const {
return (m_parent ? m_parent->IsVisible() : true) && m_isVisible;
}
bool IsRenderable() const {
return State == SceneObjectState::Initialized && IsVisible();
}
const XrPosef& Pose() const {
return m_pose;
}
XrPosef& Pose() {
m_localTransformDirty = true;
return m_pose;
}
const XrVector3f& Scale() const {
return m_scale;
}
XrVector3f& Scale() {
m_localTransformDirty = true;
return m_scale;
}
DirectX::XMMATRIX LocalTransform() const;
DirectX::XMMATRIX WorldTransform() const;
virtual void Update(const FrameTime& frameTime);
virtual void Render(SceneContext& sceneContext) const;
private:
void ApplyRigidbodyPhysics(std::chrono::duration<float> duration);
private:
bool m_isVisible{true};
XrPosef m_pose = xr::math::Pose::Identity();
XrVector3f m_scale = {1, 1, 1};
std::shared_ptr<SceneObject> m_parent;
// Local transform is relative to parent
// Only recompute when transform is changed.
mutable DirectX::XMFLOAT4X4 m_localTransform;
mutable bool m_localTransformDirty{true};
};

Просмотреть файл

@ -0,0 +1,167 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "SceneContext.h"
#include "VisibilityMask.h"
#include <StereoVisibleMaskVertexShader.h>
#include <SampleShared/Trace.h>
using namespace DirectX;
namespace {
static constexpr uint32_t NumViews = 2;
static constexpr XrViewConfigurationType ViewConfigType = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
static constexpr XrVisibilityMaskTypeKHR VisibilityMaskType = XR_VISIBILITY_MASK_TYPE_VISIBLE_TRIANGLE_MESH_KHR;
static constexpr D3D11_INPUT_ELEMENT_DESC VertexDesc = {
"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0};
struct ProjTransformConstantData {
XMFLOAT4X4 ProjTransform;
};
struct StereoVisibleMask : public IVisibilityMask {
StereoVisibleMask(SceneContext* sceneContext)
: m_sceneContext(sceneContext) {
CHECK_HRCMD(m_sceneContext->Device->CreateVertexShader(
g_StereoVisibleMaskVertexShader, sizeof(g_StereoVisibleMaskVertexShader), nullptr, m_meshVertexShader.put()));
CHECK_HRCMD(m_sceneContext->Device->CreateInputLayout(
&VertexDesc, 1, g_StereoVisibleMaskVertexShader, sizeof(g_StereoVisibleMaskVertexShader), m_meshInputLayout.put()));
const CD3D11_BUFFER_DESC cbDesc{(UINT)(sizeof(ProjTransformConstantData)), D3D11_BIND_CONSTANT_BUFFER};
CHECK_HRCMD(m_sceneContext->Device->CreateBuffer(&cbDesc, nullptr, m_projTransformConstantBuffer.put()));
CD3D11_RASTERIZER_DESC rsStateDesc(CD3D11_DEFAULT{});
rsStateDesc.FrontCounterClockwise = TRUE;
CHECK_HRCMD(m_sceneContext->Device->CreateRasterizerState(&rsStateDesc, m_ccwWindingRSState.put()));
for (uint32_t i = 0; i < NumViews; i++) {
UpdateVisibleMeshObject(i);
}
}
// Prior calling render, the caller need to ensure viewport and depth stencil state are correctly set and bind; stencil buffer is
// cleared
bool RenderMask(uint32_t viewIndex, FXMMATRIX viewToProj) const override {
assert(viewIndex < NumViews);
if (!m_isMaskValid) {
return false;
}
ProjTransformConstantData data{};
XMStoreFloat4x4(&data.ProjTransform, XMMatrixTranspose(viewToProj));
m_sceneContext->DeviceContext->UpdateSubresource(m_projTransformConstantBuffer.get(), 0, nullptr, &data, 0, 0);
ID3D11Buffer* projConstantBuffers[] = {m_projTransformConstantBuffer.get()};
m_sceneContext->DeviceContext->VSSetShader(m_meshVertexShader.get(), nullptr, 0);
m_sceneContext->DeviceContext->VSSetConstantBuffers(0, 1, projConstantBuffers);
m_sceneContext->DeviceContext->PSSetShader(nullptr, nullptr, 0);
m_sceneContext->DeviceContext->GSSetShader(nullptr, nullptr, 0);
ID3D11RasterizerState* prevRSState;
m_sceneContext->DeviceContext->RSGetState(&prevRSState);
m_sceneContext->DeviceContext->RSSetState(m_ccwWindingRSState.get());
ID3D11Buffer* iaVertBuffers[] = {m_meshVertexBuffer[viewIndex].get()};
const UINT iaStrides[] = {sizeof(XrVector2f)};
const UINT iaOffsets[] = {0};
m_sceneContext->DeviceContext->IASetVertexBuffers(0, 1, iaVertBuffers, iaStrides, iaOffsets);
m_sceneContext->DeviceContext->IASetIndexBuffer(m_meshIndexBuffer[viewIndex].get(), DXGI_FORMAT_R32_UINT, 0);
m_sceneContext->DeviceContext->IASetInputLayout(m_meshInputLayout.get());
m_sceneContext->DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_sceneContext->DeviceContext->DrawIndexed(static_cast<uint32_t>(m_visibleMeshIndices[viewIndex].size()), 0, 0);
m_sceneContext->DeviceContext->RSSetState(prevRSState);
return true;
}
void NotifyMaskChanged(uint32_t viewIndex) override {
UpdateVisibleMeshObject(viewIndex);
}
private:
void UpdateVisibleMeshObject(uint32_t viewIndex) {
assert(viewIndex < NumViews);
m_visibleMeshVertices[viewIndex].clear();
m_visibleMeshIndices[viewIndex].clear();
XrVisibilityMaskKHR visibilityMask{XR_TYPE_VISIBILITY_MASK_KHR};
CHECK_XRCMD(m_sceneContext->Extensions.xrGetVisibilityMaskKHR(
m_sceneContext->Session, ViewConfigType, viewIndex, VisibilityMaskType, &visibilityMask));
m_isMaskValid = visibilityMask.vertexCountOutput != 0;
if (!m_isMaskValid) {
return;
}
// allocate memory for vertices
m_visibleMeshVertices[viewIndex].resize(visibilityMask.vertexCountOutput);
visibilityMask.vertices = m_visibleMeshVertices[viewIndex].data();
m_visibleMeshIndices[viewIndex].resize(visibilityMask.vertexCountOutput);
visibilityMask.indices = m_visibleMeshIndices[viewIndex].data();
visibilityMask.vertexCapacityInput = visibilityMask.vertexCountOutput;
visibilityMask.indexCapacityInput = visibilityMask.indexCountOutput;
CHECK_XRCMD(m_sceneContext->Extensions.xrGetVisibilityMaskKHR(
m_sceneContext->Session, ViewConfigType, viewIndex, VisibilityMaskType, &visibilityMask));
// Re-create vertex/index buffer
D3D11_BUFFER_DESC desc{};
desc.Usage = D3D11_USAGE_DEFAULT;
desc.ByteWidth = (UINT)(sizeof(XrVector2f) * m_visibleMeshVertices[viewIndex].size());
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA initData{};
initData.pSysMem = m_visibleMeshVertices[viewIndex].data();
m_meshVertexBuffer[viewIndex] = nullptr;
CHECK_HRCMD(m_sceneContext->Device->CreateBuffer(&desc, &initData, m_meshVertexBuffer[viewIndex].put()));
desc.ByteWidth = (UINT)(sizeof(uint32_t) * m_visibleMeshIndices[viewIndex].size());
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
initData.pSysMem = m_visibleMeshIndices[viewIndex].data();
m_meshIndexBuffer[viewIndex] = nullptr;
CHECK_HRCMD(m_sceneContext->Device->CreateBuffer(&desc, &initData, m_meshIndexBuffer[viewIndex].put()));
}
std::vector<XrVector2f> m_visibleMeshVertices[NumViews];
std::vector<uint32_t> m_visibleMeshIndices[NumViews];
winrt::com_ptr<ID3D11InputLayout> m_meshInputLayout;
winrt::com_ptr<ID3D11VertexShader> m_meshVertexShader;
winrt::com_ptr<ID3D11Buffer> m_meshVertexBuffer[NumViews];
winrt::com_ptr<ID3D11Buffer> m_meshIndexBuffer[NumViews];
winrt::com_ptr<ID3D11Buffer> m_projTransformConstantBuffer;
winrt::com_ptr<ID3D11RasterizerState> m_ccwWindingRSState;
const SceneContext* m_sceneContext;
bool m_isMaskValid{false};
};
} // namespace
std::unique_ptr<IVisibilityMask> CreateStereoVisibilityMask(SceneContext* sceneContext) {
return std::make_unique<StereoVisibleMask>(sceneContext);
}

Просмотреть файл

@ -0,0 +1,7 @@
cbuffer VertexCBuffer : register(b0) {
float4x4 ProjTransform;
}
float4 main(float2 pos : POSITION) : SV_Position {
return mul(float4(pos, -1.0f, 1.0f), ProjTransform);
}

Просмотреть файл

@ -0,0 +1,110 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "TextQuadObject.h"
constexpr uint32_t TextWidth = 256;
constexpr uint32_t TextHeight = 256;
TextQuadObject::TextQuadObject(Scene* scene, XrSpace space, SceneContext* sceneContext, std::wstring text)
: m_scene(scene)
, m_text(std::move(text))
, m_sceneContext(sceneContext)
, m_textTexture(sceneContext, TextWidth, TextHeight, L"Consolas", 18.0f) {
D3D11_TEXTURE2D_DESC textDesc;
m_textTexture.Texture()->GetDesc(&textDesc);
m_textSwapchain =
sample::dx::CreateSwapchainD3D11(m_sceneContext->Session,
textDesc.Format,
TextWidth,
TextHeight,
/*arrayLength*/ 1,
/*sampleCount*/ 1,
/*createFlags*/ (m_contentProtectionEnabled ? XR_SWAPCHAIN_CREATE_PROTECTED_CONTENT_BIT : 0),
/*usage Flags*/ XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT);
PrepareTextSwapchain(space);
}
void TextQuadObject::Update(const FrameTime& frameTime) {
if (m_textChangeRequested) {
// m_quad is removed from render loop, but m_quad is a shared_ptr so
// we are still holding it until PrepareTextSwapchain() call
XrSpace lastTextQuadSpace = m_quad->Space;
PrepareTextSwapchain(lastTextQuadSpace);
m_textChangeRequested = false;
}
m_quad->SetVisible(IsVisible());
}
void TextQuadObject::SetText(const std::wstring& text) {
if (m_text != text) {
m_textChangeRequested = true;
// Queue text quad removal; it will be removed before next call to Update()
m_scene->RemoveSceneObject(m_quad);
m_text = text;
}
}
void TextQuadObject::SetContentProtectionEnabled(bool enabled) {
if (m_contentProtectionEnabled != enabled) {
m_textChangeRequested = true;
// Queue text quad removal; it will be removed before next call to Update()
m_scene->RemoveSceneObject(m_quad);
m_contentProtectionEnabled = enabled;
}
}
void TextQuadObject::SetBackgroundColor(const XrColor4f& color) {
m_backgroundColor = color;
}
void TextQuadObject::PrepareTextSwapchain(const XrSpace textSpace) {
XrSwapchainSubImage textImageData{};
textImageData.swapchain = m_textSwapchain.Handle.Get();
textImageData.imageRect.extent = {TextWidth, TextHeight};
m_quad = m_scene->AddQuadLayerObject(MakeQuadLayerObject(textSpace, textImageData));
m_quad->Scale() = {0.2f, 0.2f, 0.2f};
m_quad->CompositionLayerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
// Render text to the swapchain
{
uint32_t index;
XrSwapchainImageAcquireInfo acquireInfo{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
CHECK_XRCMD(xrAcquireSwapchainImage(m_textSwapchain.Handle.Get(), &acquireInfo, &index));
XrSwapchainImageWaitInfo waitInfo{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO};
waitInfo.timeout = XR_INFINITE_DURATION;
CHECK_XRCMD(xrWaitSwapchainImage(m_textSwapchain.Handle.Get(), &waitInfo));
m_textTexture.Draw(m_text.c_str());
m_sceneContext->DeviceContext->CopyResource(m_textSwapchain.Images[index].texture, m_textTexture.Texture());
const XrSwapchainImageReleaseInfo releaseInfo{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
CHECK_XRCMD(xrReleaseSwapchainImage(m_textSwapchain.Handle.Get(), &releaseInfo));
}
}

Просмотреть файл

@ -0,0 +1,60 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <openxr/openxr.h>
#include <dxgi.h>
#include <d2d1_2.h>
#include <dwrite_2.h>
#include <SampleShared/DxUtility.h>
#include "TextTexture.h"
#include "Scene.h"
#include "SceneObject.h"
class TextQuadObject : public SceneObject {
public:
TextQuadObject(Scene* scene, XrSpace space, SceneContext* sceneContext, std::wstring text);
void Update(const FrameTime& frameTime) override;
void SetText(const std::wstring& text);
void SetBackgroundColor(const XrColor4f& color);
void SetContentProtectionEnabled(bool enabled);
std::shared_ptr<QuadLayerObject> Quad() const {
return m_quad;
}
private:
void PrepareTextSwapchain(XrSpace textSpace);
private:
Scene* const m_scene;
SceneContext* const m_sceneContext;
std::wstring m_text;
bool m_textChangeRequested{false};
bool m_contentProtectionEnabled{false};
XrColor4f m_backgroundColor{0.0f, 0.0f, 0.0f, 0.0f};
TextTexture m_textTexture;
std::shared_ptr<QuadLayerObject> m_quad;
sample::dx::SwapchainD3D11 m_textSwapchain;
};

Просмотреть файл

@ -0,0 +1,105 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "pbr/PbrMaterial.h"
#include "TextTexture.h"
namespace {
constexpr DXGI_FORMAT TextFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
}
TextTexture::TextTexture(
SceneContext* sceneContext, uint32_t width, uint32_t height, const wchar_t* fontName, float fontSize, Pbr::RGBAColor color) {
const winrt::com_ptr<ID3D11Device> device = sceneContext->Device;
const winrt::com_ptr<ID3D11DeviceContext> context = sceneContext->DeviceContext;
D2D1_FACTORY_OPTIONS options{};
CHECK_HRCMD(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, winrt::guid_of<ID2D1Factory2>(), &options, m_d2dFactory.put_void()));
CHECK_HRCMD(DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED, winrt::guid_of<IDWriteFactory2>(), reinterpret_cast<IUnknown**>(m_dwriteFactory.put_void())));
const winrt::com_ptr<IDXGIDevice> dxgiDevice = device.as<IDXGIDevice>();
CHECK_HRCMD(m_d2dFactory->CreateDevice(dxgiDevice.get(), m_d2dDevice.put()));
CHECK_HRCMD(m_d2dDevice->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, m_d2dContext.put()));
//
// Create text format.
//
CHECK_HRCMD(m_dwriteFactory->CreateTextFormat(fontName,
nullptr,
DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
fontSize,
L"en-US",
m_textFormat.put()));
CHECK_HRCMD(m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER));
CHECK_HRCMD(m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER));
CHECK_HRCMD(m_d2dFactory->CreateDrawingStateBlock(m_stateBlock.put()));
//
// Set up 2D rendering modes.
//
const D2D1_BITMAP_PROPERTIES1 bitmapProperties = D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
D2D1::PixelFormat(TextFormat, D2D1_ALPHA_MODE_PREMULTIPLIED));
const auto texDesc = CD3D11_TEXTURE2D_DESC(
TextFormat, width, height, 1, 1, D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_DEFAULT, 0, 1, 0, 0);
CHECK_HRCMD(device->CreateTexture2D(&texDesc, nullptr, m_textDWriteTexture.put()));
winrt::com_ptr<IDXGISurface> dxgiPerfBuffer = m_textDWriteTexture.as<IDXGISurface>();
CHECK_HRCMD(m_d2dContext->CreateBitmapFromDxgiSurface(dxgiPerfBuffer.get(), &bitmapProperties, m_d2dTargetBitmap.put()));
m_d2dContext->SetTarget(m_d2dTargetBitmap.get());
m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
CHECK_HRCMD(m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(color.x, color.y, color.z, color.w), m_brush.put()));
}
void TextTexture::Draw(const wchar_t* text) {
m_d2dContext->SaveDrawingState(m_stateBlock.get());
const D2D1_SIZE_F renderTargetSize = m_d2dContext->GetSize();
m_d2dContext->BeginDraw();
m_d2dContext->Clear(0);
m_d2dContext->DrawText(text,
static_cast<UINT32>(wcslen(text)),
m_textFormat.get(),
D2D1::RectF(0.0f, 0.0f, renderTargetSize.width, renderTargetSize.height),
m_brush.get());
m_d2dContext->EndDraw();
m_d2dContext->RestoreDrawingState(m_stateBlock.get());
}
ID3D11Texture2D* TextTexture::Texture() const {
return m_textDWriteTexture.get();
}
std::shared_ptr<Pbr::Material> TextTexture::CreatePbrMaterial(const Pbr::Resources& pbrResources) const {
auto material = Pbr::Material::CreateFlat(pbrResources, Pbr::RGBA::White);
winrt::com_ptr<ID3D11ShaderResourceView> textSrv;
CHECK_HRCMD(pbrResources.GetDevice()->CreateShaderResourceView(Texture(), nullptr, textSrv.put()));
material->SetTexture(Pbr::ShaderSlots::BaseColor, textSrv.get());
material->SetAlphaBlended(true);
return material;
}

Просмотреть файл

@ -0,0 +1,50 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <openxr/openxr.h>
#include <dxgi.h>
#include <d2d1_2.h>
#include <dwrite_2.h>
#include "SceneObject.h"
// Manages a texture which can be drawn to.
class TextTexture {
public:
TextTexture(SceneContext* sceneContext,
uint32_t width,
uint32_t height,
const wchar_t* fontName = L"Segoe UI",
float fontSize = 18,
Pbr::RGBAColor color = Pbr::RGBA::White);
void Draw(const wchar_t* text);
ID3D11Texture2D* Texture() const;
std::shared_ptr<Pbr::Material> CreatePbrMaterial(const Pbr::Resources& pbrResources) const;
private:
winrt::com_ptr<ID2D1Factory2> m_d2dFactory;
winrt::com_ptr<ID2D1Device1> m_d2dDevice;
winrt::com_ptr<ID2D1DeviceContext1> m_d2dContext;
winrt::com_ptr<ID2D1Bitmap1> m_d2dTargetBitmap;
winrt::com_ptr<ID2D1SolidColorBrush> m_brush;
winrt::com_ptr<ID2D1DrawingStateBlock> m_stateBlock;
winrt::com_ptr<IDWriteFactory2> m_dwriteFactory;
winrt::com_ptr<IDWriteTextFormat> m_textFormat;
winrt::com_ptr<ID3D11Texture2D> m_textDWriteTexture;
};

Просмотреть файл

@ -0,0 +1,25 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
struct IVisibilityMask {
virtual ~IVisibilityMask() = default;
virtual bool RenderMask(uint32_t viewIndex, DirectX::FXMMATRIX viewToProj) const = 0;
virtual void NotifyMaskChanged(uint32_t viewIndex) = 0;
};
std::unique_ptr<IVisibilityMask> CreateStereoVisibilityMask(SceneContext* sceneContext);

Просмотреть файл

@ -0,0 +1,228 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM64">
<Configuration>Debug</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM64">
<Configuration>Release</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{56F1C3F4-8AB3-4518-9671-AA4219F56167}</ProjectGuid>
<Keyword>StaticLibrary</Keyword>
<RootNamespace>XrSceneLib_uwp</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.17763.0</WindowsTargetPlatformMinVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
<ProjectName>XrSceneLib_uwp</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)'=='Debug'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_LIB;UWP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
</ClCompile>
<Link>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="PbrModelObject.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="QuadLayerObject.h" />
<ClInclude Include="Scene.h" />
<ClInclude Include="SceneObject.h" />
<ClInclude Include="App.h" />
<ClInclude Include="CompositionLayers.h" />
<ClInclude Include="ProjectionLayer.h" />
<ClInclude Include="FrameTime.h" />
<ClInclude Include="SceneContext.h" />
<ClInclude Include="TextQuadObject.h" />
<ClInclude Include="TextTexture.h" />
<ClInclude Include="VisibilityMask.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="PbrModelObject.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="QuadLayerObject.cpp" />
<ClCompile Include="SceneObject.cpp" />
<ClCompile Include="Scene.cpp" />
<ClCompile Include="App.cpp" />
<ClCompile Include="ProjectionLayer.cpp" />
<ClCompile Include="StereoVisibleMask.cpp" />
<ClCompile Include="TextQuadObject.cpp" />
<ClCompile Include="TextTexture.cpp" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(SharedPath)\gltf\Gltf_uwp.vcxproj">
<Project>{63475578-0c83-4b2f-9ac5-a4513de2907f}</Project>
</ProjectReference>
<ProjectReference Include="$(SharedPath)\pbr\pbr_uwp.vcxproj">
<Project>{334e53b6-28dc-4f46-a7d9-ccec681f4feb}</Project>
</ProjectReference>
<ProjectReference Include="$(SharedPath)\SampleShared\SampleShared_uwp.vcxproj">
<Project>{7a3653fd-90a8-4627-9185-f3eefa539f49}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<FxCompile Include="StereoVisibleMaskVertexShader.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">5.0</ShaderModel>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
</ObjectFileOutput>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">5.0</ShaderModel>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
</ObjectFileOutput>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">5.0</ShaderModel>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
</ObjectFileOutput>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">5.0</ShaderModel>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
</ObjectFileOutput>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">5.0</ShaderModel>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
</ObjectFileOutput>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">5.0</ShaderModel>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
</ObjectFileOutput>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">5.0</ShaderModel>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</ObjectFileOutput>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|x64'">5.0</ShaderModel>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
</ObjectFileOutput>
</FxCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="pch.cpp" />
<ClCompile Include="App.cpp" />
<ClCompile Include="TextQuadObject.cpp">
<Filter>Objects</Filter>
</ClCompile>
<ClCompile Include="PbrModelObject.cpp">
<Filter>Objects</Filter>
</ClCompile>
<ClCompile Include="QuadLayerObject.cpp">
<Filter>Objects</Filter>
</ClCompile>
<ClCompile Include="SceneObject.cpp">
<Filter>Objects</Filter>
</ClCompile>
<ClCompile Include="StereoVisibleMask.cpp">
<Filter>Contexts</Filter>
</ClCompile>
<ClCompile Include="ProjectionLayer.cpp">
<Filter>Contexts</Filter>
</ClCompile>
<ClCompile Include="Scene.cpp" />
<ClCompile Include="TextTexture.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
<ClInclude Include="App.h" />
<ClInclude Include="TextQuadObject.h">
<Filter>Objects</Filter>
</ClInclude>
<ClInclude Include="PbrModelObject.h">
<Filter>Objects</Filter>
</ClInclude>
<ClInclude Include="QuadLayerObject.h">
<Filter>Objects</Filter>
</ClInclude>
<ClInclude Include="SceneObject.h">
<Filter>Objects</Filter>
</ClInclude>
<ClInclude Include="VisibilityMask.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="ProjectionLayer.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="CompositionLayers.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="FrameTime.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="Scene.h" />
<ClInclude Include="SceneContext.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="TextTexture.h" />
</ItemGroup>
<ItemGroup>
<Filter Include="Shaders">
<UniqueIdentifier>{d2e588b6-4392-42b8-aadc-9cb00ca97458}</UniqueIdentifier>
</Filter>
<Filter Include="Objects">
<UniqueIdentifier>{15a8b794-5b3c-4b3b-b082-ad2956aa9cee}</UniqueIdentifier>
</Filter>
<Filter Include="Contexts">
<UniqueIdentifier>{757d01b5-59f7-4d8a-8faa-53ea62f2ec25}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<FxCompile Include="StereoVisibleMaskVertexShader.hlsl">
<Filter>Shaders</Filter>
</FxCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,220 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM64">
<Configuration>Debug</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM64">
<Configuration>Release</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{A758AF22-F54F-4C74-BF85-05A377B5892E}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>XrSceneLib_win32</RootNamespace>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<ProjectName>XrSceneLib_win32</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)'=='Debug'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="TextTexture.h" />
<ClInclude Include="PbrModelObject.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="CompositionLayers.h" />
<ClInclude Include="ProjectionLayer.h" />
<ClInclude Include="QuadLayerObject.h" />
<ClInclude Include="Scene.h" />
<ClInclude Include="SceneObject.h" />
<ClInclude Include="App.h" />
<ClInclude Include="FrameTime.h" />
<ClInclude Include="SceneContext.h" />
<ClInclude Include="TextQuadObject.h" />
<ClInclude Include="VisibilityMask.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="TextTexture.cpp" />
<ClCompile Include="ProjectionLayer.cpp" />
<ClCompile Include="PbrModelObject.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="QuadLayerObject.cpp" />
<ClCompile Include="SceneObject.cpp" />
<ClCompile Include="Scene.cpp" />
<ClCompile Include="App.cpp" />
<ClCompile Include="StereoVisibleMask.cpp" />
<ClCompile Include="TextQuadObject.cpp" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(SharedPath)\gltf\Gltf_win32.vcxproj">
<Project>{6a3225a3-0750-47b7-8004-80ca543f8b8b}</Project>
</ProjectReference>
<ProjectReference Include="$(SharedPath)\pbr\pbr_win32.vcxproj">
<Project>{2b7688f8-9ae6-4a67-809b-1bac82094f21}</Project>
</ProjectReference>
<ProjectReference Include="$(SharedPath)\SampleShared\SampleShared_win32.vcxproj">
<Project>{269c12fa-e68d-470b-a734-4701034306bd}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<FxCompile Include="StereoVisibleMaskVertexShader.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">5.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">5.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">5.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">5.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">5.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">5.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">5.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Vertex</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|x64'">5.0</ShaderModel>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
</ObjectFileOutput>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
</ObjectFileOutput>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
</ObjectFileOutput>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
</ObjectFileOutput>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
</ObjectFileOutput>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
</ObjectFileOutput>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</ObjectFileOutput>
<VariableName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">g_%(Filename)</VariableName>
<HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(IntDir)\CompiledShaders\%(Filename).h</HeaderFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
</ObjectFileOutput>
</FxCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="pch.cpp" />
<ClCompile Include="Scene.cpp" />
<ClCompile Include="App.cpp" />
<ClCompile Include="PbrModelObject.cpp">
<Filter>Objects</Filter>
</ClCompile>
<ClCompile Include="QuadLayerObject.cpp">
<Filter>Objects</Filter>
</ClCompile>
<ClCompile Include="ProjectionLayer.cpp">
<Filter>Contexts</Filter>
</ClCompile>
<ClCompile Include="SceneObject.cpp">
<Filter>Objects</Filter>
</ClCompile>
<ClCompile Include="StereoVisibleMask.cpp">
<Filter>Contexts</Filter>
</ClCompile>
<ClCompile Include="TextQuadObject.cpp">
<Filter>Objects</Filter>
</ClCompile>
<ClCompile Include="TextTexture.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
<ClInclude Include="Scene.h" />
<ClInclude Include="App.h" />
<ClInclude Include="CompositionLayers.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="PbrModelObject.h">
<Filter>Objects</Filter>
</ClInclude>
<ClInclude Include="QuadLayerObject.h">
<Filter>Objects</Filter>
</ClInclude>
<ClInclude Include="ProjectionLayer.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="FrameTime.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="SceneContext.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="SceneObject.h">
<Filter>Objects</Filter>
</ClInclude>
<ClInclude Include="VisibilityMask.h">
<Filter>Contexts</Filter>
</ClInclude>
<ClInclude Include="TextQuadObject.h">
<Filter>Objects</Filter>
</ClInclude>
<ClInclude Include="TextTexture.h" />
</ItemGroup>
<ItemGroup>
<Filter Include="Shaders">
<UniqueIdentifier>{97338979-f582-471d-8f5e-10933ad9d0aa}</UniqueIdentifier>
</Filter>
<Filter Include="Contexts">
<UniqueIdentifier>{2e2f732d-d965-47b1-88cf-6f5085d0ff77}</UniqueIdentifier>
</Filter>
<Filter Include="Objects">
<UniqueIdentifier>{c8fee26b-99f6-4972-b4c7-59860905328d}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<FxCompile Include="StereoVisibleMaskVertexShader.hlsl">
<Filter>Shaders</Filter>
</FxCompile>
</ItemGroup>
<ItemGroup>
<None Include="$(OpenXRLoaderBinaryRoot)\bin\openxr_loader.dll" />
<None Include="packages.config" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenXR.Loader" version="1.0.6.2" targetFramework="native" />
</packages>

Просмотреть файл

@ -0,0 +1,16 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"

52
samples/XrSceneLib/pch.h Normal file
Просмотреть файл

@ -0,0 +1,52 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <sdkddkver.h>
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <exception>
#include <memory>
#include <tuple>
#include <vector>
#include <map>
#include <array>
#include <chrono>
#include <string>
#include <atomic>
#include <future>
#include <pathcch.h>
#include <initializer_list>
#include <optional>
#include <set>
#include <d3d11_2.h>
#include <DirectXMath.h>
#include <DirectXColors.h>
#define XR_USE_PLATFORM_WIN32
#define XR_USE_GRAPHICS_API_D3D11
#include <openxr/openxr.h>
#include <openxr/openxr_platform.h>
#include <XrUtility/XrError.h>
#include <XrUtility/XrMath.h>
#include <XrUtility/XrHandle.h>
#include <winrt/base.h> // for winrt::com_ptr

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,158 @@
//--------------------------------------------------------------------------------------
// File: DDSTextureLoader.h
//
// Functions for loading a DDS texture and creating a Direct3D runtime resource for it
//
// Note these functions are useful as a light-weight runtime loader for DDS files. For
// a full-featured DDS file reader, writer, and texture processing pipeline see
// the 'Texconv' sample and the 'DirectXTex' 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.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#include <stdint.h>
namespace DirectX
{
enum DDS_ALPHA_MODE
{
DDS_ALPHA_MODE_UNKNOWN = 0,
DDS_ALPHA_MODE_STRAIGHT = 1,
DDS_ALPHA_MODE_PREMULTIPLIED = 2,
DDS_ALPHA_MODE_OPAQUE = 3,
DDS_ALPHA_MODE_CUSTOM = 4,
};
// Standard version
HRESULT __cdecl CreateDDSTextureFromMemory(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
HRESULT __cdecl CreateDDSTextureFromFile(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
// Standard version with optional auto-gen mipmap support
HRESULT __cdecl CreateDDSTextureFromMemory(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
HRESULT __cdecl CreateDDSTextureFromFile(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
// Extended version
HRESULT __cdecl CreateDDSTextureFromMemoryEx(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
HRESULT __cdecl CreateDDSTextureFromFileEx(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
// Extended version with optional auto-gen mipmap support
HRESULT __cdecl CreateDDSTextureFromMemoryEx(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
HRESULT __cdecl CreateDDSTextureFromFileEx(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
}

Просмотреть файл

@ -0,0 +1,150 @@
//--------------------------------------------------------------------------------------
// File: DirectXHelpers.h
//
// 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.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#else
#include <d3d11_1.h>
#endif
#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) )
#if !defined(_XBOX_ONE) || !defined(_TITLE)
#pragma comment(lib,"dxguid.lib")
#endif
#endif
#ifndef IID_GRAPHICS_PPV_ARGS
#define IID_GRAPHICS_PPV_ARGS(x) IID_PPV_ARGS(x)
#endif
#include <exception>
#include <stdint.h>
//
// The core Direct3D headers provide the following helper C++ classes
// CD3D11_RECT
// CD3D11_BOX
// CD3D11_DEPTH_STENCIL_DESC
// CD3D11_BLEND_DESC, CD3D11_BLEND_DESC1
// CD3D11_RASTERIZER_DESC, CD3D11_RASTERIZER_DESC1
// CD3D11_BUFFER_DESC
// CD3D11_TEXTURE1D_DESC
// CD3D11_TEXTURE2D_DESC
// CD3D11_TEXTURE3D_DESC
// CD3D11_SHADER_RESOURCE_VIEW_DESC
// CD3D11_RENDER_TARGET_VIEW_DESC
// CD3D11_VIEWPORT
// CD3D11_DEPTH_STENCIL_VIEW_DESC
// CD3D11_UNORDERED_ACCESS_VIEW_DESC
// CD3D11_SAMPLER_DESC
// CD3D11_QUERY_DESC
// CD3D11_COUNTER_DESC
//
namespace DirectX
{
// simliar to std::lock_guard for exception-safe Direct3D resource locking
class MapGuard : public D3D11_MAPPED_SUBRESOURCE
{
public:
MapGuard( _In_ ID3D11DeviceContext* context,
_In_ ID3D11Resource *resource,
_In_ UINT subresource,
_In_ D3D11_MAP mapType,
_In_ UINT mapFlags )
: mContext(context), mResource(resource), mSubresource(subresource)
{
HRESULT hr = mContext->Map( resource, subresource, mapType, mapFlags, this );
if (FAILED(hr))
{
throw std::exception();
}
}
~MapGuard()
{
mContext->Unmap( mResource, mSubresource );
}
uint8_t* get() const
{
return reinterpret_cast<uint8_t*>( pData );
}
uint8_t* get(size_t slice) const
{
return reinterpret_cast<uint8_t*>( pData ) + ( slice * DepthPitch );
}
uint8_t* scanline(size_t row) const
{
return reinterpret_cast<uint8_t*>( pData ) + ( row * RowPitch );
}
uint8_t* scanline(size_t slice, size_t row) const
{
return reinterpret_cast<uint8_t*>( pData ) + ( slice * DepthPitch ) + ( row * RowPitch );
}
private:
ID3D11DeviceContext* mContext;
ID3D11Resource* mResource;
UINT mSubresource;
MapGuard(MapGuard const&);
MapGuard& operator= (MapGuard const&);
};
// Helper sets a D3D resource name string (used by PIX and debug layer leak reporting).
template<UINT TNameLength>
inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_z_ const char (&name)[TNameLength])
{
#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) )
#if defined(_XBOX_ONE) && defined(_TITLE)
wchar_t wname[MAX_PATH];
int result = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, name, TNameLength, wname, MAX_PATH );
if ( result > 0 )
{
resource->SetName( wname );
}
#else
resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name);
#endif
#else
UNREFERENCED_PARAMETER(resource);
UNREFERENCED_PARAMETER(name);
#endif
}
template<UINT TNameLength>
inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_z_ const wchar_t (&name)[TNameLength])
{
#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) )
#if defined(_XBOX_ONE) && defined(_TITLE)
resource->SetName( name );
#else
char aname[MAX_PATH];
int result = WideCharToMultiByte( CP_ACP, 0, name, TNameLength, aname, MAX_PATH, nullptr, nullptr );
if ( result > 0 )
{
resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, aname);
}
#endif
#else
UNREFERENCED_PARAMETER(resource);
UNREFERENCED_PARAMETER(name);
#endif
}
}

Просмотреть файл

@ -0,0 +1,850 @@
//--------------------------------------------------------------------------------------
// File: LoaderHelpers.h
//
// Helper functions for texture loaders and screen grabber
//
// 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.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#include "DDS.h"
#include "DDSTextureLoader.h"
// clang-format off
namespace DirectX
{
namespace LoaderHelpers
{
//--------------------------------------------------------------------------------------
// Return the BPP for a particular format
//--------------------------------------------------------------------------------------
inline size_t BitsPerPixel(_In_ DXGI_FORMAT fmt)
{
switch (fmt)
{
case DXGI_FORMAT_R32G32B32A32_TYPELESS:
case DXGI_FORMAT_R32G32B32A32_FLOAT:
case DXGI_FORMAT_R32G32B32A32_UINT:
case DXGI_FORMAT_R32G32B32A32_SINT:
return 128;
case DXGI_FORMAT_R32G32B32_TYPELESS:
case DXGI_FORMAT_R32G32B32_FLOAT:
case DXGI_FORMAT_R32G32B32_UINT:
case DXGI_FORMAT_R32G32B32_SINT:
return 96;
case DXGI_FORMAT_R16G16B16A16_TYPELESS:
case DXGI_FORMAT_R16G16B16A16_FLOAT:
case DXGI_FORMAT_R16G16B16A16_UNORM:
case DXGI_FORMAT_R16G16B16A16_UINT:
case DXGI_FORMAT_R16G16B16A16_SNORM:
case DXGI_FORMAT_R16G16B16A16_SINT:
case DXGI_FORMAT_R32G32_TYPELESS:
case DXGI_FORMAT_R32G32_FLOAT:
case DXGI_FORMAT_R32G32_UINT:
case DXGI_FORMAT_R32G32_SINT:
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_Y416:
case DXGI_FORMAT_Y210:
case DXGI_FORMAT_Y216:
return 64;
case DXGI_FORMAT_R10G10B10A2_TYPELESS:
case DXGI_FORMAT_R10G10B10A2_UNORM:
case DXGI_FORMAT_R10G10B10A2_UINT:
case DXGI_FORMAT_R11G11B10_FLOAT:
case DXGI_FORMAT_R8G8B8A8_TYPELESS:
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT_R8G8B8A8_UINT:
case DXGI_FORMAT_R8G8B8A8_SNORM:
case DXGI_FORMAT_R8G8B8A8_SINT:
case DXGI_FORMAT_R16G16_TYPELESS:
case DXGI_FORMAT_R16G16_FLOAT:
case DXGI_FORMAT_R16G16_UNORM:
case DXGI_FORMAT_R16G16_UINT:
case DXGI_FORMAT_R16G16_SNORM:
case DXGI_FORMAT_R16G16_SINT:
case DXGI_FORMAT_R32_TYPELESS:
case DXGI_FORMAT_D32_FLOAT:
case DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT_R32_UINT:
case DXGI_FORMAT_R32_SINT:
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_R9G9B9E5_SHAREDEXP:
case DXGI_FORMAT_R8G8_B8G8_UNORM:
case DXGI_FORMAT_G8R8_G8B8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_B8G8R8X8_UNORM:
case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
case DXGI_FORMAT_B8G8R8A8_TYPELESS:
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
case DXGI_FORMAT_B8G8R8X8_TYPELESS:
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
case DXGI_FORMAT_AYUV:
case DXGI_FORMAT_Y410:
case DXGI_FORMAT_YUY2:
return 32;
case DXGI_FORMAT_P010:
case DXGI_FORMAT_P016:
return 24;
case DXGI_FORMAT_R8G8_TYPELESS:
case DXGI_FORMAT_R8G8_UNORM:
case DXGI_FORMAT_R8G8_UINT:
case DXGI_FORMAT_R8G8_SNORM:
case DXGI_FORMAT_R8G8_SINT:
case DXGI_FORMAT_R16_TYPELESS:
case DXGI_FORMAT_R16_FLOAT:
case DXGI_FORMAT_D16_UNORM:
case DXGI_FORMAT_R16_UNORM:
case DXGI_FORMAT_R16_UINT:
case DXGI_FORMAT_R16_SNORM:
case DXGI_FORMAT_R16_SINT:
case DXGI_FORMAT_B5G6R5_UNORM:
case DXGI_FORMAT_B5G5R5A1_UNORM:
case DXGI_FORMAT_A8P8:
case DXGI_FORMAT_B4G4R4A4_UNORM:
return 16;
case DXGI_FORMAT_NV12:
case DXGI_FORMAT_420_OPAQUE:
case DXGI_FORMAT_NV11:
return 12;
case DXGI_FORMAT_R8_TYPELESS:
case DXGI_FORMAT_R8_UNORM:
case DXGI_FORMAT_R8_UINT:
case DXGI_FORMAT_R8_SNORM:
case DXGI_FORMAT_R8_SINT:
case DXGI_FORMAT_A8_UNORM:
case DXGI_FORMAT_AI44:
case DXGI_FORMAT_IA44:
case DXGI_FORMAT_P8:
return 8;
case DXGI_FORMAT_R1_UNORM:
return 1;
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT_BC4_SNORM:
return 4;
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_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT_BC5_SNORM:
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:
return 8;
#if defined(_XBOX_ONE) && defined(_TITLE)
case DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT:
case DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT:
case DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM:
return 32;
case DXGI_FORMAT_D16_UNORM_S8_UINT:
case DXGI_FORMAT_R16_UNORM_X8_TYPELESS:
case DXGI_FORMAT_X16_TYPELESS_G8_UINT:
return 24;
case DXGI_FORMAT_R4G4_UNORM:
return 8;
#endif // _XBOX_ONE && _TITLE
default:
return 0;
}
}
//--------------------------------------------------------------------------------------
inline DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM:
return DXGI_FORMAT_R8G8B8A8_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_B8G8R8A8_UNORM:
return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
case DXGI_FORMAT_B8G8R8X8_UNORM:
return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
case DXGI_FORMAT_BC7_UNORM:
return DXGI_FORMAT_BC7_UNORM_SRGB;
default:
return format;
}
}
//--------------------------------------------------------------------------------------
inline bool IsCompressed(_In_ DXGI_FORMAT fmt)
{
switch (fmt)
{
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_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:
return true;
default:
return false;
}
}
//--------------------------------------------------------------------------------------
inline DXGI_FORMAT EnsureNotTypeless(DXGI_FORMAT fmt)
{
// Assumes UNORM or FLOAT; doesn't use UINT or SINT
switch (fmt)
{
case DXGI_FORMAT_R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_FLOAT;
case DXGI_FORMAT_R32G32B32_TYPELESS: return DXGI_FORMAT_R32G32B32_FLOAT;
case DXGI_FORMAT_R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_UNORM;
case DXGI_FORMAT_R32G32_TYPELESS: return DXGI_FORMAT_R32G32_FLOAT;
case DXGI_FORMAT_R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_UNORM;
case DXGI_FORMAT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_UNORM;
case DXGI_FORMAT_R16G16_TYPELESS: return DXGI_FORMAT_R16G16_UNORM;
case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_R32_FLOAT;
case DXGI_FORMAT_R8G8_TYPELESS: return DXGI_FORMAT_R8G8_UNORM;
case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_R16_UNORM;
case DXGI_FORMAT_R8_TYPELESS: return DXGI_FORMAT_R8_UNORM;
case DXGI_FORMAT_BC1_TYPELESS: return DXGI_FORMAT_BC1_UNORM;
case DXGI_FORMAT_BC2_TYPELESS: return DXGI_FORMAT_BC2_UNORM;
case DXGI_FORMAT_BC3_TYPELESS: return DXGI_FORMAT_BC3_UNORM;
case DXGI_FORMAT_BC4_TYPELESS: return DXGI_FORMAT_BC4_UNORM;
case DXGI_FORMAT_BC5_TYPELESS: return DXGI_FORMAT_BC5_UNORM;
case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM;
case DXGI_FORMAT_B8G8R8X8_TYPELESS: return DXGI_FORMAT_B8G8R8X8_UNORM;
case DXGI_FORMAT_BC7_TYPELESS: return DXGI_FORMAT_BC7_UNORM;
default: return fmt;
}
}
//--------------------------------------------------------------------------------------
inline HRESULT LoadTextureDataFromFile(_In_z_ const wchar_t* fileName,
std::unique_ptr<uint8_t[]>& ddsData,
const DDS_HEADER** header,
const uint8_t** bitData,
size_t* bitSize
)
{
if (!header || !bitData || !bitSize)
{
return E_POINTER;
}
// open the file
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
ScopedHandle hFile(safe_handle(CreateFile2(fileName,
GENERIC_READ,
FILE_SHARE_READ,
OPEN_EXISTING,
nullptr)));
#else
ScopedHandle hFile(safe_handle(CreateFileW(fileName,
GENERIC_READ,
FILE_SHARE_READ,
nullptr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
nullptr)));
#endif
if (!hFile)
{
return HRESULT_FROM_WIN32(GetLastError());
}
// Get the file size
FILE_STANDARD_INFO fileInfo;
if (!GetFileInformationByHandleEx(hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo)))
{
return HRESULT_FROM_WIN32(GetLastError());
}
// File is too big for 32-bit allocation, so reject read
if (fileInfo.EndOfFile.HighPart > 0)
{
return E_FAIL;
}
// Need at least enough data to fill the header and magic number to be a valid DDS
if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t)))
{
return E_FAIL;
}
// create enough space for the file data
ddsData.reset(new (std::nothrow) uint8_t[fileInfo.EndOfFile.LowPart]);
if (!ddsData)
{
return E_OUTOFMEMORY;
}
// read the data in
DWORD BytesRead = 0;
if (!ReadFile(hFile.get(),
ddsData.get(),
fileInfo.EndOfFile.LowPart,
&BytesRead,
nullptr
))
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (BytesRead < fileInfo.EndOfFile.LowPart)
{
return E_FAIL;
}
// DDS files always start with the same magic number ("DDS ")
uint32_t dwMagicNumber = *reinterpret_cast<const uint32_t*>(ddsData.get());
if (dwMagicNumber != DDS_MAGIC)
{
return E_FAIL;
}
auto hdr = reinterpret_cast<const DDS_HEADER*>(ddsData.get() + sizeof(uint32_t));
// Verify header to validate DDS file
if (hdr->size != sizeof(DDS_HEADER) ||
hdr->ddspf.size != sizeof(DDS_PIXELFORMAT))
{
return E_FAIL;
}
// Check for DX10 extension
bool bDXT10Header = false;
if ((hdr->ddspf.flags & DDS_FOURCC) &&
(MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.fourCC))
{
// Must be long enough for both headers and magic value
if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10)))
{
return E_FAIL;
}
bDXT10Header = true;
}
// setup the pointers in the process request
*header = hdr;
ptrdiff_t offset = sizeof(uint32_t) + sizeof(DDS_HEADER)
+ (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);
*bitData = ddsData.get() + offset;
*bitSize = fileInfo.EndOfFile.LowPart - offset;
return S_OK;
}
//--------------------------------------------------------------------------------------
// Get surface information for a particular format
//--------------------------------------------------------------------------------------
inline void GetSurfaceInfo(_In_ size_t width,
_In_ size_t height,
_In_ DXGI_FORMAT fmt,
_Out_opt_ size_t* outNumBytes,
_Out_opt_ size_t* outRowBytes,
_Out_opt_ size_t* outNumRows)
{
size_t numBytes = 0;
size_t rowBytes = 0;
size_t numRows = 0;
bool bc = false;
bool packed = false;
bool planar = false;
size_t bpe = 0;
switch (fmt)
{
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT_BC4_SNORM:
bc = true;
bpe = 8;
break;
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_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT_BC5_SNORM:
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:
bc = true;
bpe = 16;
break;
case DXGI_FORMAT_R8G8_B8G8_UNORM:
case DXGI_FORMAT_G8R8_G8B8_UNORM:
case DXGI_FORMAT_YUY2:
packed = true;
bpe = 4;
break;
case DXGI_FORMAT_Y210:
case DXGI_FORMAT_Y216:
packed = true;
bpe = 8;
break;
case DXGI_FORMAT_NV12:
case DXGI_FORMAT_420_OPAQUE:
planar = true;
bpe = 2;
break;
case DXGI_FORMAT_P010:
case DXGI_FORMAT_P016:
planar = true;
bpe = 4;
break;
#if defined(_XBOX_ONE) && defined(_TITLE)
case DXGI_FORMAT_D16_UNORM_S8_UINT:
case DXGI_FORMAT_R16_UNORM_X8_TYPELESS:
case DXGI_FORMAT_X16_TYPELESS_G8_UINT:
planar = true;
bpe = 4;
break;
#endif
default:
break;
}
if (bc)
{
size_t numBlocksWide = 0;
if (width > 0)
{
numBlocksWide = std::max<size_t>(1, (width + 3) / 4);
}
size_t numBlocksHigh = 0;
if (height > 0)
{
numBlocksHigh = std::max<size_t>(1, (height + 3) / 4);
}
rowBytes = numBlocksWide * bpe;
numRows = numBlocksHigh;
numBytes = rowBytes * numBlocksHigh;
}
else if (packed)
{
rowBytes = ((width + 1) >> 1) * bpe;
numRows = height;
numBytes = rowBytes * height;
}
else if (fmt == DXGI_FORMAT_NV11)
{
rowBytes = ((width + 3) >> 2) * 4;
numRows = height * 2; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data
numBytes = rowBytes * numRows;
}
else if (planar)
{
rowBytes = ((width + 1) >> 1) * bpe;
numBytes = (rowBytes * height) + ((rowBytes * height + 1) >> 1);
numRows = height + ((height + 1) >> 1);
}
else
{
size_t bpp = BitsPerPixel(fmt);
rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
numRows = height;
numBytes = rowBytes * height;
}
if (outNumBytes)
{
*outNumBytes = numBytes;
}
if (outRowBytes)
{
*outRowBytes = rowBytes;
}
if (outNumRows)
{
*outNumRows = numRows;
}
}
//--------------------------------------------------------------------------------------
#define ISBITMASK( r,g,b,a ) ( ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a )
inline DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf)
{
if (ddpf.flags & DDS_RGB)
{
// Note that sRGB formats are written using the "DX10" extended header
switch (ddpf.RGBBitCount)
{
case 32:
if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
{
return DXGI_FORMAT_R8G8B8A8_UNORM;
}
if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
{
return DXGI_FORMAT_B8G8R8A8_UNORM;
}
if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000))
{
return DXGI_FORMAT_B8G8R8X8_UNORM;
}
// No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0x00000000) aka D3DFMT_X8B8G8R8
// Note that many common DDS reader/writers (including D3DX) swap the
// the RED/BLUE masks for 10:10:10:2 formats. We assume
// below that the 'backwards' header mask is being used since it is most
// likely written by D3DX. The more robust solution is to use the 'DX10'
// header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
// For 'correct' writers, this should be 0x000003ff,0x000ffc00,0x3ff00000 for RGB data
if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000))
{
return DXGI_FORMAT_R10G10B10A2_UNORM;
}
// No DXGI format maps to ISBITMASK(0x000003ff,0x000ffc00,0x3ff00000,0xc0000000) aka D3DFMT_A2R10G10B10
if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
{
return DXGI_FORMAT_R16G16_UNORM;
}
if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000))
{
// Only 32-bit color channel format in D3D9 was R32F
return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
}
break;
case 24:
// No 24bpp DXGI formats aka D3DFMT_R8G8B8
break;
case 16:
if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000))
{
return DXGI_FORMAT_B5G5R5A1_UNORM;
}
if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000))
{
return DXGI_FORMAT_B5G6R5_UNORM;
}
// No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0x0000) aka D3DFMT_X1R5G5B5
if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000))
{
return DXGI_FORMAT_B4G4R4A4_UNORM;
}
// No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0x0000) aka D3DFMT_X4R4G4B4
// No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
break;
}
}
else if (ddpf.flags & DDS_LUMINANCE)
{
if (8 == ddpf.RGBBitCount)
{
if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000))
{
return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
}
// No DXGI format maps to ISBITMASK(0x0f,0x00,0x00,0xf0) aka D3DFMT_A4L4
if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
{
return DXGI_FORMAT_R8G8_UNORM; // Some DDS writers assume the bitcount should be 8 instead of 16
}
}
if (16 == ddpf.RGBBitCount)
{
if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
{
return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
}
if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
{
return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
}
}
}
else if (ddpf.flags & DDS_ALPHA)
{
if (8 == ddpf.RGBBitCount)
{
return DXGI_FORMAT_A8_UNORM;
}
}
else if (ddpf.flags & DDS_BUMPDUDV)
{
if (16 == ddpf.RGBBitCount)
{
if (ISBITMASK(0x00ff, 0xff00, 0x0000, 0x0000))
{
return DXGI_FORMAT_R8G8_SNORM; // D3DX10/11 writes this out as DX10 extension
}
}
if (32 == ddpf.RGBBitCount)
{
if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
{
return DXGI_FORMAT_R8G8B8A8_SNORM; // D3DX10/11 writes this out as DX10 extension
}
if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
{
return DXGI_FORMAT_R16G16_SNORM; // D3DX10/11 writes this out as DX10 extension
}
// No DXGI format maps to ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000) aka D3DFMT_A2W10V10U10
}
}
else if (ddpf.flags & DDS_FOURCC)
{
if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC)
{
return DXGI_FORMAT_BC1_UNORM;
}
if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC)
{
return DXGI_FORMAT_BC2_UNORM;
}
if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC)
{
return DXGI_FORMAT_BC3_UNORM;
}
// While pre-multiplied alpha isn't directly supported by the DXGI formats,
// they are basically the same as these BC formats so they can be mapped
if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC)
{
return DXGI_FORMAT_BC2_UNORM;
}
if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC)
{
return DXGI_FORMAT_BC3_UNORM;
}
if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC)
{
return DXGI_FORMAT_BC4_UNORM;
}
if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC)
{
return DXGI_FORMAT_BC4_UNORM;
}
if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC)
{
return DXGI_FORMAT_BC4_SNORM;
}
if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC)
{
return DXGI_FORMAT_BC5_UNORM;
}
if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC)
{
return DXGI_FORMAT_BC5_UNORM;
}
if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC)
{
return DXGI_FORMAT_BC5_SNORM;
}
// BC6H and BC7 are written using the "DX10" extended header
if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC)
{
return DXGI_FORMAT_R8G8_B8G8_UNORM;
}
if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC)
{
return DXGI_FORMAT_G8R8_G8B8_UNORM;
}
if (MAKEFOURCC('Y', 'U', 'Y', '2') == ddpf.fourCC)
{
return DXGI_FORMAT_YUY2;
}
// Check for D3DFORMAT enums being set here
switch (ddpf.fourCC)
{
case 36: // D3DFMT_A16B16G16R16
return DXGI_FORMAT_R16G16B16A16_UNORM;
case 110: // D3DFMT_Q16W16V16U16
return DXGI_FORMAT_R16G16B16A16_SNORM;
case 111: // D3DFMT_R16F
return DXGI_FORMAT_R16_FLOAT;
case 112: // D3DFMT_G16R16F
return DXGI_FORMAT_R16G16_FLOAT;
case 113: // D3DFMT_A16B16G16R16F
return DXGI_FORMAT_R16G16B16A16_FLOAT;
case 114: // D3DFMT_R32F
return DXGI_FORMAT_R32_FLOAT;
case 115: // D3DFMT_G32R32F
return DXGI_FORMAT_R32G32_FLOAT;
case 116: // D3DFMT_A32B32G32R32F
return DXGI_FORMAT_R32G32B32A32_FLOAT;
}
}
return DXGI_FORMAT_UNKNOWN;
}
#undef ISBITMASK
//--------------------------------------------------------------------------------------
inline DirectX::DDS_ALPHA_MODE GetAlphaMode(_In_ const DDS_HEADER* header)
{
if (header->ddspf.flags & DDS_FOURCC)
{
if (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)
{
auto d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
auto mode = static_cast<DDS_ALPHA_MODE>(d3d10ext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK);
switch (mode)
{
case DDS_ALPHA_MODE_STRAIGHT:
case DDS_ALPHA_MODE_PREMULTIPLIED:
case DDS_ALPHA_MODE_OPAQUE:
case DDS_ALPHA_MODE_CUSTOM:
return mode;
default:
break;
}
}
else if ((MAKEFOURCC('D', 'X', 'T', '2') == header->ddspf.fourCC)
|| (MAKEFOURCC('D', 'X', 'T', '4') == header->ddspf.fourCC))
{
return DDS_ALPHA_MODE_PREMULTIPLIED;
}
}
return DDS_ALPHA_MODE_UNKNOWN;
}
//--------------------------------------------------------------------------------------
class auto_delete_file
{
public:
auto_delete_file(HANDLE hFile) : m_handle(hFile) {}
auto_delete_file(const auto_delete_file&) = delete;
auto_delete_file& operator=(const auto_delete_file&) = delete;
~auto_delete_file()
{
if (m_handle)
{
FILE_DISPOSITION_INFO info = {};
info.DeleteFile = TRUE;
(void)SetFileInformationByHandle(m_handle, FileDispositionInfo, &info, sizeof(info));
}
}
void clear() { m_handle = 0; }
private:
HANDLE m_handle;
};
}
}

Просмотреть файл

@ -0,0 +1,152 @@
//--------------------------------------------------------------------------------------
// File: PlatformHelpers.h
//
// 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.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#pragma warning(disable : 4324)
#include <exception>
#include <memory>
namespace DirectX
{
// Helper class for COM exceptions
class com_exception : public std::exception
{
public:
com_exception(HRESULT hr) : result(hr) {}
virtual const char* what() const override
{
static char s_str[64] = {};
sprintf_s(s_str, "Failure with HRESULT of %08X", static_cast<unsigned int>(result));
return s_str;
}
private:
HRESULT result;
};
// Helper utility converts D3D API failures into exceptions.
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
throw com_exception(hr);
}
}
// Helper for output debug tracing
inline void DebugTrace( _In_z_ _Printf_format_string_ const char* format, ... )
{
#ifdef _DEBUG
va_list args;
va_start( args, format );
char buff[1024] = {};
vsprintf_s( buff, format, args );
OutputDebugStringA( buff );
va_end( args );
#else
UNREFERENCED_PARAMETER( format );
#endif
}
// Helper smart-pointers
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) || (defined(_XBOX_ONE) && defined(_TITLE)) || !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)
struct virtual_deleter { void operator()(void* p) { if (p) VirtualFree(p, 0, MEM_RELEASE); } };
#endif
struct aligned_deleter { void operator()(void* p) { _aligned_free(p); } };
struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } };
typedef std::unique_ptr<void, handle_closer> ScopedHandle;
inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; }
}
#ifdef DIRECTX_EMULATE_MUTEX
// Emulate the C++0x mutex and lock_guard types when building with Visual Studio CRT versions < 2012.
namespace std
{
class mutex
{
public:
mutex() { InitializeCriticalSection(&mCriticalSection); }
~mutex() { DeleteCriticalSection(&mCriticalSection); }
void lock() { EnterCriticalSection(&mCriticalSection); }
void unlock() { LeaveCriticalSection(&mCriticalSection); }
bool try_lock() { return TryEnterCriticalSection(&mCriticalSection) != 0; }
private:
CRITICAL_SECTION mCriticalSection;
mutex(mutex const&);
mutex& operator= (mutex const&);
};
template<typename Mutex>
class lock_guard
{
public:
typedef Mutex mutex_type;
explicit lock_guard(mutex_type& mutex)
: mMutex(mutex)
{
mMutex.lock();
}
~lock_guard()
{
mMutex.unlock();
}
private:
mutex_type& mMutex;
lock_guard(lock_guard const&);
lock_guard& operator= (lock_guard const&);
};
}
#else
#include <mutex>
#endif
#ifdef DIRECTX_EMULATE_MAKE_UNIQUE
// Emulate make_unique when building with Visual Studio CRT versions < 2012.
namespace std
{
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
#endif

Просмотреть файл

@ -0,0 +1,228 @@
//--------------------------------------------------------------------------------------
// dds.h
//
// This header defines constants and structures that are useful when parsing
// DDS files. DDS files were originally designed to use several structures
// and constants that are native to DirectDraw and are defined in ddraw.h,
// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar
// (compatible) constants and structures so that one can use DDS files
// without needing to include ddraw.h.
//
// 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.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
namespace DirectX
{
#pragma pack(push,1)
const uint32_t DDS_MAGIC = 0x20534444; // "DDS "
struct DDS_PIXELFORMAT
{
uint32_t size;
uint32_t flags;
uint32_t fourCC;
uint32_t RGBBitCount;
uint32_t RBitMask;
uint32_t GBitMask;
uint32_t BBitMask;
uint32_t ABitMask;
};
#define DDS_FOURCC 0x00000004 // DDPF_FOURCC
#define DDS_RGB 0x00000040 // DDPF_RGB
#define DDS_RGBA 0x00000041 // DDPF_RGB | DDPF_ALPHAPIXELS
#define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE
#define DDS_LUMINANCEA 0x00020001 // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
#define DDS_ALPHA 0x00000002 // DDPF_ALPHA
#define DDS_PAL8 0x00000020 // DDPF_PALETTEINDEXED8
#define DDS_BUMPDUDV 0x00080000 // DDPF_BUMPDUDV
#ifndef MAKEFOURCC
#define MAKEFOURCC(ch0, ch1, ch2, ch3) \
((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \
((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 ))
#endif /* defined(MAKEFOURCC) */
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT1 =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT2 =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','2'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT3 =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT4 =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','4'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT5 =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_UNORM =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','U'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_SNORM =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','S'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_UNORM =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','U'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_SNORM =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','S'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8_B8G8 =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('R','G','B','G'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G8R8_G8B8 =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('G','R','G','B'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_YUY2 =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('Y','U','Y','2'), 0, 0, 0, 0, 0 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R8G8B8 =
{ sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8R8G8B8 =
{ sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8B8G8R8 =
{ sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8B8G8R8 =
{ sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G16R16 =
{ sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R5G6B5 =
{ sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0000f800, 0x000007e0, 0x0000001f, 0x00000000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A1R5G5B5 =
{ sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00007c00, 0x000003e0, 0x0000001f, 0x00008000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4R4G4B4 =
{ sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00000f00, 0x000000f0, 0x0000000f, 0x0000f000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8B8 =
{ sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 24, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L8 =
{ sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0x00, 0x00, 0x00 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L16 =
{ sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 16, 0xffff, 0x0000, 0x0000, 0x0000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8 =
{ sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 16, 0x00ff, 0x0000, 0x0000, 0xff00 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8 =
{ sizeof(DDS_PIXELFORMAT), DDS_ALPHA, 0, 8, 0x00, 0x00, 0x00, 0xff };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V8U8 =
{ sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 16, 0x00ff, 0xff00, 0x0000, 0x0000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_Q8W8V8U8 =
{ sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 };
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V16U16 =
{ sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 };
// D3DFMT_A2R10G10B10/D3DFMT_A2B10G10R10 should be written using DX10 extension to avoid D3DX 10:10:10:2 reversal issue
// This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat)
extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 };
#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
#define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT
#define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH
#define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH
#define DDS_HEADER_FLAGS_LINEARSIZE 0x00080000 // DDSD_LINEARSIZE
#define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
#define DDS_WIDTH 0x00000004 // DDSD_WIDTH
#define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
#define DDS_SURFACE_FLAGS_MIPMAP 0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
#define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
#define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
#define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
#define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
#define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
#define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
#define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
#define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ )
#define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
#define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
// Subset here matches D3D10_RESOURCE_DIMENSION and D3D11_RESOURCE_DIMENSION
enum DDS_RESOURCE_DIMENSION
{
DDS_DIMENSION_TEXTURE1D = 2,
DDS_DIMENSION_TEXTURE2D = 3,
DDS_DIMENSION_TEXTURE3D = 4,
};
// Subset here matches D3D10_RESOURCE_MISC_FLAG and D3D11_RESOURCE_MISC_FLAG
enum DDS_RESOURCE_MISC_FLAG
{
DDS_RESOURCE_MISC_TEXTURECUBE = 0x4L,
};
enum DDS_MISC_FLAGS2
{
DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L,
};
struct DDS_HEADER
{
uint32_t size;
uint32_t flags;
uint32_t height;
uint32_t width;
uint32_t pitchOrLinearSize;
uint32_t depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
uint32_t mipMapCount;
uint32_t reserved1[11];
DDS_PIXELFORMAT ddspf;
uint32_t caps;
uint32_t caps2;
uint32_t caps3;
uint32_t caps4;
uint32_t reserved2;
};
struct DDS_HEADER_DXT10
{
DXGI_FORMAT dxgiFormat;
uint32_t resourceDimension;
uint32_t miscFlag; // see D3D11_RESOURCE_MISC_FLAG
uint32_t arraySize;
uint32_t miscFlags2; // see DDS_MISC_FLAGS2
} ;
#pragma pack(pop)
static_assert( sizeof(DDS_HEADER) == 124, "DDS Header size mismatch" );
static_assert( sizeof(DDS_HEADER_DXT10) == 20, "DDS DX10 Extended Header size mismatch");
} // namespace

Просмотреть файл

@ -0,0 +1,176 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "DxUtility.h"
#include <D3Dcompiler.h>
#pragma comment(lib, "D3DCompiler.lib")
namespace sample::dx {
winrt::com_ptr<IDXGIAdapter1> GetAdapter(LUID adapterId) {
// Create the DXGI factory.
winrt::com_ptr<IDXGIFactory1> dxgiFactory;
CHECK_HRCMD(CreateDXGIFactory1(winrt::guid_of<IDXGIFactory1>(), dxgiFactory.put_void()));
for (UINT adapterIndex = 0;; adapterIndex++) {
// EnumAdapters1 will fail with DXGI_ERROR_NOT_FOUND when there are no more adapters to enumerate.
winrt::com_ptr<IDXGIAdapter1> dxgiAdapter;
CHECK_HRCMD(dxgiFactory->EnumAdapters1(adapterIndex, dxgiAdapter.put()));
DXGI_ADAPTER_DESC1 adapterDesc;
CHECK_HRCMD(dxgiAdapter->GetDesc1(&adapterDesc));
if (memcmp(&adapterDesc.AdapterLuid, &adapterId, sizeof(adapterId)) == 0) {
DEBUG_PRINT("Using graphics adapter %ws", adapterDesc.Description);
return dxgiAdapter;
}
}
}
void CreateD3D11DeviceAndContext(IDXGIAdapter1* adapter,
const std::vector<D3D_FEATURE_LEVEL>& featureLevels,
bool singleThreaded,
ID3D11Device** device,
ID3D11DeviceContext** deviceContext) {
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
if (singleThreaded) {
creationFlags |= D3D11_CREATE_DEVICE_SINGLETHREADED;
}
#ifdef _DEBUG
creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
// Create the Direct3D 11 API device object and a corresponding context.
D3D_DRIVER_TYPE driverType = adapter == nullptr ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN;
TryAgain:
const HRESULT hr = D3D11CreateDevice(adapter,
driverType,
0,
creationFlags,
featureLevels.data(),
(UINT)featureLevels.size(),
D3D11_SDK_VERSION,
device,
nullptr,
deviceContext);
if (FAILED(hr)) {
// If initialization failed, it may be because device debugging isn't supported, so retry without that.
if ((creationFlags & D3D11_CREATE_DEVICE_DEBUG) && (hr == DXGI_ERROR_SDK_COMPONENT_MISSING)) {
creationFlags &= ~D3D11_CREATE_DEVICE_DEBUG;
goto TryAgain;
}
// If the initialization still fails, fall back to the WARP device.
// For more information on WARP, see: http://go.microsoft.com/fwlink/?LinkId=286690
if (driverType != D3D_DRIVER_TYPE_WARP) {
driverType = D3D_DRIVER_TYPE_WARP;
goto TryAgain;
}
}
if (!singleThreaded) {
winrt::com_ptr<ID3D11Device> comPtr;
comPtr.copy_from(*device);
winrt::com_ptr<ID3D11Multithread> d3dMultiThread = comPtr.try_as<ID3D11Multithread>();
if (d3dMultiThread) {
d3dMultiThread->SetMultithreadProtected(true);
}
}
}
winrt::com_ptr<ID3DBlob> CompileShader(const char* hlsl, const char* entrypoint, const char* shaderTarget) {
winrt::com_ptr<ID3DBlob> compiled;
winrt::com_ptr<ID3DBlob> errMsgs;
DWORD flags = D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS;
#ifdef _DEBUG
flags |= D3DCOMPILE_SKIP_OPTIMIZATION | D3DCOMPILE_DEBUG;
#else
flags |= D3DCOMPILE_OPTIMIZATION_LEVEL3;
#endif
HRESULT hr =
D3DCompile(hlsl, strlen(hlsl), nullptr, nullptr, nullptr, entrypoint, shaderTarget, flags, 0, compiled.put(), errMsgs.put());
if (FAILED(hr)) {
std::string errMsg((const char*)errMsgs->GetBufferPointer(), errMsgs->GetBufferSize());
DEBUG_PRINT("D3DCompile failed %X: %s", hr, errMsg.c_str());
CHECK_HRESULT(hr, "D3DCompile failed");
}
return compiled;
}
bool IsSRGBFormat(DXGI_FORMAT format) {
switch (format) {
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
case DXGI_FORMAT_BC7_UNORM_SRGB:
return true;
default:
return false;
}
}
SwapchainD3D11 CreateSwapchainD3D11(XrSession session,
DXGI_FORMAT format,
int32_t width,
int32_t height,
uint32_t arrayLength,
uint32_t sampleCount,
XrSwapchainCreateFlags createFlags,
XrSwapchainUsageFlags usageFlags,
std::optional<XrViewConfigurationType> viewConfigurationForSwapchain) {
SwapchainD3D11 swapchain;
swapchain.Format = format;
swapchain.Width = width;
swapchain.Height = height;
XrSwapchainCreateInfo swapchainCreateInfo{XR_TYPE_SWAPCHAIN_CREATE_INFO};
swapchainCreateInfo.arraySize = arrayLength;
swapchainCreateInfo.format = format;
swapchainCreateInfo.width = width;
swapchainCreateInfo.height = height;
swapchainCreateInfo.mipCount = 1;
swapchainCreateInfo.faceCount = 1;
swapchainCreateInfo.sampleCount = sampleCount;
swapchainCreateInfo.createFlags = createFlags;
swapchainCreateInfo.usageFlags = usageFlags;
XrSwapchainSecondaryViewConfigurationCreateInfoMSFT secondaryViewConfigCreateInfo{
XR_TYPE_SWAPCHAIN_SECONDARY_VIEW_CONFIGURATION_CREATE_INFO_MSFT};
if (viewConfigurationForSwapchain.has_value()) {
secondaryViewConfigCreateInfo.viewConfigurationType = viewConfigurationForSwapchain.value();
swapchainCreateInfo.next = &secondaryViewConfigCreateInfo;
}
CHECK_XRCMD(xrCreateSwapchain(session, &swapchainCreateInfo, swapchain.Handle.Put()));
uint32_t chainLength;
CHECK_XRCMD(xrEnumerateSwapchainImages(swapchain.Handle.Get(), 0, &chainLength, nullptr));
swapchain.Images.resize(chainLength, {XR_TYPE_SWAPCHAIN_IMAGE_D3D11_KHR});
CHECK_XRCMD(xrEnumerateSwapchainImages(swapchain.Handle.Get(),
(uint32_t)swapchain.Images.size(),
&chainLength,
reinterpret_cast<XrSwapchainImageBaseHeader*>(swapchain.Images.data())));
return swapchain;
}
} // namespace sample::dx

Просмотреть файл

@ -0,0 +1,53 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <winrt/base.h> // winrt::com_ptr
#include <d3dcommon.h> //ID3DBlob
#include <XrUtility/XrHandle.h>
namespace sample::dx {
winrt::com_ptr<IDXGIAdapter1> GetAdapter(LUID adapterId);
void CreateD3D11DeviceAndContext(IDXGIAdapter1* adapter,
const std::vector<D3D_FEATURE_LEVEL>& featureLevels,
bool singleThreaded,
ID3D11Device** device,
ID3D11DeviceContext** deviceContext);
bool IsSRGBFormat(DXGI_FORMAT format);
winrt::com_ptr<ID3DBlob> CompileShader(const char* hlsl, const char* entrypoint, const char* shaderTarget);
struct SwapchainD3D11 {
xr::SwapchainHandle Handle;
DXGI_FORMAT Format{DXGI_FORMAT_UNKNOWN};
int32_t Width{0};
int32_t Height{0};
std::vector<XrSwapchainImageD3D11KHR> Images;
};
SwapchainD3D11 CreateSwapchainD3D11(XrSession session,
DXGI_FORMAT format,
int32_t width,
int32_t height,
uint32_t arrayLength,
uint32_t sampleCount,
XrSwapchainCreateFlags createFlags,
XrSwapchainUsageFlags usageFlags,
std::optional<XrViewConfigurationType> viewConfigurationForSwapchain = std::nullopt);
} // namespace sample::dx

Просмотреть файл

@ -0,0 +1,102 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"
#include "FileUtility.h"
#include "DirectXTK/DDSTextureLoader.h"
#include <pbr/GltfLoader.h>
#include <pbr/PbrModel.h>
#include <DirectXMath.h>
#include <fstream>
#define FMT_HEADER_ONLY
#include <fmt/format.h>
using namespace DirectX;
namespace sample {
std::vector<uint8_t> ReadFileBytes(const std::filesystem::path& path) {
bool fileExists = false;
try {
std::ifstream file;
file.exceptions(std::ios::failbit | std::ios::badbit);
file.open(path, std::ios::binary | std::ios::ate);
fileExists = true;
// If tellg fails then it will throw an exception instead of returning -1.
std::vector<uint8_t> data(static_cast<size_t>(file.tellg()));
file.seekg(0, std::ios::beg);
file.read(reinterpret_cast<char*>(data.data()), data.size());
return data;
} catch (const std::ios::failure&) {
// The exception only knows that the failbit was set so it doesn't contain anything useful.
throw std::runtime_error(fmt::format("Failed to {} file: {}", fileExists ? "read" : "open", path.string()));
}
}
std::filesystem::path GetPathInAppFolder(const std::filesystem::path& filename) {
HMODULE thisModule;
#ifdef UWP
thisModule = nullptr;
#else
if (!::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast<LPCWSTR>(GetPathInAppFolder), &thisModule)) {
throw std::runtime_error("Unable to get the module handle.");
}
#endif
wchar_t moduleFilename[MAX_PATH];
::GetModuleFileName(thisModule, moduleFilename, (DWORD)std::size(moduleFilename));
std::filesystem::path fullPath(moduleFilename);
return fullPath.replace_filename(filename);
}
Pbr::Resources InitializePbrResources(ID3D11Device* device, bool environmentIBL) {
Pbr::Resources pbrResources(device);
// Set up a light source (an image-based lighting environment map will also be loaded and contribute to the scene lighting).
pbrResources.SetLight({0.0f, 0.7071067811865475f, 0.7071067811865475f}, Pbr::RGB::White);
// Read the BRDF Lookup Table used by the PBR system into a DirectX texture.
std::vector<byte> brdfLutFileData = ReadFileBytes(GetPathInAppFolder(L"brdf_lut.png"));
winrt::com_ptr<ID3D11ShaderResourceView> brdLutResourceView =
Pbr::Texture::LoadTextureImage(device, brdfLutFileData.data(), (uint32_t)brdfLutFileData.size());
pbrResources.SetBrdfLut(brdLutResourceView.get());
winrt::com_ptr<ID3D11ShaderResourceView> diffuseTextureView;
winrt::com_ptr<ID3D11ShaderResourceView> specularTextureView;
if (environmentIBL) {
CHECK_HRCMD(DirectX::CreateDDSTextureFromFile(
device, GetPathInAppFolder(L"Sample_DiffuseHDR.DDS").c_str(), nullptr, diffuseTextureView.put()));
CHECK_HRCMD(DirectX::CreateDDSTextureFromFile(
device, GetPathInAppFolder(L"Sample_SpecularHDR.DDS").c_str(), nullptr, specularTextureView.put()));
} else {
diffuseTextureView = Pbr::Texture::CreateFlatCubeTexture(device, Pbr::RGBA::White);
specularTextureView = Pbr::Texture::CreateFlatCubeTexture(device, Pbr::RGBA::White);
}
pbrResources.SetEnvironmentMap(specularTextureView.get(), diffuseTextureView.get());
return pbrResources;
}
std::shared_ptr<Pbr::Model> LoadPbrModelBinary(const std::filesystem::path& filePath, const Pbr::Resources& resources) {
std::vector<byte> fileData = ReadFileBytes(GetPathInAppFolder(filePath));
std::shared_ptr<Pbr::Model> pbrModel = Gltf::FromGltfBinary(resources, fileData.data(), (uint32_t)fileData.size());
return pbrModel;
}
} // namespace sample

Просмотреть файл

@ -0,0 +1,30 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <filesystem>
namespace Pbr {
struct Model;
struct Resources;
}
namespace sample {
std::vector<uint8_t> ReadFileBytes(const std::filesystem::path& path);
std::filesystem::path GetPathInAppFolder(const std::filesystem::path& filename);
Pbr::Resources InitializePbrResources(ID3D11Device* device, bool environmentIBL = true);
std::shared_ptr<Pbr::Model> LoadPbrModelBinary(const std::filesystem::path& filePath, const Pbr::Resources& resources);
} // namespace sample

Просмотреть файл

@ -0,0 +1,26 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <memory.h>
namespace sample {
template <typename GUID1, typename GUID2>
void CopyGuid(GUID1& dest, const GUID2& src) {
static_assert(sizeof(GUID1) == sizeof(GUID2), "GUID sizes must be equal");
memcpy_s(&dest, sizeof(GUID1), &src, sizeof(GUID2));
}
} // namespace sample

Просмотреть файл

@ -0,0 +1,388 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM64">
<Configuration>Debug</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM64">
<Configuration>Release</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{7A3653FD-90A8-4627-9185-F3EEFA539F49}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>SampleShared_uwp</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.17763.0</WindowsTargetPlatformMinVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
<ProjectName>SampleShared_uwp</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_LIB;UWP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_LIB;UWP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_LIB;UWP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;UWP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;UWP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_LIB;UWP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_LIB;UWP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_LIB;UWP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="DirectXTK\dds.h" />
<ClInclude Include="DirectXTK\DDSTextureLoader.h" />
<ClInclude Include="DirectXTK\DirectXHelpers.h" />
<ClInclude Include="DirectXTK\LoaderHelpers.h" />
<ClInclude Include="DirectXTK\PlatformHelpers.h" />
<ClInclude Include="DxUtility.h" />
<ClInclude Include="FileUtility.h" />
<ClInclude Include="Guid.h" />
<ClInclude Include="ScopeGuard.h" />
<ClInclude Include="ThreadPool.h" />
<ClInclude Include="Trace.h" />
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="pch.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="DxUtility.cpp" />
<ClCompile Include="DirectXTK\DDSTextureLoader.cpp" />
<ClCompile Include="FileUtility.cpp" />
</ItemGroup>
<ItemGroup>
<Image Include="UWPAssets\smallTile-sdk.png" />
<Image Include="UWPAssets\splash-sdk.png" />
<Image Include="UWPAssets\squareTile-sdk.png" />
<Image Include="UWPAssets\storeLogo-sdk.png" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="pch.cpp" />
<ClCompile Include="DirectXTK\DDSTextureLoader.cpp">
<Filter>DirectXTK</Filter>
</ClCompile>
<ClCompile Include="FileUtility.cpp" />
<ClCompile Include="DxUtility.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
<ClInclude Include="DirectXTK\dds.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="DirectXTK\DDSTextureLoader.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="DirectXTK\DirectXHelpers.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="DirectXTK\LoaderHelpers.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="DirectXTK\PlatformHelpers.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="FileUtility.h" />
<ClInclude Include="DxUtility.h" />
<ClInclude Include="Trace.h" />
<ClInclude Include="ScopeGuard.h" />
<ClInclude Include="ThreadPool.h" />
<ClInclude Include="Guid.h" />
</ItemGroup>
<ItemGroup>
<Filter Include="DirectXTK">
<UniqueIdentifier>{fae7caa5-87c8-49d7-9ac1-6f7e2466a532}</UniqueIdentifier>
</Filter>
<Filter Include="UWPAssets">
<UniqueIdentifier>{3f7fd9dc-72ea-462c-b880-45d9cbba4afd}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Image Include="UWPAssets\smallTile-sdk.png">
<Filter>UWPAssets</Filter>
</Image>
<Image Include="UWPAssets\splash-sdk.png">
<Filter>UWPAssets</Filter>
</Image>
<Image Include="UWPAssets\squareTile-sdk.png">
<Filter>UWPAssets</Filter>
</Image>
<Image Include="UWPAssets\storeLogo-sdk.png">
<Filter>UWPAssets</Filter>
</Image>
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,358 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM64">
<Configuration>Debug</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM64">
<Configuration>Release</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{269C12FA-E68D-470B-A734-4701034306BD}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>SampleShared_win32</RootNamespace>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<ProjectName>SampleShared_win32</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<WindowsSDKDesktopARMSupport>true</WindowsSDKDesktopARMSupport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<WindowsSDKDesktopARM64Support>true</WindowsSDKDesktopARM64Support>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<WindowsSDKDesktopARMSupport>true</WindowsSDKDesktopARMSupport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<WindowsSDKDesktopARM64Support>true</WindowsSDKDesktopARM64Support>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<TreatWarningAsError>true</TreatWarningAsError>
<CompileAsManaged>false</CompileAsManaged>
<CompileAsWinRT>false</CompileAsWinRT>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="DirectXTK\dds.h" />
<ClInclude Include="DirectXTK\DDSTextureLoader.h" />
<ClInclude Include="DirectXTK\DirectXHelpers.h" />
<ClInclude Include="DirectXTK\LoaderHelpers.h" />
<ClInclude Include="DirectXTK\PlatformHelpers.h" />
<ClInclude Include="DxUtility.h" />
<ClInclude Include="FileUtility.h" />
<ClInclude Include="Trace.h" />
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="pch.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="DxUtility.cpp" />
<ClCompile Include="DirectXTK\DDSTextureLoader.cpp" />
<ClCompile Include="FileUtility.cpp" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets" Condition="Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.props'))" />
<Error Condition="!Exists('..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\OpenXR.Loader.1.0.6.2\build\native\OpenXR.Loader.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="pch.cpp" />
<ClCompile Include="DirectXTK\DDSTextureLoader.cpp">
<Filter>DirectXTK</Filter>
</ClCompile>
<ClCompile Include="FileUtility.cpp" />
<ClCompile Include="DxUtility.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
<ClInclude Include="DirectXTK\dds.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="DirectXTK\DDSTextureLoader.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="DirectXTK\DirectXHelpers.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="DirectXTK\LoaderHelpers.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="DirectXTK\PlatformHelpers.h">
<Filter>DirectXTK</Filter>
</ClInclude>
<ClInclude Include="FileUtility.h" />
<ClInclude Include="DxUtility.h" />
<ClInclude Include="Trace.h" />
</ItemGroup>
<ItemGroup>
<Filter Include="DirectXTK">
<UniqueIdentifier>{4f521880-4ed3-411f-93f7-646a063395e4}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,83 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <atomic>
template <typename TFunction>
struct ScopeGuard {
static_assert(std::is_invocable_v<TFunction>, "Type must be invocable function.");
ScopeGuard(bool active, TFunction&& guard)
: m_guard(std::move(guard))
, m_active(active) {
}
ScopeGuard(ScopeGuard&&) = default;
ScopeGuard& operator=(ScopeGuard&&) = default;
~ScopeGuard() {
if (m_active.load()) {
m_guard();
}
}
void Activate() {
m_active.store(true);
}
void Deactivate() {
m_active.store(false);
}
private:
ScopeGuard(ScopeGuard&) = delete;
ScopeGuard& operator=(ScopeGuard&) = delete;
TFunction m_guard;
std::atomic<bool> m_active;
};
// Usage: auto guard = MakeScopeGuard([&] { foobar; });
template <typename TFunction>
ScopeGuard<TFunction> MakeScopeGuard(TFunction&& guard) {
return ScopeGuard<TFunction>(true, std::forward<TFunction>(guard));
}
// Usage: auto guard = MakeInactiveScopeGuard([&] { foobar; });
// if (some_condition == satisified) {
// guard.Activate()
// }
template <typename TFunction>
ScopeGuard<TFunction> MakeInactiveScopeGuard(TFunction&& guard) {
return ScopeGuard<TFunction>(false, std::forward<TFunction>(guard));
}
// Usage: auto guard = MakeFailureGuard([&] { foobar; });
// Executes guard only if destruction is caused due to exception unwind.
template <typename TFunction>
auto MakeFailureGuard(TFunction&& guard) {
auto failureGuard = [initialUncaughtExceptionCount{std::uncaught_exceptions()}, guard{std::move(guard)}]() {
// Execute only if this lambda is being destroyed due to exception stack unwind.
// In the case of this guard running while an exception is being handled as part of a stack unwind due to another
// exception, there may already be an uncaught exception that should ignored. This is why the exception count
// is compared against a snapshot.
if (std::uncaught_exceptions() > initialUncaughtExceptionCount) {
guard();
}
};
return MakeScopeGuard(std::move(failureGuard));
}

Просмотреть файл

@ -0,0 +1,195 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <thread>
#include <condition_variable>
#include <mutex>
#include <vector>
#include <deque>
namespace sample {
class ThreadPool final {
// Move-only alternative to using std::function<void()>
class UniqueFunction {
struct TypelessFunction {
virtual void Call() = 0;
virtual ~TypelessFunction() {
}
};
std::unique_ptr<TypelessFunction> m_impl;
template <typename F>
struct TypedFunction : TypelessFunction {
F m_func;
TypedFunction(F&& func)
: m_func(std::move(func)) {
}
void Call() override {
m_func();
}
};
public:
template <typename F>
explicit UniqueFunction(F&& f)
: m_impl(new TypedFunction<F>(std::move(f))) {
}
UniqueFunction() = delete;
UniqueFunction(const UniqueFunction&) = delete;
UniqueFunction& operator=(const UniqueFunction&) = delete;
UniqueFunction(UniqueFunction&& other) noexcept = default;
UniqueFunction& operator=(UniqueFunction&& other) noexcept = default;
void operator()() {
m_impl->Call();
}
};
// The state shared between all of the threads in the thread pool.
// This is what makes it possible for the thread pool to be destroyed by one of its own threads.
struct SharedState : std::enable_shared_from_this<SharedState> {
explicit SharedState(size_t threadCount) {
m_threads.reserve(threadCount);
}
template<typename F>
_Requires_lock_not_held_(m_mutex) bool SubmitUnique(F&& f) {
{
std::lock_guard guard(m_mutex);
if (!m_allowSubmit) {
return false;
}
m_tasks.emplace_back(std::move(f));
}
m_cond.notify_one();
return true;
}
_Requires_lock_not_held_(m_mutex) void AddThread() {
std::lock_guard guard(m_mutex);
m_threads.emplace_back([this]() {
if (auto keepAlive = shared_from_this()) {
for (;;) {
std::unique_lock lk(m_mutex);
m_cond.wait(lk, [this]() { return m_stopped || !m_tasks.empty(); });
// Don't stop until the queue is empty
if (!m_tasks.empty()) {
auto task = std::move(m_tasks.front());
m_tasks.pop_front();
lk.unlock();
task();
} else if (m_stopped) {
break;
}
}
}
});
}
_Requires_lock_not_held_(m_mutex) void DisallowSubmit() {
std::lock_guard guard(m_mutex);
m_allowSubmit = false;
}
_Requires_lock_not_held_(m_mutex) void JoinAllThreads() {
{
std::lock_guard guard(m_mutex);
m_stopped = true;
}
m_cond.notify_all();
for (;;) {
std::unique_lock lk(m_mutex);
if (m_threads.empty()) {
break;
}
auto thread = std::move(m_threads.back());
m_threads.pop_back();
lk.unlock();
if (std::this_thread::get_id() == thread.get_id()) {
thread.detach();
} else if (thread.joinable()) {
thread.join();
}
}
}
private:
std::vector<std::thread> m_threads;
std::deque<UniqueFunction> m_tasks;
std::condition_variable m_cond;
std::mutex m_mutex;
bool m_allowSubmit{true};
bool m_stopped{false};
};
public:
// A default constructed ThreadPool does not have a shared state.
// Most methods will throw an exception if called with a default constructed ThreadPool.
ThreadPool() noexcept = default;
explicit ThreadPool(size_t threadCount)
: m_state{std::make_shared<SharedState>(threadCount)} {
if (threadCount == 0) {
throw std::invalid_argument("threadCount must be greater than zero");
}
for (size_t i = 0; i < threadCount; ++i) {
m_state->AddThread();
}
}
// The destructor will wait for all tasks to complete.
~ThreadPool() {
if (m_state) {
m_state->DisallowSubmit();
m_state->JoinAllThreads();
}
}
ThreadPool(ThreadPool&& other) = default;
ThreadPool& operator=(ThreadPool&& other) = default;
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
template <typename F>
bool Submit(F func) {
if (m_state == nullptr) {
throw std::system_error(std::make_error_code(std::errc::operation_not_permitted));
}
return m_state->SubmitUnique(std::move(func));
}
bool Submit(std::function<void()>) = delete;
bool Submit(std::nullptr_t) = delete;
// Stops the thread pool from accepting more tasks and then waits for all queued tasks to complete.
void StopAndWait() {
if (m_state == nullptr) {
throw std::system_error(std::make_error_code(std::errc::operation_not_permitted));
}
m_state->DisallowSubmit();
m_state->JoinAllThreads();
}
// Returns true if the ThreadPool has an associated shared state.
// It does not indicate whether the thread pool has any running threads.
explicit operator bool() const noexcept {
return m_state != nullptr;
}
private:
std::shared_ptr<SharedState> m_state;
};
} // namespace sample

Просмотреть файл

@ -0,0 +1,65 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <iostream>
#include <iomanip>
#include <fstream>
#include <chrono>
#include <thread>
#include <string_view>
#include <processthreadsapi.h>
#define FMT_HEADER_ONLY
#include <fmt/format.h>
namespace sample {
template <typename CharT>
inline void FormatHeader(fmt::basic_memory_buffer<CharT>& buffer, const CharT* formatStr) {
using namespace std::chrono;
const auto now = system_clock::now();
const auto posixTime = system_clock::to_time_t(now);
const auto remainingTime = now - system_clock::from_time_t(posixTime);
const uint64_t remainingMicroseconds = duration_cast<microseconds>(remainingTime).count();
const uint32_t threadId = ::GetCurrentThreadId();
tm localTime;
::localtime_s(&localTime, &posixTime);
fmt::format_to(buffer, formatStr, localTime.tm_hour, localTime.tm_min, localTime.tm_sec, remainingMicroseconds, threadId);
}
template <typename... Args>
inline void Trace(std::wstring_view format_str, const Args&... args) {
// fmt::wmemory_buffer allows this function to avoid std::wstring heap allocations if the resulting string is less than 500 characters.
// If it is more than 500 chars then it will do a heap allocation.
fmt::wmemory_buffer buffer;
FormatHeader(buffer, L"[{:02d}-{:02d}-{:02d}.{:06d}] (t:{:04x}): ");
fmt::format_to(buffer, format_str, args...);
buffer.push_back(L'\0');
::OutputDebugStringW(buffer.data());
}
template <typename... Args>
inline void Trace(std::string_view format_str, const Args&... args) {
fmt::memory_buffer buffer;
FormatHeader(buffer, "[{:02d}-{:02d}-{:02d}.{:06d}] (t:{:04x}): ");
fmt::format_to(buffer, format_str, args...);
buffer.push_back(L'\0');
::OutputDebugStringA(buffer.data());
}
} // namespace sample

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7e386f38f98bf8fcfbe701fd6a407d16e09d94f666fff03d20e38ea27b90e276
size 670

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:afc30eedcf18d686163c71b60ee2d80b103987007aefaba5bce0da2c879d7590
size 9274

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:107b1ed18356d190c5da52c4437a5b4cdec542241f76433baca620be364c1a9f
size 1137

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:911a486a0356f8b378c3e51882057a6428ae8501293205487523fa5d2de83a36
size 442

Просмотреть файл

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenXR.Loader" version="1.0.6.2" targetFramework="native" />
</packages>

Просмотреть файл

@ -0,0 +1,16 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 "pch.h"

47
shared/SampleShared/pch.h Normal file
Просмотреть файл

@ -0,0 +1,47 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <sdkddkver.h>
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <wincodec.h>
#include <winrt/base.h> // for winrt::com_ptr
#include <algorithm>
#include <atomic>
#include <chrono>
#include <initializer_list>
#include <map>
#include <mutex>
#include <optional>
#include <string>
#include <tuple>
#include <vector>
#include <d3d11_4.h>
#include <DirectXMath.h>
#define XR_USE_PLATFORM_WIN32
#define XR_USE_GRAPHICS_API_D3D11
#include <openxr/openxr.h>
#include <openxr/openxr_platform.h>
#include <XrUtility/XrError.h>
#include <XrUtility/XrHandle.h>

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:bc3ad4035b05fa9addf29459c0476a32747d15725e01302c8160b3d47296755a
size 1966208

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f3419168c77cea37ee8c147ce470157bd443d9637c15505ee5915fd4809ed99f
size 33554624

Просмотреть файл

@ -0,0 +1,154 @@
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.
//
//*********************************************************
#pragma once
#include <set>
#include <XrUtility/XrString.h>
#include <XrUtility/XrHandle.h>
namespace xr {
class ActionSet {
public:
ActionSet(XrInstance instance, const std::string& name, const std::string& localizedName, uint32_t priority = 0)
: m_instance(instance) {
XrActionSetCreateInfo actionSetCreateInfo{XR_TYPE_ACTION_SET_CREATE_INFO};
strcpy_s(actionSetCreateInfo.actionSetName, name.c_str());
strcpy_s(actionSetCreateInfo.localizedActionSetName, localizedName.c_str());
actionSetCreateInfo.priority = priority;
CHECK_XRCMD(xrCreateActionSet(m_instance, &actionSetCreateInfo, m_actionSet.Put()));
}
XrAction CreateAction(const std::string& actionName,
const std::string& localizedName,
XrActionType actionType,
const std::vector<std::string>& subactionPaths) {
std::vector<XrPath> subActionXrPaths = xr::StringsToPaths(m_instance, subactionPaths);
XrActionCreateInfo actionCreateInfo{XR_TYPE_ACTION_CREATE_INFO};
actionCreateInfo.actionType = actionType;
actionCreateInfo.countSubactionPaths = static_cast<uint32_t>(subActionXrPaths.size());
actionCreateInfo.subactionPaths = subActionXrPaths.data();
actionName.copy(actionCreateInfo.actionName, sizeof(actionCreateInfo.actionName));
localizedName.copy(actionCreateInfo.localizedActionName, sizeof(actionCreateInfo.localizedActionName));
for (XrPath subactionPath : subActionXrPaths) {
m_declaredSubactionPaths.insert(subactionPath); // std::set will remove duplication.
}
xr::ActionHandle action;
CHECK_XRCMD(xrCreateAction(m_actionSet.Get(), &actionCreateInfo, action.Put()));
m_actions.push_back(std::move(action));
return m_actions.back().Get();
}
const std::set<XrPath>& DeclaredSubactionPaths() const {
return m_declaredSubactionPaths;
}
XrActionSet Handle() const {
return m_actionSet.Get();
}
bool Active() const {
return m_active;
}
void SetActive(bool active) {
m_active = active;
}
private:
const XrInstance m_instance;
xr::ActionSetHandle m_actionSet;
std::vector<xr::ActionHandle> m_actions;
bool m_active{true};
std::set<XrPath> m_declaredSubactionPaths;
};
struct ActionContext {
explicit ActionContext(XrInstance instance)
: m_instance(instance) {
}
ActionSet& CreateActionSet(const std::string& name, const std::string& localizedName, uint32_t priority = 0);
void SuggestInteractionProfileBindings(const std::string& interactionProfile,
const std::vector<std::pair<XrAction, std::string>>& suggestedBindings);
void SyncActions(XrSession session);
void AttachActionsToSession(XrSession session);
private:
XrInstance m_instance;
std::list<ActionSet> m_actionSets;
std::unordered_map<XrPath, std::vector<XrActionSuggestedBinding>> m_actionBindings;
};
inline ActionSet& ActionContext::CreateActionSet(const std::string& name, const std::string& localizedName, uint32_t priority) {
return m_actionSets.emplace_back(m_instance, name, localizedName, priority);
}
inline void ActionContext::SuggestInteractionProfileBindings(const std::string& interactionProfile,
const std::vector<std::pair<XrAction, std::string>>& suggestedBindings) {
const XrPath profilePath = xr::StringToPath(m_instance, interactionProfile.c_str());
for (const auto& [action, suggestedBinding] : suggestedBindings) {
m_actionBindings[profilePath].push_back({action, xr::StringToPath(m_instance, suggestedBinding.c_str())});
}
}
inline void ActionContext::SyncActions(XrSession session) {
std::vector<XrActiveActionSet> activeActionSets;
for (const auto& actionSet : m_actionSets) {
if (!actionSet.Active()) {
continue;
}
for (const auto& subactionPath : actionSet.DeclaredSubactionPaths()) {
XrActiveActionSet activeActionSet;
activeActionSet.actionSet = actionSet.Handle();
activeActionSet.subactionPath = subactionPath;
activeActionSets.push_back(activeActionSet);
}
}
XrActionsSyncInfo syncInfo{XR_TYPE_ACTIONS_SYNC_INFO};
syncInfo.countActiveActionSets = static_cast<uint32_t>(std::size(activeActionSets));
syncInfo.activeActionSets = activeActionSets.data();
CHECK_XRCMD(xrSyncActions(session, &syncInfo));
}
inline void ActionContext::AttachActionsToSession(XrSession session) {
for (const auto& [interactionProfile, bindingsList] : m_actionBindings) {
XrInteractionProfileSuggestedBinding bindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
bindings.interactionProfile = interactionProfile;
bindings.suggestedBindings = bindingsList.data();
bindings.countSuggestedBindings = static_cast<uint32_t>(bindingsList.size());
CHECK_XRCMD(xrSuggestInteractionProfileBindings(m_instance, &bindings));
}
if (!m_actionSets.empty()) {
std::vector<XrActionSet> actionSetHandles;
for (const auto& actionSet : m_actionSets) {
actionSetHandles.push_back(actionSet.Handle());
}
XrSessionActionSetsAttachInfo attachInfo{XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO};
attachInfo.countActionSets = static_cast<uint32_t>(std::size(actionSetHandles));
attachInfo.actionSets = actionSetHandles.data();
CHECK_XRCMD(xrAttachSessionActionSets(session, &attachInfo));
}
}
} // namespace xr

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше