Fixing 'doc' buildbot job: removing trailing whitespaces and tab indents

Signed-off-by: Maxim Kostin <v-maxkos@microsoft.com>
pull/3700/head
Maxim Kostin 10 years ago
parent 22a30af353
commit 530c8dc0c0
  1. 80
      platforms/winrt/build_all.bat
  2. 27
      platforms/winrt/readme.txt
  3. 32
      platforms/winrt/setup_winrt.ps1
  4. 92
      samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvImageManipulations.h
  5. 2
      samples/winrt/OcvImageProcessing/OcvImageProcessing/MainPage.xaml.cpp
  6. 2
      samples/winrt/readme.txt
  7. 146
      samples/winrt_universal/PhoneTutorial/App.xaml.cpp
  8. 28
      samples/winrt_universal/PhoneTutorial/App.xaml.h
  9. 18
      samples/winrt_universal/PhoneTutorial/MainPage.xaml.h
  10. 2
      samples/winrt_universal/PhoneTutorial/opencv.props
  11. 2
      samples/winrt_universal/readme.txt
  12. 77
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1/MainPage.xaml
  13. 4
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1/MainPage.xaml.cs
  14. 10
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1/Properties/AssemblyInfo.cs
  15. 130
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/BasicTimer.h
  16. 244
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DBase.cpp
  17. 42
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DBase.h
  18. 90
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DContentProvider.cpp
  19. 28
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DContentProvider.h
  20. 322
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DInterop.cpp
  21. 118
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DInterop.h
  22. 62
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/DirectXHelper.h
  23. 604
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/QuadRenderer.cpp
  24. 58
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/QuadRenderer.h
  25. 8
      samples/wp8/OcvImageManipulation/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/SimpleVertexShader.hlsl
  26. 55
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1/MainPage.xaml
  27. 2
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1/MainPage.xaml.cs
  28. 10
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1/Properties/AssemblyInfo.cs
  29. 130
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/BasicTimer.h
  30. 744
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/CubeRenderer.cpp
  31. 66
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/CubeRenderer.h
  32. 244
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DBase.cpp
  33. 42
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DBase.h
  34. 90
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DContentProvider.cpp
  35. 28
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DContentProvider.h
  36. 94
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DInterop.cpp
  37. 74
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/Direct3DInterop.h
  38. 62
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/DirectXHelper.h
  39. 8
      samples/wp8/OcvRotatingCube/PhoneXamlDirect3DApp1/PhoneXamlDirect3DApp1Comp/SimpleVertexShader.hlsl
  40. 4
      samples/wp8/OpenCVXaml/OpenCVComponent/OpenCVComponent.cpp
  41. 2
      samples/wp8/OpenCVXaml/OpenCVXaml/MainPage.xaml.cs
  42. 10
      samples/wp8/OpenCVXaml/OpenCVXaml/Properties/AssemblyInfo.cs
  43. 2
      samples/wp8/readme.txt

@ -7,7 +7,7 @@ if defined VS120COMNTOOLS (
set VSTOOLS="%VS120COMNTOOLS%" set VSTOOLS="%VS120COMNTOOLS%"
set VC_VER=120 set VC_VER=120
set FOUND_VC=1 set FOUND_VC=1
) )
set VSTOOLS=%VSTOOLS:"=% set VSTOOLS=%VSTOOLS:"=%
set "VSTOOLS=%VSTOOLS:\=/%" set "VSTOOLS=%VSTOOLS:\=/%"
@ -29,45 +29,45 @@ echo.
call %VSVARS% call %VSVARS%
if %FOUND_VC%==1 ( if %FOUND_VC%==1 (
call:DoMSBuild ..\..\bin\WP\8.1\x86\OpenCV.sln Debug call:DoMSBuild ..\..\bin\WP\8.1\x86\OpenCV.sln Debug
call:DoMSBuild ..\..\bin\WP\8.1\x86\INSTALL.vcxproj Debug call:DoMSBuild ..\..\bin\WP\8.1\x86\INSTALL.vcxproj Debug
call:DoMSBuild ..\..\bin\WP\8.1\x86\OpenCV.sln Release call:DoMSBuild ..\..\bin\WP\8.1\x86\OpenCV.sln Release
call:DoMSBuild ..\..\bin\WP\8.1\x86\INSTALL.vcxproj Release call:DoMSBuild ..\..\bin\WP\8.1\x86\INSTALL.vcxproj Release
call:DoMSBuild ..\..\bin\WP\8.1\ARM\OpenCV.sln Debug call:DoMSBuild ..\..\bin\WP\8.1\ARM\OpenCV.sln Debug
call:DoMSBuild ..\..\bin\WP\8.1\ARM\INSTALL.vcxproj Debug call:DoMSBuild ..\..\bin\WP\8.1\ARM\INSTALL.vcxproj Debug
call:DoMSBuild ..\..\bin\WP\8.1\ARM\OpenCV.sln Release call:DoMSBuild ..\..\bin\WP\8.1\ARM\OpenCV.sln Release
call:DoMSBuild ..\..\bin\WP\8.1\ARM\INSTALL.vcxproj Release call:DoMSBuild ..\..\bin\WP\8.1\ARM\INSTALL.vcxproj Release
call:DoMSBuild ..\..\bin\WS\8.1\x86\OpenCV.sln Debug call:DoMSBuild ..\..\bin\WS\8.1\x86\OpenCV.sln Debug
call:DoMSBuild ..\..\bin\WS\8.1\x86\INSTALL.vcxproj Debug call:DoMSBuild ..\..\bin\WS\8.1\x86\INSTALL.vcxproj Debug
call:DoMSBuild ..\..\bin\WS\8.1\x86\OpenCV.sln Release call:DoMSBuild ..\..\bin\WS\8.1\x86\OpenCV.sln Release
call:DoMSBuild ..\..\bin\WS\8.1\x86\INSTALL.vcxproj Release call:DoMSBuild ..\..\bin\WS\8.1\x86\INSTALL.vcxproj Release
call:DoMSBuild ..\..\bin\WS\8.1\ARM\OpenCV.sln Debug call:DoMSBuild ..\..\bin\WS\8.1\ARM\OpenCV.sln Debug
call:DoMSBuild ..\..\bin\WS\8.1\ARM\INSTALL.vcxproj Debug call:DoMSBuild ..\..\bin\WS\8.1\ARM\INSTALL.vcxproj Debug
call:DoMSBuild ..\..\bin\WS\8.1\ARM\OpenCV.sln Release call:DoMSBuild ..\..\bin\WS\8.1\ARM\OpenCV.sln Release
call:DoMSBuild ..\..\bin\WS\8.1\ARM\INSTALL.vcxproj Release call:DoMSBuild ..\..\bin\WS\8.1\ARM\INSTALL.vcxproj Release
call:DoMSBuild ..\..\bin\WP\8.0\x86\OpenCV.sln Debug call:DoMSBuild ..\..\bin\WP\8.0\x86\OpenCV.sln Debug
call:DoMSBuild ..\..\bin\WP\8.0\x86\INSTALL.vcxproj Debug call:DoMSBuild ..\..\bin\WP\8.0\x86\INSTALL.vcxproj Debug
call:DoMSBuild ..\..\bin\WP\8.0\x86\OpenCV.sln Release call:DoMSBuild ..\..\bin\WP\8.0\x86\OpenCV.sln Release
call:DoMSBuild ..\..\bin\WP\8.0\x86\INSTALL.vcxproj Release call:DoMSBuild ..\..\bin\WP\8.0\x86\INSTALL.vcxproj Release
call:DoMSBuild ..\..\bin\WP\8.0\ARM\OpenCV.sln Debug call:DoMSBuild ..\..\bin\WP\8.0\ARM\OpenCV.sln Debug
call:DoMSBuild ..\..\bin\WP\8.0\ARM\INSTALL.vcxproj Debug call:DoMSBuild ..\..\bin\WP\8.0\ARM\INSTALL.vcxproj Debug
call:DoMSBuild ..\..\bin\WP\8.0\ARM\OpenCV.sln Release call:DoMSBuild ..\..\bin\WP\8.0\ARM\OpenCV.sln Release
call:DoMSBuild ..\..\bin\WP\8.0\ARM\INSTALL.vcxproj Release call:DoMSBuild ..\..\bin\WP\8.0\ARM\INSTALL.vcxproj Release
call:DoMSBuild ..\..\bin\WS\8.0\x86\OpenCV.sln Debug call:DoMSBuild ..\..\bin\WS\8.0\x86\OpenCV.sln Debug
call:DoMSBuild ..\..\bin\WS\8.0\x86\INSTALL.vcxproj Debug call:DoMSBuild ..\..\bin\WS\8.0\x86\INSTALL.vcxproj Debug
call:DoMSBuild ..\..\bin\WS\8.0\x86\OpenCV.sln Release call:DoMSBuild ..\..\bin\WS\8.0\x86\OpenCV.sln Release
call:DoMSBuild ..\..\bin\WS\8.0\x86\INSTALL.vcxproj Release call:DoMSBuild ..\..\bin\WS\8.0\x86\INSTALL.vcxproj Release
call:DoMSBuild ..\..\bin\WS\8.0\ARM\OpenCV.sln Debug call:DoMSBuild ..\..\bin\WS\8.0\ARM\OpenCV.sln Debug
call:DoMSBuild ..\..\bin\WS\8.0\ARM\INSTALL.vcxproj Debug call:DoMSBuild ..\..\bin\WS\8.0\ARM\INSTALL.vcxproj Debug
call:DoMSBuild ..\..\bin\WS\8.0\ARM\OpenCV.sln Release call:DoMSBuild ..\..\bin\WS\8.0\ARM\OpenCV.sln Release
call:DoMSBuild ..\..\bin\WS\8.0\ARM\INSTALL.vcxproj Release call:DoMSBuild ..\..\bin\WS\8.0\ARM\INSTALL.vcxproj Release
) )
echo.&goto:EOF echo.&goto:EOF

@ -5,15 +5,15 @@ Requirements
============ ============
CMake 3.1.0 or higher CMake 3.1.0 or higher
Windows Phone/Store 8.1 Visual Studio 2013 Windows Phone/Store 8.1 Visual Studio 2013
Windows Phone/Store 8.0 Visual Studio 2012 Windows Phone/Store 8.0 Visual Studio 2012
For example, to be able to build all Windows Phone and Windows Store projects install the following: For example, to be able to build all Windows Phone and Windows Store projects install the following:
Install Visual Studio 2013 Community Edition Install Visual Studio 2013 Community Edition
http://go.microsoft.com/?linkid=9863608 http://go.microsoft.com/?linkid=9863608
Install Visual Studio Express 2012 for Windows Desktop Install Visual Studio Express 2012 for Windows Desktop
http://www.microsoft.com/en-us/download/details.aspx?id=34673 http://www.microsoft.com/en-us/download/details.aspx?id=34673
@ -24,11 +24,11 @@ setup_winrt.bat "WP,WS" "8.0,8.1" "x86,ARM"
If everything's fine, a few minutes later you will get the following output in the opencv/bin directory: If everything's fine, a few minutes later you will get the following output in the opencv/bin directory:
bin bin
WP WP
8.0 8.0
ARM ARM
x86 x86
8.1 8.1
ARM ARM
x86 x86
@ -38,7 +38,7 @@ bin
x86 x86
8.1 8.1
ARM ARM
x86 x86
Build the OpenCV.sln for the particular platform you are targeting. Due to the current limitations of CMake, separate x86/x64/ARM projects must be generated for each platform. Build the OpenCV.sln for the particular platform you are targeting. Due to the current limitations of CMake, separate x86/x64/ARM projects must be generated for each platform.
@ -48,8 +48,8 @@ You can also target a single specific configuration
Or a subset of configurations Or a subset of configurations
setup_winrt.bat "WP,WS" "8.1" "x86" setup_winrt.bat "WP,WS" "8.1" "x86"
To display the command line options for setup_winrt.bat To display the command line options for setup_winrt.bat
setup_winrt.bat -h setup_winrt.bat -h
Note that x64 CMake generation support is as follows: Note that x64 CMake generation support is as follows:
------------------------------ ------------------------------
@ -93,11 +93,10 @@ Windows Store 8.0 ARM
cmake -G "Visual Studio 12 2013 ARM" -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=8.0 <path-to-source> cmake -G "Visual Studio 12 2013 ARM" -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=8.0 <path-to-source>
Example Example
======= ======================================================
To generate Windows Phone 8.1 x86 project files in the opencv/bin dir To generate Windows Phone 8.1 x86 project files in the opencv/bin dir
mkdir bin mkdir bin
cd bin cd bin
cmake -G "Visual Studio 12 2013" -DCMAKE_SYSTEM_NAME=WindowsPhone -DCMAKE_SYSTEM_VERSION=8.1 ../ cmake -G "Visual Studio 12 2013" -DCMAKE_SYSTEM_NAME=WindowsPhone -DCMAKE_SYSTEM_VERSION=8.1 ../

@ -1,10 +1,10 @@
<# <#
Copyright © Microsoft Open Technologies, Inc. Copyright © Microsoft Open Technologies, Inc.
All Rights Reserved All Rights Reserved
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
@ -110,11 +110,11 @@ function Call-MSBuild($path, $config)
L "Executing: $($command)" L "Executing: $($command)"
msbuild $path /p:Configuration="$config" /m msbuild $path /p:Configuration="$config" /m
if(-Not $?) { if(-Not $?) {
Throw "Failure executing command: $($command)" Throw "Failure executing command: $($command)"
} }
return $true return $true
} }
Function Execute() { Function Execute() {
@ -122,10 +122,10 @@ Function Execute() {
ShowHelp ShowHelp
} }
# Validating arguments. # Validating arguments.
# This type of validation (rather than using ValidateSet()) is required to make .bat wrapper work # This type of validation (rather than using ValidateSet()) is required to make .bat wrapper work
D "Input Platforms: $PLATFORMS_IN" D "Input Platforms: $PLATFORMS_IN"
$platforms = New-Object System.Collections.ArrayList $platforms = New-Object System.Collections.ArrayList
$PLATFORMS_IN.Split("," ,[System.StringSplitOptions]::RemoveEmptyEntries) | ForEach { $PLATFORMS_IN.Split("," ,[System.StringSplitOptions]::RemoveEmptyEntries) | ForEach {
$_ = $_.Trim() $_ = $_.Trim()
@ -133,7 +133,7 @@ Function Execute() {
[void]$platforms.Add($_) [void]$platforms.Add($_)
D "$_ is valid" D "$_ is valid"
} else { } else {
Throw "$($_) is not valid! Please use WP, WS" Throw "$($_) is not valid! Please use WP, WS"
} }
} }
D "Processed Platforms: $platforms" D "Processed Platforms: $platforms"
@ -144,9 +144,9 @@ Function Execute() {
$_ = $_.Trim() $_ = $_.Trim()
if ("8.0","8.1" -Contains $_) { if ("8.0","8.1" -Contains $_) {
[void]$versions.Add($_) [void]$versions.Add($_)
D "$_ is valid" D "$_ is valid"
} else { } else {
Throw "$($_) is not valid! Please use 8.0, 8.1" Throw "$($_) is not valid! Please use 8.0, 8.1"
} }
} }
D "Processed Versions: $versions" D "Processed Versions: $versions"
@ -159,7 +159,7 @@ Function Execute() {
$architectures.Add($_) > $null $architectures.Add($_) > $null
D "$_ is valid" D "$_ is valid"
} else { } else {
Throw "$($_) is not valid! Please use x86, x64, ARM" Throw "$($_) is not valid! Please use x86, x64, ARM"
} }
} }
D "Processed Architectures: $architectures" D "Processed Architectures: $architectures"
@ -231,7 +231,7 @@ Function Execute() {
Push-Location -Path $path Push-Location -Path $path
L "Generating project:" L "Generating project:"
L "cmake -G $genName -DCMAKE_SYSTEM_NAME:String=$platName -DCMAKE_SYSTEM_VERSION:String=$vers -DCMAKE_VS_EFFECTIVE_PLATFORMS:String=$arch -DCMAKE_INSTALL_PREFIX:PATH=$installPath $SRC" L "cmake -G $genName -DCMAKE_SYSTEM_NAME:String=$platName -DCMAKE_SYSTEM_VERSION:String=$vers -DCMAKE_VS_EFFECTIVE_PLATFORMS:String=$arch -DCMAKE_INSTALL_PREFIX:PATH=$installPath $SRC"
cmake -G $genName -DCMAKE_SYSTEM_NAME:String=$platName -DCMAKE_SYSTEM_VERSION:String=$vers -DCMAKE_VS_EFFECTIVE_PLATFORMS:String=$arch -DCMAKE_INSTALL_PREFIX:PATH=$installPath $SRC cmake -G $genName -DCMAKE_SYSTEM_NAME:String=$platName -DCMAKE_SYSTEM_VERSION:String=$vers -DCMAKE_VS_EFFECTIVE_PLATFORMS:String=$arch -DCMAKE_INSTALL_PREFIX:PATH=$installPath $SRC
L "-----------------------------------------------" L "-----------------------------------------------"
@ -273,8 +273,8 @@ Function Execute() {
Function ShowHelp() { Function ShowHelp() {
Write-Host "Configures OpenCV and generates projects for specified verion of Visual Studio/platforms/architectures." Write-Host "Configures OpenCV and generates projects for specified verion of Visual Studio/platforms/architectures."
Write-Host "Must be executed from the sources folder containing main CMakeLists configuration." Write-Host "Must be executed from the sources folder containing main CMakeLists configuration."
Write-Host "Parameter keys can be shortened down to a signle symbol (e.g. '-a') and are not case sensitive." Write-Host "Parameter keys can be shortened down to a single symbol (e.g. '-a') and are not case sensitive."
Write-Host "Proper parameter sequensing is required when omitting keys." Write-Host "Proper parameter sequencing is required when omitting keys."
Write-Host "Generates the following folder structure, depending on the supplied parameters: " Write-Host "Generates the following folder structure, depending on the supplied parameters: "
Write-Host " bin/ " Write-Host " bin/ "
Write-Host " | " Write-Host " | "
@ -286,7 +286,7 @@ Function ShowHelp() {
Write-Host " | | |-x86 " Write-Host " | | |-x86 "
Write-Host " | | |-x64 " Write-Host " | | |-x64 "
Write-Host " | | |-ARM " Write-Host " | | |-ARM "
Write-Host " " Write-Host " "
Write-Host " USAGE: " Write-Host " USAGE: "
Write-Host " Calling:" Write-Host " Calling:"
Write-Host " PS> setup_winrt.ps1 [params]" Write-Host " PS> setup_winrt.ps1 [params]"
@ -310,7 +310,7 @@ Function ShowHelp() {
Write-Host " version - Array of platform versions. " Write-Host " version - Array of platform versions. "
Write-Host " Default: 8.1 " Write-Host " Default: 8.1 "
Write-Host " Example: '8.0,8.1' " Write-Host " Example: '8.0,8.1' "
Write-Host " Options: 8.0, 8.1. Available options may be limited depending on your local setup (e.g. SDK availability). " Write-Host " Options: 8.0, 8.1. Available options may be limited depending on your local setup (e.g. SDK availability). "
Write-Host " Note that you'll need to use quotes to specify more than one version. " Write-Host " Note that you'll need to use quotes to specify more than one version. "
Write-Host " architecture - Array of target architectures to build for. " Write-Host " architecture - Array of target architectures to build for. "
Write-Host " Default: x86 " Write-Host " Default: x86 "

@ -1,92 +0,0 @@
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 8.00.0603 */
/* at Tue Jan 20 15:16:38 2015
*/
/* Compiler settings for C:\Users\MAXIM~1.KOS\AppData\Local\Temp\OcvImageManipulations.idl-a5dae736:
Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 8.00.0603
protocol : dce , ms_ext, c_ext, robust
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
/* @@MIDL_FILE_HEADING( ) */
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__
#ifndef __OcvImageManipulations_h__
#define __OcvImageManipulations_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#if defined(__cplusplus)
#if defined(__MIDL_USE_C_ENUM)
#define MIDL_ENUM enum
#else
#define MIDL_ENUM enum class
#endif
#endif
/* Forward Declarations */
/* header files for imported files */
#include "Windows.Media.h"
#ifdef __cplusplus
extern "C"{
#endif
/* interface __MIDL_itf_OcvImageManipulations_0000_0000 */
/* [local] */
#pragma warning(push)
#pragma warning(disable:4001)
#pragma once
#pragma warning(pop)
#ifndef RUNTIMECLASS_OcvTransform_OcvImageManipulations_DEFINED
#define RUNTIMECLASS_OcvTransform_OcvImageManipulations_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_OcvTransform_OcvImageManipulations[] = L"OcvTransform.OcvImageManipulations";
#endif
/* interface __MIDL_itf_OcvImageManipulations_0000_0000 */
/* [local] */
extern RPC_IF_HANDLE __MIDL_itf_OcvImageManipulations_0000_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_OcvImageManipulations_0000_0000_v0_0_s_ifspec;
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif

@ -131,7 +131,7 @@ cv::Mat OcvImageProcessing::MainPage::ApplyFindFeaturesFilter(const cv::Mat& ima
{ {
cv::Mat result; cv::Mat result;
cv::Mat intermediateMat; cv::Mat intermediateMat;
cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create(50); cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create(50);
std::vector<cv::KeyPoint> features; std::vector<cv::KeyPoint> features;
image.copyTo(result); image.copyTo(result);

@ -1,6 +1,6 @@
Building OpenCV WinRT Samples Building OpenCV WinRT Samples
============================= =============================
Samples are created to run against x86 architecture OpenCV binaries. Samples are created to run against x86 architecture OpenCV binaries.
Please follow the instructions in "platforms/winrt/readme.txt" to generate and build OpenCV for WinRT. Please follow the instructions in "platforms/winrt/readme.txt" to generate and build OpenCV for WinRT.

@ -31,8 +31,8 @@ using namespace Windows::UI::Xaml::Navigation;
/// </summary> /// </summary>
App::App() App::App()
{ {
InitializeComponent(); InitializeComponent();
Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending); Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
} }
/// <summary> /// <summary>
@ -44,61 +44,61 @@ App::App()
void App::OnLaunched(LaunchActivatedEventArgs^ e) void App::OnLaunched(LaunchActivatedEventArgs^ e)
{ {
#if _DEBUG #if _DEBUG
if (IsDebuggerPresent()) if (IsDebuggerPresent())
{ {
DebugSettings->EnableFrameRateCounter = true; DebugSettings->EnableFrameRateCounter = true;
} }
#endif #endif
auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content); auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
// Do not repeat app initialization when the Window already has content, // Do not repeat app initialization when the Window already has content,
// just ensure that the window is active. // just ensure that the window is active.
if (rootFrame == nullptr) if (rootFrame == nullptr)
{ {
// Create a Frame to act as the navigation context and associate it with // Create a Frame to act as the navigation context and associate it with
// a SuspensionManager key // a SuspensionManager key
rootFrame = ref new Frame(); rootFrame = ref new Frame();
// TODO: Change this value to a cache size that is appropriate for your application. // TODO: Change this value to a cache size that is appropriate for your application.
rootFrame->CacheSize = 1; rootFrame->CacheSize = 1;
if (e->PreviousExecutionState == ApplicationExecutionState::Terminated) if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
{ {
// TODO: Restore the saved session state only when appropriate, scheduling the // TODO: Restore the saved session state only when appropriate, scheduling the
// final launch steps after the restore is complete. // final launch steps after the restore is complete.
} }
// Place the frame in the current Window // Place the frame in the current Window
Window::Current->Content = rootFrame; Window::Current->Content = rootFrame;
} }
if (rootFrame->Content == nullptr) if (rootFrame->Content == nullptr)
{ {
// Removes the turnstile navigation for startup. // Removes the turnstile navigation for startup.
if (rootFrame->ContentTransitions != nullptr) if (rootFrame->ContentTransitions != nullptr)
{ {
_transitions = ref new TransitionCollection(); _transitions = ref new TransitionCollection();
for (auto transition : rootFrame->ContentTransitions) for (auto transition : rootFrame->ContentTransitions)
{ {
_transitions->Append(transition); _transitions->Append(transition);
} }
} }
rootFrame->ContentTransitions = nullptr; rootFrame->ContentTransitions = nullptr;
_firstNavigatedToken = rootFrame->Navigated += ref new NavigatedEventHandler(this, &App::RootFrame_FirstNavigated); _firstNavigatedToken = rootFrame->Navigated += ref new NavigatedEventHandler(this, &App::RootFrame_FirstNavigated);
// When the navigation stack isn't restored navigate to the first page, // When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation // configuring the new page by passing required information as a navigation
// parameter. // parameter.
if (!rootFrame->Navigate(MainPage::typeid, e->Arguments)) if (!rootFrame->Navigate(MainPage::typeid, e->Arguments))
{ {
throw ref new FailureException("Failed to create initial page"); throw ref new FailureException("Failed to create initial page");
} }
} }
// Ensure the current window is active // Ensure the current window is active
Window::Current->Activate(); Window::Current->Activate();
} }
/// <summary> /// <summary>
@ -106,21 +106,21 @@ void App::OnLaunched(LaunchActivatedEventArgs^ e)
/// </summary> /// </summary>
void App::RootFrame_FirstNavigated(Object^ sender, NavigationEventArgs^ e) void App::RootFrame_FirstNavigated(Object^ sender, NavigationEventArgs^ e)
{ {
auto rootFrame = safe_cast<Frame^>(sender); auto rootFrame = safe_cast<Frame^>(sender);
TransitionCollection^ newTransitions; TransitionCollection^ newTransitions;
if (_transitions == nullptr) if (_transitions == nullptr)
{ {
newTransitions = ref new TransitionCollection(); newTransitions = ref new TransitionCollection();
newTransitions->Append(ref new NavigationThemeTransition()); newTransitions->Append(ref new NavigationThemeTransition());
} }
else else
{ {
newTransitions = _transitions; newTransitions = _transitions;
} }
rootFrame->ContentTransitions = newTransitions; rootFrame->ContentTransitions = newTransitions;
rootFrame->Navigated -= _firstNavigatedToken; rootFrame->Navigated -= _firstNavigatedToken;
} }
/// <summary> /// <summary>
@ -130,8 +130,8 @@ void App::RootFrame_FirstNavigated(Object^ sender, NavigationEventArgs^ e)
/// </summary> /// </summary>
void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e) void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
{ {
(void) sender; // Unused parameter (void) sender; // Unused parameter
(void) e; // Unused parameter (void) e; // Unused parameter
// TODO: Save application state and stop any background activity // TODO: Save application state and stop any background activity
} }

@ -9,21 +9,21 @@
namespace PhoneTutorial namespace PhoneTutorial
{ {
/// <summary> /// <summary>
/// Provides application-specific behavior to supplement the default Application class. /// Provides application-specific behavior to supplement the default Application class.
/// </summary> /// </summary>
ref class App sealed ref class App sealed
{ {
public: public:
App(); App();
virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override; virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override;
private: private:
Windows::UI::Xaml::Media::Animation::TransitionCollection^ _transitions; Windows::UI::Xaml::Media::Animation::TransitionCollection^ _transitions;
Windows::Foundation::EventRegistrationToken _firstNavigatedToken; Windows::Foundation::EventRegistrationToken _firstNavigatedToken;
void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e); void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
void RootFrame_FirstNavigated(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e); void RootFrame_FirstNavigated(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e);
}; };
} }

@ -9,16 +9,16 @@
namespace PhoneTutorial namespace PhoneTutorial
{ {
/// <summary> /// <summary>
/// An empty page that can be used on its own or navigated to within a Frame. /// An empty page that can be used on its own or navigated to within a Frame.
/// </summary> /// </summary>
public ref class MainPage sealed public ref class MainPage sealed
{ {
public: public:
MainPage(); MainPage();
protected: protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override; virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private: private:
Windows::UI::Xaml::Media::Imaging::WriteableBitmap^ m_bitmap; Windows::UI::Xaml::Media::Imaging::WriteableBitmap^ m_bitmap;

@ -26,6 +26,6 @@
<!--Add required OpenCV libs here--> <!--Add required OpenCV libs here-->
<AdditionalDependencies>opencv_core300$(DebugSuffix).lib;opencv_imgproc300$(DebugSuffix).lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>opencv_core300$(DebugSuffix).lib;opencv_imgproc300$(DebugSuffix).lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(OpenCV_Lib);%(AdditionalLibraryDirectories);</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>$(OpenCV_Lib);%(AdditionalLibraryDirectories);</AdditionalLibraryDirectories>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
</Project> </Project>

@ -1,6 +1,6 @@
Building OpenCV WinRT Universal Samples Building OpenCV WinRT Universal Samples
======================================= =======================================
Samples are created to run against x86 architecture OpenCV binaries. Samples are created to run against x86 architecture OpenCV binaries.
Please follow the instructions in "platforms/winrt/readme.txt" to generate and build OpenCV for WinRT. Please follow the instructions in "platforms/winrt/readme.txt" to generate and build OpenCV for WinRT.

@ -1,42 +1,53 @@
<phone:PhoneApplicationPage <phone:PhoneApplicationPage x:Class="PhoneXamlDirect3DApp1.MainPage"
x:Class="PhoneXamlDirect3DApp1.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" FontFamily="{StaticResource PhoneFontFamilyNormal}"
mc:Ignorable="d" FontSize="{StaticResource PhoneFontSizeNormal}"
FontFamily="{StaticResource PhoneFontFamilyNormal}" Foreground="{StaticResource PhoneForegroundBrush}"
FontSize="{StaticResource PhoneFontSizeNormal}" Orientation="Portrait"
Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait"
SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True"
shell:SystemTray.IsVisible="True"> mc:Ignorable="d">
<!--LayoutRoot is the root grid where all page content is placed--> <!-- LayoutRoot is the root grid where all page content is placed -->
<Grid x:Name="LayoutRoot" Background="Transparent"> <Grid x:Name="LayoutRoot" Background="Transparent">
<DrawingSurface x:Name="DrawingSurface" Loaded="DrawingSurface_Loaded" /> <DrawingSurface x:Name="DrawingSurface" Loaded="DrawingSurface_Loaded" />
<StackPanel Margin="40"> <StackPanel Margin="40">
<RadioButton x:Name="Normal" Content="Normal" GroupName="Group1" <RadioButton x:Name="Normal"
Checked="RadioButton_Checked" IsChecked="True"/> Checked="RadioButton_Checked"
<RadioButton x:Name="Gray" Content="Gray" GroupName="Group1" Content="Normal"
Checked="RadioButton_Checked"/> GroupName="Group1"
<RadioButton x:Name="Canny" Content="Canny" GroupName="Group1" IsChecked="True" />
Checked="RadioButton_Checked"/> <RadioButton x:Name="Gray"
<RadioButton x:Name="Sepia" Content="Sepia" GroupName="Group1" Checked="RadioButton_Checked"
Checked="RadioButton_Checked"/> Content="Gray"
<RadioButton x:Name="Features" Content="Features" GroupName="Group1" GroupName="Group1" />
Checked="RadioButton_Checked"/> <RadioButton x:Name="Canny"
Checked="RadioButton_Checked"
Content="Canny"
GroupName="Group1" />
<RadioButton x:Name="Sepia"
Checked="RadioButton_Checked"
Content="Sepia"
GroupName="Group1" />
<RadioButton x:Name="Features"
Checked="RadioButton_Checked"
Content="Features"
GroupName="Group1" />
<StackPanel Orientation="Horizontal" Margin="20,0,0,0"> <StackPanel Margin="20,0,0,0" Orientation="Horizontal">
<TextBlock Text="Memory: "/> <TextBlock Text="Memory: " />
<TextBlock x:Name="MemoryTextBlock"/> <TextBlock x:Name="MemoryTextBlock" />
<TextBlock Text=" MB"/> <TextBlock Text=" MB" />
</StackPanel> </StackPanel>
<StackPanel Orientation="Horizontal" Margin="20,0,0,0"> <StackPanel Margin="20,0,0,0" Orientation="Horizontal">
<TextBlock Text="Peak Memory: "/> <TextBlock Text="Peak Memory: " />
<TextBlock x:Name="PeakMemoryTextBlock"/> <TextBlock x:Name="PeakMemoryTextBlock" />
<TextBlock Text=" MB"/> <TextBlock Text=" MB" />
</StackPanel> </StackPanel>
</StackPanel> </StackPanel>

@ -88,7 +88,7 @@ namespace PhoneXamlDirect3DApp1
{ {
try try
{ {
// These are TextBlock controls that are created in the page’s XAML file. // These are TextBlock controls that are created in the page’s XAML file.
float value = DeviceStatus.ApplicationCurrentMemoryUsage / (1024.0f * 1024.0f) ; float value = DeviceStatus.ApplicationCurrentMemoryUsage / (1024.0f * 1024.0f) ;
MemoryTextBlock.Text = value.ToString(); MemoryTextBlock.Text = value.ToString();
value = DeviceStatus.ApplicationPeakMemoryUsage / (1024.0f * 1024.0f); value = DeviceStatus.ApplicationPeakMemoryUsage / (1024.0f * 1024.0f);
@ -99,5 +99,5 @@ namespace PhoneXamlDirect3DApp1
MemoryTextBlock.Text = ex.Message; MemoryTextBlock.Text = ex.Message;
} }
} }
} }
} }

@ -3,7 +3,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Resources; using System.Resources;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("PhoneXamlDirect3DApp1")] [assembly: AssemblyTitle("PhoneXamlDirect3DApp1")]
@ -15,8 +15,8 @@ using System.Resources;
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible // Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from // to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. // COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
@ -26,11 +26,11 @@ using System.Resources;
// Version information for an assembly consists of the following four values: // Version information for an assembly consists of the following four values:
// //
// Major Version // Major Version
// Minor Version // Minor Version
// Build Number // Build Number
// Revision // Revision
// //
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]

@ -6,71 +6,71 @@
ref class BasicTimer sealed ref class BasicTimer sealed
{ {
public: public:
// Initializes internal timer values. // Initializes internal timer values.
BasicTimer() BasicTimer()
{ {
if (!QueryPerformanceFrequency(&m_frequency)) if (!QueryPerformanceFrequency(&m_frequency))
{ {
throw ref new Platform::FailureException(); throw ref new Platform::FailureException();
} }
Reset(); Reset();
} }
// Reset the timer to initial values. // Reset the timer to initial values.
void Reset() void Reset()
{ {
Update(); Update();
m_startTime = m_currentTime; m_startTime = m_currentTime;
m_total = 0.0f; m_total = 0.0f;
m_delta = 1.0f / 60.0f; m_delta = 1.0f / 60.0f;
} }
// Update the timer's internal values. // Update the timer's internal values.
void Update() void Update()
{ {
if (!QueryPerformanceCounter(&m_currentTime)) if (!QueryPerformanceCounter(&m_currentTime))
{ {
throw ref new Platform::FailureException(); throw ref new Platform::FailureException();
} }
m_total = static_cast<float>( m_total = static_cast<float>(
static_cast<double>(m_currentTime.QuadPart - m_startTime.QuadPart) / static_cast<double>(m_currentTime.QuadPart - m_startTime.QuadPart) /
static_cast<double>(m_frequency.QuadPart) static_cast<double>(m_frequency.QuadPart)
); );
if (m_lastTime.QuadPart == m_startTime.QuadPart) if (m_lastTime.QuadPart == m_startTime.QuadPart)
{ {
// If the timer was just reset, report a time delta equivalent to 60Hz frame time. // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
m_delta = 1.0f / 60.0f; m_delta = 1.0f / 60.0f;
} }
else else
{ {
m_delta = static_cast<float>( m_delta = static_cast<float>(
static_cast<double>(m_currentTime.QuadPart - m_lastTime.QuadPart) / static_cast<double>(m_currentTime.QuadPart - m_lastTime.QuadPart) /
static_cast<double>(m_frequency.QuadPart) static_cast<double>(m_frequency.QuadPart)
); );
} }
m_lastTime = m_currentTime; m_lastTime = m_currentTime;
} }
// Duration in seconds between the last call to Reset() and the last call to Update(). // Duration in seconds between the last call to Reset() and the last call to Update().
property float Total property float Total
{ {
float get() { return m_total; } float get() { return m_total; }
} }
// Duration in seconds between the previous two calls to Update(). // Duration in seconds between the previous two calls to Update().
property float Delta property float Delta
{ {
float get() { return m_delta; } float get() { return m_delta; }
} }
private: private:
LARGE_INTEGER m_frequency; LARGE_INTEGER m_frequency;
LARGE_INTEGER m_currentTime; LARGE_INTEGER m_currentTime;
LARGE_INTEGER m_startTime; LARGE_INTEGER m_startTime;
LARGE_INTEGER m_lastTime; LARGE_INTEGER m_lastTime;
float m_total; float m_total;
float m_delta; float m_delta;
}; };

@ -15,148 +15,148 @@ Direct3DBase::Direct3DBase()
// Initialize the Direct3D resources required to run. // Initialize the Direct3D resources required to run.
void Direct3DBase::Initialize() void Direct3DBase::Initialize()
{ {
CreateDeviceResources(); CreateDeviceResources();
} }
// These are the resources that depend on the device. // These are the resources that depend on the device.
void Direct3DBase::CreateDeviceResources() void Direct3DBase::CreateDeviceResources()
{ {
// This flag adds support for surfaces with a different color channel ordering // This flag adds support for surfaces with a different color channel ordering
// than the API default. It is required for compatibility with Direct2D. // than the API default. It is required for compatibility with Direct2D.
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#if defined(_DEBUG) #if defined(_DEBUG)
// If the project is in a debug build, enable debugging via SDK Layers with this flag. // If the project is in a debug build, enable debugging via SDK Layers with this flag.
creationFlags |= D3D11_CREATE_DEVICE_DEBUG; creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif #endif
// This array defines the set of DirectX hardware feature levels this app will support. // This array defines the set of DirectX hardware feature levels this app will support.
// Note the ordering should be preserved. // Note the ordering should be preserved.
// Don't forget to declare your application's minimum required feature level in its // Don't forget to declare your application's minimum required feature level in its
// description. All applications are assumed to support 9.1 unless otherwise stated. // description. All applications are assumed to support 9.1 unless otherwise stated.
D3D_FEATURE_LEVEL featureLevels[] = D3D_FEATURE_LEVEL featureLevels[] =
{ {
D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3 D3D_FEATURE_LEVEL_9_3
}; };
// Create the Direct3D 11 API device object and a corresponding context. // Create the Direct3D 11 API device object and a corresponding context.
ComPtr<ID3D11Device> device; ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context; ComPtr<ID3D11DeviceContext> context;
DX::ThrowIfFailed( DX::ThrowIfFailed(
D3D11CreateDevice( D3D11CreateDevice(
nullptr, // Specify nullptr to use the default adapter. nullptr, // Specify nullptr to use the default adapter.
D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_HARDWARE,
nullptr, nullptr,
creationFlags, // Set set debug and Direct2D compatibility flags. creationFlags, // Set set debug and Direct2D compatibility flags.
featureLevels, // List of feature levels this app can support. featureLevels, // List of feature levels this app can support.
ARRAYSIZE(featureLevels), ARRAYSIZE(featureLevels),
D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION. D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION.
&device, // Returns the Direct3D device created. &device, // Returns the Direct3D device created.
&m_featureLevel, // Returns feature level of device created. &m_featureLevel, // Returns feature level of device created.
&context // Returns the device immediate context. &context // Returns the device immediate context.
) )
); );
// Get the Direct3D 11.1 API device and context interfaces. // Get the Direct3D 11.1 API device and context interfaces.
DX::ThrowIfFailed( DX::ThrowIfFailed(
device.As(&m_d3dDevice) device.As(&m_d3dDevice)
); );
DX::ThrowIfFailed( DX::ThrowIfFailed(
context.As(&m_d3dContext) context.As(&m_d3dContext)
); );
} }
// Allocate all memory resources that depend on the window size. // Allocate all memory resources that depend on the window size.
void Direct3DBase::CreateWindowSizeDependentResources() void Direct3DBase::CreateWindowSizeDependentResources()
{ {
// Create a descriptor for the render target buffer. // Create a descriptor for the render target buffer.
CD3D11_TEXTURE2D_DESC renderTargetDesc( CD3D11_TEXTURE2D_DESC renderTargetDesc(
DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM,
static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Width),
static_cast<UINT>(m_renderTargetSize.Height), static_cast<UINT>(m_renderTargetSize.Height),
1, 1,
1, 1,
D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE
); );
renderTargetDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX | D3D11_RESOURCE_MISC_SHARED_NTHANDLE; renderTargetDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX | D3D11_RESOURCE_MISC_SHARED_NTHANDLE;
// Allocate a 2-D surface as the render target buffer. // Allocate a 2-D surface as the render target buffer.
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateTexture2D( m_d3dDevice->CreateTexture2D(
&renderTargetDesc, &renderTargetDesc,
nullptr, nullptr,
&m_renderTarget &m_renderTarget
) )
); );
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateRenderTargetView( m_d3dDevice->CreateRenderTargetView(
m_renderTarget.Get(), m_renderTarget.Get(),
nullptr, nullptr,
&m_renderTargetView &m_renderTargetView
) )
); );
// Create a depth stencil view. // Create a depth stencil view.
CD3D11_TEXTURE2D_DESC depthStencilDesc( CD3D11_TEXTURE2D_DESC depthStencilDesc(
DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_D24_UNORM_S8_UINT,
static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Width),
static_cast<UINT>(m_renderTargetSize.Height), static_cast<UINT>(m_renderTargetSize.Height),
1, 1,
1, 1,
D3D11_BIND_DEPTH_STENCIL D3D11_BIND_DEPTH_STENCIL
); );
ComPtr<ID3D11Texture2D> depthStencil; ComPtr<ID3D11Texture2D> depthStencil;
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateTexture2D( m_d3dDevice->CreateTexture2D(
&depthStencilDesc, &depthStencilDesc,
nullptr, nullptr,
&depthStencil &depthStencil
) )
); );
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D); CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateDepthStencilView( m_d3dDevice->CreateDepthStencilView(
depthStencil.Get(), depthStencil.Get(),
&depthStencilViewDesc, &depthStencilViewDesc,
&m_depthStencilView &m_depthStencilView
) )
); );
// Set the rendering viewport to target the entire window. // Set the rendering viewport to target the entire window.
CD3D11_VIEWPORT viewport( CD3D11_VIEWPORT viewport(
0.0f, 0.0f,
0.0f, 0.0f,
m_renderTargetSize.Width, m_renderTargetSize.Width,
m_renderTargetSize.Height m_renderTargetSize.Height
); );
m_d3dContext->RSSetViewports(1, &viewport); m_d3dContext->RSSetViewports(1, &viewport);
} }
void Direct3DBase::UpdateForRenderResolutionChange(float width, float height) void Direct3DBase::UpdateForRenderResolutionChange(float width, float height)
{ {
m_renderTargetSize.Width = width; m_renderTargetSize.Width = width;
m_renderTargetSize.Height = height; m_renderTargetSize.Height = height;
ID3D11RenderTargetView* nullViews[] = {nullptr}; ID3D11RenderTargetView* nullViews[] = {nullptr};
m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr); m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
m_renderTarget = nullptr; m_renderTarget = nullptr;
m_renderTargetView = nullptr; m_renderTargetView = nullptr;
m_depthStencilView = nullptr; m_depthStencilView = nullptr;
m_d3dContext->Flush(); m_d3dContext->Flush();
CreateWindowSizeDependentResources(); CreateWindowSizeDependentResources();
} }
void Direct3DBase::UpdateForWindowSizeChange(float width, float height) void Direct3DBase::UpdateForWindowSizeChange(float width, float height)
{ {
m_windowBounds.Width = width; m_windowBounds.Width = width;
m_windowBounds.Height = height; m_windowBounds.Height = height;
} }

@ -6,32 +6,32 @@
ref class Direct3DBase abstract ref class Direct3DBase abstract
{ {
internal: internal:
Direct3DBase(); Direct3DBase();
public: public:
virtual void Initialize(); virtual void Initialize();
virtual void CreateDeviceResources(); virtual void CreateDeviceResources();
virtual void CreateWindowSizeDependentResources(); virtual void CreateWindowSizeDependentResources();
virtual void UpdateForRenderResolutionChange(float width, float height); virtual void UpdateForRenderResolutionChange(float width, float height);
virtual void UpdateForWindowSizeChange(float width, float height); virtual void UpdateForWindowSizeChange(float width, float height);
virtual void Render() = 0; virtual void Render() = 0;
internal: internal:
virtual ID3D11Texture2D* GetTexture() virtual ID3D11Texture2D* GetTexture()
{ {
return m_renderTarget.Get(); return m_renderTarget.Get();
} }
protected private: protected private:
// Direct3D Objects. // Direct3D Objects.
Microsoft::WRL::ComPtr<ID3D11Device1> m_d3dDevice; Microsoft::WRL::ComPtr<ID3D11Device1> m_d3dDevice;
Microsoft::WRL::ComPtr<ID3D11DeviceContext1> m_d3dContext; Microsoft::WRL::ComPtr<ID3D11DeviceContext1> m_d3dContext;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_renderTarget; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_renderTarget;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_renderTargetView; Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_renderTargetView;
Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_depthStencilView; Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_depthStencilView;
// Cached renderer properties. // Cached renderer properties.
D3D_FEATURE_LEVEL m_featureLevel; D3D_FEATURE_LEVEL m_featureLevel;
Windows::Foundation::Size m_renderTargetSize; Windows::Foundation::Size m_renderTargetSize;
Windows::Foundation::Rect m_windowBounds; Windows::Foundation::Rect m_windowBounds;
}; };

@ -4,74 +4,74 @@
using namespace PhoneXamlDirect3DApp1Comp; using namespace PhoneXamlDirect3DApp1Comp;
Direct3DContentProvider::Direct3DContentProvider(Direct3DInterop^ controller) : Direct3DContentProvider::Direct3DContentProvider(Direct3DInterop^ controller) :
m_controller(controller) m_controller(controller)
{ {
m_controller->RequestAdditionalFrame += ref new RequestAdditionalFrameHandler([=] () m_controller->RequestAdditionalFrame += ref new RequestAdditionalFrameHandler([=] ()
{ {
if (m_host) if (m_host)
{ {
m_host->RequestAdditionalFrame(); m_host->RequestAdditionalFrame();
} }
}); });
m_controller->RecreateSynchronizedTexture += ref new RecreateSynchronizedTextureHandler([=] () m_controller->RecreateSynchronizedTexture += ref new RecreateSynchronizedTextureHandler([=] ()
{ {
if (m_host) if (m_host)
{ {
m_host->CreateSynchronizedTexture(m_controller->GetTexture(), &m_synchronizedTexture); m_host->CreateSynchronizedTexture(m_controller->GetTexture(), &m_synchronizedTexture);
} }
}); });
} }
// IDrawingSurfaceContentProviderNative interface // IDrawingSurfaceContentProviderNative interface
HRESULT Direct3DContentProvider::Connect(_In_ IDrawingSurfaceRuntimeHostNative* host) HRESULT Direct3DContentProvider::Connect(_In_ IDrawingSurfaceRuntimeHostNative* host)
{ {
m_host = host; m_host = host;
return m_controller->Connect(host); return m_controller->Connect(host);
} }
void Direct3DContentProvider::Disconnect() void Direct3DContentProvider::Disconnect()
{ {
m_controller->Disconnect(); m_controller->Disconnect();
m_host = nullptr; m_host = nullptr;
m_synchronizedTexture = nullptr; m_synchronizedTexture = nullptr;
} }
HRESULT Direct3DContentProvider::PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty) HRESULT Direct3DContentProvider::PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty)
{ {
return m_controller->PrepareResources(presentTargetTime, contentDirty); return m_controller->PrepareResources(presentTargetTime, contentDirty);
} }
HRESULT Direct3DContentProvider::GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle) HRESULT Direct3DContentProvider::GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle)
{ {
HRESULT hr = S_OK; HRESULT hr = S_OK;
if (!m_synchronizedTexture)
{
hr = m_host->CreateSynchronizedTexture(m_controller->GetTexture(), &m_synchronizedTexture);
}
if (!m_synchronizedTexture) // Set output parameters.
{ textureSubRectangle->left = 0.0f;
hr = m_host->CreateSynchronizedTexture(m_controller->GetTexture(), &m_synchronizedTexture); textureSubRectangle->top = 0.0f;
} textureSubRectangle->right = static_cast<FLOAT>(size->width);
textureSubRectangle->bottom = static_cast<FLOAT>(size->height);
// Set output parameters. m_synchronizedTexture.CopyTo(synchronizedTexture);
textureSubRectangle->left = 0.0f;
textureSubRectangle->top = 0.0f;
textureSubRectangle->right = static_cast<FLOAT>(size->width);
textureSubRectangle->bottom = static_cast<FLOAT>(size->height);
m_synchronizedTexture.CopyTo(synchronizedTexture); // Draw to the texture.
if (SUCCEEDED(hr))
{
hr = m_synchronizedTexture->BeginDraw();
// Draw to the texture. if (SUCCEEDED(hr))
if (SUCCEEDED(hr)) {
{ hr = m_controller->GetTexture(size, synchronizedTexture, textureSubRectangle);
hr = m_synchronizedTexture->BeginDraw(); }
if (SUCCEEDED(hr))
{
hr = m_controller->GetTexture(size, synchronizedTexture, textureSubRectangle);
}
m_synchronizedTexture->EndDraw(); m_synchronizedTexture->EndDraw();
} }
return hr; return hr;
} }

@ -8,26 +8,26 @@
#include "Direct3DInterop.h" #include "Direct3DInterop.h"
class Direct3DContentProvider : public Microsoft::WRL::RuntimeClass< class Direct3DContentProvider : public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix>, Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix>,
ABI::Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider, ABI::Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider,
IDrawingSurfaceContentProviderNative> IDrawingSurfaceContentProviderNative>
{ {
public: public:
Direct3DContentProvider(PhoneXamlDirect3DApp1Comp::Direct3DInterop^ controller); Direct3DContentProvider(PhoneXamlDirect3DApp1Comp::Direct3DInterop^ controller);
void ReleaseD3DResources(); void ReleaseD3DResources();
// IDrawingSurfaceContentProviderNative // IDrawingSurfaceContentProviderNative
HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host); HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host);
void STDMETHODCALLTYPE Disconnect(); void STDMETHODCALLTYPE Disconnect();
HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty); HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty);
HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle); HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle);
private: private:
HRESULT InitializeTexture(_In_ const DrawingSurfaceSizeF* size); HRESULT InitializeTexture(_In_ const DrawingSurfaceSizeF* size);
PhoneXamlDirect3DApp1Comp::Direct3DInterop^ m_controller; PhoneXamlDirect3DApp1Comp::Direct3DInterop^ m_controller;
Microsoft::WRL::ComPtr<IDrawingSurfaceRuntimeHostNative> m_host; Microsoft::WRL::ComPtr<IDrawingSurfaceRuntimeHostNative> m_host;
Microsoft::WRL::ComPtr<IDrawingSurfaceSynchronizedTextureNative> m_synchronizedTexture; Microsoft::WRL::ComPtr<IDrawingSurfaceSynchronizedTextureNative> m_synchronizedTexture;
}; };

@ -29,27 +29,27 @@ namespace PhoneXamlDirect3DApp1Comp
{ {
// Called each time a preview frame is available // Called each time a preview frame is available
void CameraCapturePreviewSink::OnFrameAvailable( void CameraCapturePreviewSink::OnFrameAvailable(
DXGI_FORMAT format, DXGI_FORMAT format,
UINT width, UINT width,
UINT height, UINT height,
BYTE* pixels BYTE* pixels
) )
{ {
m_Direct3dInterop->UpdateFrame(pixels, width, height); m_Direct3dInterop->UpdateFrame(pixels, width, height);
} }
// Called each time a captured frame is available // Called each time a captured frame is available
void CameraCaptureSampleSink::OnSampleAvailable( void CameraCaptureSampleSink::OnSampleAvailable(
ULONGLONG hnsPresentationTime, ULONGLONG hnsPresentationTime,
ULONGLONG hnsSampleDuration, ULONGLONG hnsSampleDuration,
DWORD cbSample, DWORD cbSample,
BYTE* pSample) BYTE* pSample)
{ {
} }
Direct3DInterop::Direct3DInterop() Direct3DInterop::Direct3DInterop()
: m_algorithm(OCVFilterType::ePreview) : m_algorithm(OCVFilterType::ePreview)
, m_contentDirty(false) , m_contentDirty(false)
, m_backFrame(nullptr) , m_backFrame(nullptr)
@ -84,80 +84,80 @@ namespace PhoneXamlDirect3DApp1Comp
void Direct3DInterop::ProcessFrame() void Direct3DInterop::ProcessFrame()
{ {
if (SwapFrames()) if (SwapFrames())
{ {
if (m_renderer) if (m_renderer)
{ {
cv::Mat* mat = m_frontFrame.get(); cv::Mat* mat = m_frontFrame.get();
switch (m_algorithm) switch (m_algorithm)
{ {
case OCVFilterType::ePreview: case OCVFilterType::ePreview:
{ {
break; break;
} }
case OCVFilterType::eGray: case OCVFilterType::eGray:
{ {
ApplyGrayFilter(mat); ApplyGrayFilter(mat);
break; break;
} }
case OCVFilterType::eCanny: case OCVFilterType::eCanny:
{ {
ApplyCannyFilter(mat); ApplyCannyFilter(mat);
break; break;
} }
case OCVFilterType::eBlur: case OCVFilterType::eBlur:
{ {
ApplyBlurFilter(mat); ApplyBlurFilter(mat);
break; break;
} }
case OCVFilterType::eFindFeatures: case OCVFilterType::eFindFeatures:
{ {
ApplyFindFeaturesFilter(mat); ApplyFindFeaturesFilter(mat);
break; break;
} }
case OCVFilterType::eSepia: case OCVFilterType::eSepia:
{ {
ApplySepiaFilter(mat); ApplySepiaFilter(mat);
break; break;
} }
} }
m_renderer->CreateTextureFromByte(mat->data, mat->cols, mat->rows); m_renderer->CreateTextureFromByte(mat->data, mat->cols, mat->rows);
} }
} }
}
void Direct3DInterop::ApplyGrayFilter(cv::Mat* mat)
{
cv::Mat intermediateMat;
cv::cvtColor(*mat, intermediateMat, CV_RGBA2GRAY);
cv::cvtColor(intermediateMat, *mat, CV_GRAY2BGRA);
}
void Direct3DInterop::ApplyCannyFilter(cv::Mat* mat)
{
cv::Mat intermediateMat;
cv::Canny(*mat, intermediateMat, 80, 90);
cv::cvtColor(intermediateMat, *mat, CV_GRAY2BGRA);
} }
void Direct3DInterop::ApplyGrayFilter(cv::Mat* mat) void Direct3DInterop::ApplyBlurFilter(cv::Mat* mat)
{ {
cv::Mat intermediateMat;
cv::cvtColor(*mat, intermediateMat, CV_RGBA2GRAY);
cv::cvtColor(intermediateMat, *mat, CV_GRAY2BGRA);
}
void Direct3DInterop::ApplyCannyFilter(cv::Mat* mat)
{
cv::Mat intermediateMat;
cv::Canny(*mat, intermediateMat, 80, 90);
cv::cvtColor(intermediateMat, *mat, CV_GRAY2BGRA);
}
void Direct3DInterop::ApplyBlurFilter(cv::Mat* mat)
{
cv::Mat intermediateMat;
// cv::Blur(image, intermediateMat, 80, 90);
cv::cvtColor(intermediateMat, *mat, CV_GRAY2BGRA);
}
void Direct3DInterop::ApplyFindFeaturesFilter(cv::Mat* mat)
{
cv::Mat intermediateMat; cv::Mat intermediateMat;
cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create(50); // cv::Blur(image, intermediateMat, 80, 90);
cv::cvtColor(intermediateMat, *mat, CV_GRAY2BGRA);
}
void Direct3DInterop::ApplyFindFeaturesFilter(cv::Mat* mat)
{
cv::Mat intermediateMat;
cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create(50);
std::vector<cv::KeyPoint> features; std::vector<cv::KeyPoint> features;
cv::cvtColor(*mat, intermediateMat, CV_RGBA2GRAY); cv::cvtColor(*mat, intermediateMat, CV_RGBA2GRAY);
@ -168,21 +168,21 @@ namespace PhoneXamlDirect3DApp1Comp
const cv::KeyPoint& kp = features[i]; const cv::KeyPoint& kp = features[i];
cv::circle(*mat, cv::Point((int)kp.pt.x, (int)kp.pt.y), 10, cv::Scalar(255,0,0,255)); cv::circle(*mat, cv::Point((int)kp.pt.x, (int)kp.pt.y), 10, cv::Scalar(255,0,0,255));
} }
} }
void Direct3DInterop::ApplySepiaFilter(cv::Mat* mat) void Direct3DInterop::ApplySepiaFilter(cv::Mat* mat)
{ {
const float SepiaKernelData[16] = const float SepiaKernelData[16] =
{ {
/* B */0.131f, 0.534f, 0.272f, 0.f, /* B */0.131f, 0.534f, 0.272f, 0.f,
/* G */0.168f, 0.686f, 0.349f, 0.f, /* G */0.168f, 0.686f, 0.349f, 0.f,
/* R */0.189f, 0.769f, 0.393f, 0.f, /* R */0.189f, 0.769f, 0.393f, 0.f,
/* A */0.000f, 0.000f, 0.000f, 1.f /* A */0.000f, 0.000f, 0.000f, 1.f
}; };
const cv::Mat SepiaKernel(4, 4, CV_32FC1, (void*)SepiaKernelData); const cv::Mat SepiaKernel(4, 4, CV_32FC1, (void*)SepiaKernelData);
cv::transform(*mat, *mat, SepiaKernel); cv::transform(*mat, *mat, SepiaKernel);
} }
IDrawingSurfaceContentProvider^ Direct3DInterop::CreateContentProvider() IDrawingSurfaceContentProvider^ Direct3DInterop::CreateContentProvider()
{ {
@ -238,75 +238,75 @@ namespace PhoneXamlDirect3DApp1Comp
void Direct3DInterop::StartCamera() void Direct3DInterop::StartCamera()
{ {
// Set the capture dimensions // Set the capture dimensions
Size captureDimensions; Size captureDimensions;
captureDimensions.Width = 640; captureDimensions.Width = 640;
captureDimensions.Height = 480; captureDimensions.Height = 480;
// Open the AudioVideoCaptureDevice for video only // Open the AudioVideoCaptureDevice for video only
IAsyncOperation<AudioVideoCaptureDevice^> ^openOperation = AudioVideoCaptureDevice::OpenForVideoOnlyAsync(CameraSensorLocation::Back, captureDimensions); IAsyncOperation<AudioVideoCaptureDevice^> ^openOperation = AudioVideoCaptureDevice::OpenForVideoOnlyAsync(CameraSensorLocation::Back, captureDimensions);
openOperation->Completed = ref new AsyncOperationCompletedHandler<AudioVideoCaptureDevice^>( openOperation->Completed = ref new AsyncOperationCompletedHandler<AudioVideoCaptureDevice^>(
[this] (IAsyncOperation<AudioVideoCaptureDevice^> ^operation, Windows::Foundation::AsyncStatus status) [this] (IAsyncOperation<AudioVideoCaptureDevice^> ^operation, Windows::Foundation::AsyncStatus status)
{ {
if (status == Windows::Foundation::AsyncStatus::Completed) if (status == Windows::Foundation::AsyncStatus::Completed)
{ {
auto captureDevice = operation->GetResults(); auto captureDevice = operation->GetResults();
// Save the reference to the opened video capture device // Save the reference to the opened video capture device
pAudioVideoCaptureDevice = captureDevice; pAudioVideoCaptureDevice = captureDevice;
// Retrieve the native ICameraCaptureDeviceNative interface from the managed video capture device // Retrieve the native ICameraCaptureDeviceNative interface from the managed video capture device
ICameraCaptureDeviceNative *iCameraCaptureDeviceNative = NULL; ICameraCaptureDeviceNative *iCameraCaptureDeviceNative = NULL;
HRESULT hr = reinterpret_cast<IUnknown*>(captureDevice)->QueryInterface(__uuidof(ICameraCaptureDeviceNative), (void**) &iCameraCaptureDeviceNative); HRESULT hr = reinterpret_cast<IUnknown*>(captureDevice)->QueryInterface(__uuidof(ICameraCaptureDeviceNative), (void**) &iCameraCaptureDeviceNative);
// Save the pointer to the native interface // Save the pointer to the native interface
pCameraCaptureDeviceNative = iCameraCaptureDeviceNative; pCameraCaptureDeviceNative = iCameraCaptureDeviceNative;
// Initialize the preview dimensions (see the accompanying article at ) // Initialize the preview dimensions (see the accompanying article at )
// The aspect ratio of the capture and preview resolution must be equal, // The aspect ratio of the capture and preview resolution must be equal,
// 4:3 for capture => 4:3 for preview, and 16:9 for capture => 16:9 for preview. // 4:3 for capture => 4:3 for preview, and 16:9 for capture => 16:9 for preview.
Size previewDimensions; Size previewDimensions;
previewDimensions.Width = 640; previewDimensions.Width = 640;
previewDimensions.Height = 480; previewDimensions.Height = 480;
IAsyncAction^ setPreviewResolutionAction = pAudioVideoCaptureDevice->SetPreviewResolutionAsync(previewDimensions); IAsyncAction^ setPreviewResolutionAction = pAudioVideoCaptureDevice->SetPreviewResolutionAsync(previewDimensions);
setPreviewResolutionAction->Completed = ref new AsyncActionCompletedHandler( setPreviewResolutionAction->Completed = ref new AsyncActionCompletedHandler(
[this](IAsyncAction^ action, Windows::Foundation::AsyncStatus status) [this](IAsyncAction^ action, Windows::Foundation::AsyncStatus status)
{ {
HResult hr = action->ErrorCode; HResult hr = action->ErrorCode;
if (status == Windows::Foundation::AsyncStatus::Completed) if (status == Windows::Foundation::AsyncStatus::Completed)
{ {
// Create the sink // Create the sink
MakeAndInitialize<CameraCapturePreviewSink>(&pCameraCapturePreviewSink); MakeAndInitialize<CameraCapturePreviewSink>(&pCameraCapturePreviewSink);
pCameraCapturePreviewSink->SetDelegate(this); pCameraCapturePreviewSink->SetDelegate(this);
pCameraCaptureDeviceNative->SetPreviewSink(pCameraCapturePreviewSink); pCameraCaptureDeviceNative->SetPreviewSink(pCameraCapturePreviewSink);
// Set the preview format // Set the preview format
pCameraCaptureDeviceNative->SetPreviewFormat(DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM); pCameraCaptureDeviceNative->SetPreviewFormat(DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM);
} }
} }
); );
// Retrieve IAudioVideoCaptureDeviceNative native interface from managed projection. // Retrieve IAudioVideoCaptureDeviceNative native interface from managed projection.
IAudioVideoCaptureDeviceNative *iAudioVideoCaptureDeviceNative = NULL; IAudioVideoCaptureDeviceNative *iAudioVideoCaptureDeviceNative = NULL;
hr = reinterpret_cast<IUnknown*>(captureDevice)->QueryInterface(__uuidof(IAudioVideoCaptureDeviceNative), (void**) &iAudioVideoCaptureDeviceNative); hr = reinterpret_cast<IUnknown*>(captureDevice)->QueryInterface(__uuidof(IAudioVideoCaptureDeviceNative), (void**) &iAudioVideoCaptureDeviceNative);
// Save the pointer to the IAudioVideoCaptureDeviceNative native interface // Save the pointer to the IAudioVideoCaptureDeviceNative native interface
pAudioVideoCaptureDeviceNative = iAudioVideoCaptureDeviceNative; pAudioVideoCaptureDeviceNative = iAudioVideoCaptureDeviceNative;
// Set sample encoding format to ARGB. See the documentation for further values. // Set sample encoding format to ARGB. See the documentation for further values.
pAudioVideoCaptureDevice->VideoEncodingFormat = CameraCaptureVideoFormat::Argb; pAudioVideoCaptureDevice->VideoEncodingFormat = CameraCaptureVideoFormat::Argb;
// Initialize and set the CameraCaptureSampleSink class as sink for captures samples // Initialize and set the CameraCaptureSampleSink class as sink for captures samples
MakeAndInitialize<CameraCaptureSampleSink>(&pCameraCaptureSampleSink); MakeAndInitialize<CameraCaptureSampleSink>(&pCameraCaptureSampleSink);
pAudioVideoCaptureDeviceNative->SetVideoSampleSink(pCameraCaptureSampleSink); pAudioVideoCaptureDeviceNative->SetVideoSampleSink(pCameraCaptureSampleSink);
// Start recording (only way to receive samples using the ICameraCaptureSampleSink interface // Start recording (only way to receive samples using the ICameraCaptureSampleSink interface
pAudioVideoCaptureDevice->StartRecordingToSinkAsync(); pAudioVideoCaptureDevice->StartRecordingToSinkAsync();
} }
} }
); );
} }
// Interface With Direct3DContentProvider // Interface With Direct3DContentProvider
@ -339,7 +339,7 @@ namespace PhoneXamlDirect3DApp1Comp
HRESULT Direct3DInterop::GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle) HRESULT Direct3DInterop::GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle)
{ {
m_renderer->Update(); m_renderer->Update();
m_renderer->Render(); m_renderer->Render();
return S_OK; return S_OK;
} }

@ -15,16 +15,16 @@
namespace PhoneXamlDirect3DApp1Comp namespace PhoneXamlDirect3DApp1Comp
{ {
public enum class OCVFilterType public enum class OCVFilterType
{ {
ePreview, ePreview,
eGray, eGray,
eCanny, eCanny,
eBlur, eBlur,
eFindFeatures, eFindFeatures,
eSepia, eSepia,
eNumOCVFilterTypes eNumOCVFilterTypes
}; };
class CameraCapturePreviewSink; class CameraCapturePreviewSink;
@ -37,71 +37,71 @@ public delegate void RecreateSynchronizedTextureHandler();
public ref class Direct3DInterop sealed : public Windows::Phone::Input::Interop::IDrawingSurfaceManipulationHandler public ref class Direct3DInterop sealed : public Windows::Phone::Input::Interop::IDrawingSurfaceManipulationHandler
{ {
public: public:
Direct3DInterop(); Direct3DInterop();
Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider^ CreateContentProvider(); Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider^ CreateContentProvider();
// IDrawingSurfaceManipulationHandler // IDrawingSurfaceManipulationHandler
virtual void SetManipulationHost(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ manipulationHost); virtual void SetManipulationHost(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ manipulationHost);
event RequestAdditionalFrameHandler^ RequestAdditionalFrame; event RequestAdditionalFrameHandler^ RequestAdditionalFrame;
event RecreateSynchronizedTextureHandler^ RecreateSynchronizedTexture; event RecreateSynchronizedTextureHandler^ RecreateSynchronizedTexture;
property Windows::Foundation::Size WindowBounds; property Windows::Foundation::Size WindowBounds;
property Windows::Foundation::Size NativeResolution; property Windows::Foundation::Size NativeResolution;
property Windows::Foundation::Size RenderResolution property Windows::Foundation::Size RenderResolution
{ {
Windows::Foundation::Size get(){ return m_renderResolution; } Windows::Foundation::Size get(){ return m_renderResolution; }
void set(Windows::Foundation::Size renderResolution); void set(Windows::Foundation::Size renderResolution);
} }
void SetAlgorithm(OCVFilterType type) { m_algorithm = type; }; void SetAlgorithm(OCVFilterType type) { m_algorithm = type; };
void UpdateFrame(byte* buffer, int width, int height); void UpdateFrame(byte* buffer, int width, int height);
protected: protected:
// Event Handlers // Event Handlers
void OnPointerPressed(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerPressed(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args);
void OnPointerMoved(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerMoved(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args);
void OnPointerReleased(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerReleased(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args);
internal: internal:
HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host); HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host);
void STDMETHODCALLTYPE Disconnect(); void STDMETHODCALLTYPE Disconnect();
HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty); HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty);
HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle); HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle);
ID3D11Texture2D* GetTexture(); ID3D11Texture2D* GetTexture();
private: private:
void StartCamera(); void StartCamera();
void ProcessFrame(); void ProcessFrame();
bool SwapFrames(); bool SwapFrames();
QuadRenderer^ m_renderer; QuadRenderer^ m_renderer;
Windows::Foundation::Size m_renderResolution; Windows::Foundation::Size m_renderResolution;
OCVFilterType m_algorithm; OCVFilterType m_algorithm;
bool m_contentDirty; bool m_contentDirty;
std::shared_ptr<cv::Mat> m_backFrame; std::shared_ptr<cv::Mat> m_backFrame;
std::shared_ptr<cv::Mat> m_frontFrame; std::shared_ptr<cv::Mat> m_frontFrame;
std::mutex m_mutex; std::mutex m_mutex;
Windows::Phone::Media::Capture::AudioVideoCaptureDevice ^pAudioVideoCaptureDevice; Windows::Phone::Media::Capture::AudioVideoCaptureDevice ^pAudioVideoCaptureDevice;
ICameraCaptureDeviceNative* pCameraCaptureDeviceNative; ICameraCaptureDeviceNative* pCameraCaptureDeviceNative;
IAudioVideoCaptureDeviceNative* pAudioVideoCaptureDeviceNative; IAudioVideoCaptureDeviceNative* pAudioVideoCaptureDeviceNative;
CameraCapturePreviewSink* pCameraCapturePreviewSink; CameraCapturePreviewSink* pCameraCapturePreviewSink;
CameraCaptureSampleSink* pCameraCaptureSampleSink; CameraCaptureSampleSink* pCameraCaptureSampleSink;
//void ApplyPreviewFilter(const cv::Mat& image); //void ApplyPreviewFilter(const cv::Mat& image);
void ApplyGrayFilter(cv::Mat* mat); void ApplyGrayFilter(cv::Mat* mat);
void ApplyCannyFilter(cv::Mat* mat); void ApplyCannyFilter(cv::Mat* mat);
void ApplyBlurFilter(cv::Mat* mat); void ApplyBlurFilter(cv::Mat* mat);
void ApplyFindFeaturesFilter(cv::Mat* mat); void ApplyFindFeaturesFilter(cv::Mat* mat);
void ApplySepiaFilter(cv::Mat* mat); void ApplySepiaFilter(cv::Mat* mat);
}; };
class CameraCapturePreviewSink : class CameraCapturePreviewSink :
public Microsoft::WRL::RuntimeClass< public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::ClassicCom>, Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::ClassicCom>,
ICameraCapturePreviewSink> ICameraCapturePreviewSink>
{ {
public: public:
void SetDelegate(Direct3DInterop^ delegate) void SetDelegate(Direct3DInterop^ delegate)
@ -109,20 +109,20 @@ public:
m_Direct3dInterop = delegate; m_Direct3dInterop = delegate;
} }
IFACEMETHODIMP_(void) OnFrameAvailable( IFACEMETHODIMP_(void) OnFrameAvailable(
DXGI_FORMAT format, DXGI_FORMAT format,
UINT width, UINT width,
UINT height, UINT height,
BYTE* pixels); BYTE* pixels);
private: private:
Direct3DInterop^ m_Direct3dInterop; Direct3DInterop^ m_Direct3dInterop;
}; };
class CameraCaptureSampleSink : class CameraCaptureSampleSink :
public Microsoft::WRL::RuntimeClass< public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::ClassicCom>, Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::ClassicCom>,
ICameraCaptureSampleSink> ICameraCaptureSampleSink>
{ {
public: public:
void SetDelegate(Direct3DInterop^ delegate) void SetDelegate(Direct3DInterop^ delegate)
@ -131,10 +131,10 @@ public:
} }
IFACEMETHODIMP_(void) OnSampleAvailable( IFACEMETHODIMP_(void) OnSampleAvailable(
ULONGLONG hnsPresentationTime, ULONGLONG hnsPresentationTime,
ULONGLONG hnsSampleDuration, ULONGLONG hnsSampleDuration,
DWORD cbSample, DWORD cbSample,
BYTE* pSample); BYTE* pSample);
private: private:
Direct3DInterop^ m_Direct3dInterop; Direct3DInterop^ m_Direct3dInterop;

@ -6,36 +6,36 @@
namespace DX namespace DX
{ {
inline void ThrowIfFailed(HRESULT hr) inline void ThrowIfFailed(HRESULT hr)
{ {
if (FAILED(hr)) if (FAILED(hr))
{ {
// Set a breakpoint on this line to catch Win32 API errors. // Set a breakpoint on this line to catch Win32 API errors.
throw Platform::Exception::CreateException(hr); throw Platform::Exception::CreateException(hr);
} }
} }
// Function that reads from a binary file asynchronously. // Function that reads from a binary file asynchronously.
inline Concurrency::task<Platform::Array<byte>^> ReadDataAsync(Platform::String^ filename) inline Concurrency::task<Platform::Array<byte>^> ReadDataAsync(Platform::String^ filename)
{ {
using namespace Windows::Storage; using namespace Windows::Storage;
using namespace Concurrency; using namespace Concurrency;
auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation; auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
return create_task(folder->GetFileAsync(filename)).then([] (StorageFile^ file) return create_task(folder->GetFileAsync(filename)).then([] (StorageFile^ file)
{ {
return file->OpenReadAsync(); return file->OpenReadAsync();
}).then([] (Streams::IRandomAccessStreamWithContentType^ stream) }).then([] (Streams::IRandomAccessStreamWithContentType^ stream)
{ {
unsigned int bufferSize = static_cast<unsigned int>(stream->Size); unsigned int bufferSize = static_cast<unsigned int>(stream->Size);
auto fileBuffer = ref new Streams::Buffer(bufferSize); auto fileBuffer = ref new Streams::Buffer(bufferSize);
return stream->ReadAsync(fileBuffer, bufferSize, Streams::InputStreamOptions::None); return stream->ReadAsync(fileBuffer, bufferSize, Streams::InputStreamOptions::None);
}).then([] (Streams::IBuffer^ fileBuffer) -> Platform::Array<byte>^ }).then([] (Streams::IBuffer^ fileBuffer) -> Platform::Array<byte>^
{ {
auto fileData = ref new Platform::Array<byte>(fileBuffer->Length); auto fileData = ref new Platform::Array<byte>(fileBuffer->Length);
Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(fileData); Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(fileData);
return fileData; return fileData;
}); });
} }
} }

@ -7,247 +7,247 @@ using namespace Windows::Foundation;
using namespace Windows::UI::Core; using namespace Windows::UI::Core;
QuadRenderer::QuadRenderer() : QuadRenderer::QuadRenderer() :
m_loadingComplete(false), m_loadingComplete(false),
m_indexCount(0) m_indexCount(0)
{ {
} }
void QuadRenderer::CreateTextureFromByte(byte* buffer,int width,int height) void QuadRenderer::CreateTextureFromByte(byte* buffer,int width,int height)
{ {
int pixelSize = 4; int pixelSize = 4;
if (m_Texture.Get() == nullptr) if (m_Texture.Get() == nullptr)
{ {
CD3D11_TEXTURE2D_DESC textureDesc( CD3D11_TEXTURE2D_DESC textureDesc(
DXGI_FORMAT_B8G8R8A8_UNORM, // format DXGI_FORMAT_B8G8R8A8_UNORM, // format
static_cast<UINT>(width), // width static_cast<UINT>(width), // width
static_cast<UINT>(height), // height static_cast<UINT>(height), // height
1, // arraySize 1, // arraySize
1, // mipLevels 1, // mipLevels
D3D11_BIND_SHADER_RESOURCE, // bindFlags D3D11_BIND_SHADER_RESOURCE, // bindFlags
D3D11_USAGE_DYNAMIC, // usage D3D11_USAGE_DYNAMIC, // usage
D3D11_CPU_ACCESS_WRITE, // cpuaccessFlags D3D11_CPU_ACCESS_WRITE, // cpuaccessFlags
1, // sampleCount 1, // sampleCount
0, // sampleQuality 0, // sampleQuality
0 // miscFlags 0 // miscFlags
); );
D3D11_SUBRESOURCE_DATA data; D3D11_SUBRESOURCE_DATA data;
data.pSysMem = buffer; data.pSysMem = buffer;
data.SysMemPitch = pixelSize*width; data.SysMemPitch = pixelSize*width;
data.SysMemSlicePitch = pixelSize*width*height; data.SysMemSlicePitch = pixelSize*width*height;
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateTexture2D( m_d3dDevice->CreateTexture2D(
&textureDesc, &textureDesc,
&data, &data,
m_Texture.ReleaseAndGetAddressOf() m_Texture.ReleaseAndGetAddressOf()
) )
); );
m_d3dDevice->CreateShaderResourceView(m_Texture.Get(), NULL, m_SRV.ReleaseAndGetAddressOf()); m_d3dDevice->CreateShaderResourceView(m_Texture.Get(), NULL, m_SRV.ReleaseAndGetAddressOf());
D3D11_SAMPLER_DESC sampDesc; D3D11_SAMPLER_DESC sampDesc;
ZeroMemory(&sampDesc, sizeof(sampDesc)); ZeroMemory(&sampDesc, sizeof(sampDesc));
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0; sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX; sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
m_d3dDevice->CreateSamplerState(&sampDesc, m_QuadsTexSamplerState.ReleaseAndGetAddressOf()); m_d3dDevice->CreateSamplerState(&sampDesc, m_QuadsTexSamplerState.ReleaseAndGetAddressOf());
} }
else else
{ {
int nRowSpan = width * pixelSize; int nRowSpan = width * pixelSize;
D3D11_MAPPED_SUBRESOURCE mappedResource; D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT hr = m_d3dContext->Map(m_Texture.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); HRESULT hr = m_d3dContext->Map(m_Texture.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
BYTE* mappedData = static_cast<BYTE*>(mappedResource.pData); BYTE* mappedData = static_cast<BYTE*>(mappedResource.pData);
for (int i = 0; i < height; ++i) for (int i = 0; i < height; ++i)
{ {
memcpy(mappedData + (i*mappedResource.RowPitch), buffer + (i*nRowSpan), nRowSpan); memcpy(mappedData + (i*mappedResource.RowPitch), buffer + (i*nRowSpan), nRowSpan);
} }
m_d3dContext->Unmap(m_Texture.Get(), 0); m_d3dContext->Unmap(m_Texture.Get(), 0);
} }
} }
void QuadRenderer::CreateDeviceResources() void QuadRenderer::CreateDeviceResources()
{ {
Direct3DBase::CreateDeviceResources(); Direct3DBase::CreateDeviceResources();
D3D11_BLEND_DESC blendDesc; D3D11_BLEND_DESC blendDesc;
ZeroMemory( &blendDesc, sizeof(blendDesc) ); ZeroMemory( &blendDesc, sizeof(blendDesc) );
D3D11_RENDER_TARGET_BLEND_DESC rtbd; D3D11_RENDER_TARGET_BLEND_DESC rtbd;
ZeroMemory( &rtbd, sizeof(rtbd) ); ZeroMemory( &rtbd, sizeof(rtbd) );
rtbd.BlendEnable = TRUE; rtbd.BlendEnable = TRUE;
rtbd.SrcBlend = D3D11_BLEND_SRC_ALPHA; rtbd.SrcBlend = D3D11_BLEND_SRC_ALPHA;
rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA; rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
rtbd.BlendOp = D3D11_BLEND_OP_ADD; rtbd.BlendOp = D3D11_BLEND_OP_ADD;
rtbd.SrcBlendAlpha = D3D11_BLEND_ONE; rtbd.SrcBlendAlpha = D3D11_BLEND_ONE;
rtbd.DestBlendAlpha = D3D11_BLEND_ZERO; rtbd.DestBlendAlpha = D3D11_BLEND_ZERO;
rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD; rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;
rtbd.RenderTargetWriteMask = 0x0f; rtbd.RenderTargetWriteMask = 0x0f;
blendDesc.AlphaToCoverageEnable = false; blendDesc.AlphaToCoverageEnable = false;
blendDesc.RenderTarget[0] = rtbd; blendDesc.RenderTarget[0] = rtbd;
m_d3dDevice->CreateBlendState(&blendDesc, &m_Transparency); m_d3dDevice->CreateBlendState(&blendDesc, &m_Transparency);
D3D11_RASTERIZER_DESC cmdesc; D3D11_RASTERIZER_DESC cmdesc;
ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC)); ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC));
cmdesc.FillMode = D3D11_FILL_SOLID; cmdesc.FillMode = D3D11_FILL_SOLID;
cmdesc.CullMode = D3D11_CULL_BACK; cmdesc.CullMode = D3D11_CULL_BACK;
cmdesc.DepthClipEnable = TRUE; cmdesc.DepthClipEnable = TRUE;
cmdesc.FrontCounterClockwise = true; cmdesc.FrontCounterClockwise = true;
m_d3dDevice->CreateRasterizerState(&cmdesc, &CCWcullMode); m_d3dDevice->CreateRasterizerState(&cmdesc, &CCWcullMode);
cmdesc.FrontCounterClockwise = false; cmdesc.FrontCounterClockwise = false;
m_d3dDevice->CreateRasterizerState(&cmdesc, &CWcullMode); m_d3dDevice->CreateRasterizerState(&cmdesc, &CWcullMode);
auto loadVSTask = DX::ReadDataAsync("SimpleVertexShader.cso"); auto loadVSTask = DX::ReadDataAsync("SimpleVertexShader.cso");
auto loadPSTask = DX::ReadDataAsync("SimplePixelShader.cso"); auto loadPSTask = DX::ReadDataAsync("SimplePixelShader.cso");
auto createVSTask = loadVSTask.then([this](Platform::Array<byte>^ fileData) auto createVSTask = loadVSTask.then([this](Platform::Array<byte>^ fileData)
{ {
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateVertexShader( m_d3dDevice->CreateVertexShader(
fileData->Data, fileData->Data,
fileData->Length, fileData->Length,
nullptr, nullptr,
&m_vertexShader &m_vertexShader
) )
); );
const D3D11_INPUT_ELEMENT_DESC vertexDesc[] = const D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
{ {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
}; };
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateInputLayout( m_d3dDevice->CreateInputLayout(
vertexDesc, vertexDesc,
ARRAYSIZE(vertexDesc), ARRAYSIZE(vertexDesc),
fileData->Data, fileData->Data,
fileData->Length, fileData->Length,
&m_inputLayout &m_inputLayout
) )
); );
}); });
auto createPSTask = loadPSTask.then([this](Platform::Array<byte>^ fileData) auto createPSTask = loadPSTask.then([this](Platform::Array<byte>^ fileData)
{ {
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreatePixelShader( m_d3dDevice->CreatePixelShader(
fileData->Data, fileData->Data,
fileData->Length, fileData->Length,
nullptr, nullptr,
&m_pixelShader &m_pixelShader
) )
); );
CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER); CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateBuffer( m_d3dDevice->CreateBuffer(
&constantBufferDesc, &constantBufferDesc,
nullptr, nullptr,
&m_constantBuffer &m_constantBuffer
) )
); );
}); });
auto createCubeTask = (createPSTask && createVSTask).then([this] () auto createCubeTask = (createPSTask && createVSTask).then([this] ()
{ {
Vertex v[] = Vertex v[] =
{ {
Vertex(-1.0f, -1.0f, 1.0f, 1.0f, 1.0f), Vertex(-1.0f, -1.0f, 1.0f, 1.0f, 1.0f),
Vertex(1.0f, -1.0f, 1.0f, 0.0f, 1.0f), Vertex(1.0f, -1.0f, 1.0f, 0.0f, 1.0f),
Vertex(1.0f, 1.0f, 1.0f, 0.0f, 0.0f), Vertex(1.0f, 1.0f, 1.0f, 0.0f, 0.0f),
Vertex(-1.0f, 1.0f, 1.0f, 1.0f, 0.0f) Vertex(-1.0f, 1.0f, 1.0f, 1.0f, 0.0f)
}; };
D3D11_SUBRESOURCE_DATA vertexBufferData = {0}; D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
vertexBufferData.pSysMem = v; vertexBufferData.pSysMem = v;
vertexBufferData.SysMemPitch = 0; vertexBufferData.SysMemPitch = 0;
vertexBufferData.SysMemSlicePitch = 0; vertexBufferData.SysMemSlicePitch = 0;
CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(v), D3D11_BIND_VERTEX_BUFFER); CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(v), D3D11_BIND_VERTEX_BUFFER);
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateBuffer( m_d3dDevice->CreateBuffer(
&vertexBufferDesc, &vertexBufferDesc,
&vertexBufferData, &vertexBufferData,
&m_vertexBuffer &m_vertexBuffer
) )
); );
DWORD indices[] = DWORD indices[] =
{ {
// Front Face // Front Face
0, 2, 1, 0, 2, 1,
0, 3, 2, 0, 3, 2,
}; };
m_indexCount = ARRAYSIZE(indices); m_indexCount = ARRAYSIZE(indices);
D3D11_SUBRESOURCE_DATA indexBufferData = {0}; D3D11_SUBRESOURCE_DATA indexBufferData = {0};
indexBufferData.pSysMem = indices; indexBufferData.pSysMem = indices;
indexBufferData.SysMemPitch = 0; indexBufferData.SysMemPitch = 0;
indexBufferData.SysMemSlicePitch = 0; indexBufferData.SysMemSlicePitch = 0;
CD3D11_BUFFER_DESC indexBufferDesc(sizeof(indices), D3D11_BIND_INDEX_BUFFER); CD3D11_BUFFER_DESC indexBufferDesc(sizeof(indices), D3D11_BIND_INDEX_BUFFER);
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateBuffer( m_d3dDevice->CreateBuffer(
&indexBufferDesc, &indexBufferDesc,
&indexBufferData, &indexBufferData,
&m_indexBuffer &m_indexBuffer
) )
); );
}); });
createCubeTask.then([this] () createCubeTask.then([this] ()
{ {
m_loadingComplete = true; m_loadingComplete = true;
}); });
} }
void QuadRenderer::CreateWindowSizeDependentResources() void QuadRenderer::CreateWindowSizeDependentResources()
{ {
Direct3DBase::CreateWindowSizeDependentResources(); Direct3DBase::CreateWindowSizeDependentResources();
float aspectRatio = m_windowBounds.Width / m_windowBounds.Height; float aspectRatio = m_windowBounds.Width / m_windowBounds.Height;
float fovAngleY = 60.0f * (XM_PI / 180.0f); float fovAngleY = 60.0f * (XM_PI / 180.0f);
if (aspectRatio < 1.0f) if (aspectRatio < 1.0f)
{ {
fovAngleY /= aspectRatio; fovAngleY /= aspectRatio;
} }
XMStoreFloat4x4( XMStoreFloat4x4(
&m_constantBufferData.projection, &m_constantBufferData.projection,
XMMatrixTranspose( XMMatrixTranspose(
XMMatrixPerspectiveFovRH( XMMatrixPerspectiveFovRH(
fovAngleY, fovAngleY,
aspectRatio, aspectRatio,
0.01f, 0.01f,
100.0f 100.0f
) )
) )
); );
} }
void QuadRenderer::Update(float timeTotal, float timeDelta) void QuadRenderer::Update(float timeTotal, float timeDelta)
{ {
(void) timeDelta; // Unused parameter. (void) timeDelta; // Unused parameter.
XMVECTOR X = XMVectorSet(0.0f, 0.0f, .3f, 0.0f); XMVECTOR X = XMVectorSet(0.0f, 0.0f, .3f, 0.0f);
XMVECTOR Y = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); XMVECTOR Y = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
XMVECTOR Z = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f); XMVECTOR Z = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
XMStoreFloat4x4(&m_constantBufferData.view, XMMatrixTranspose(XMMatrixLookAtLH(X, Y, Z))); XMStoreFloat4x4(&m_constantBufferData.view, XMMatrixTranspose(XMMatrixLookAtLH(X, Y, Z)));
XMStoreFloat4x4(&m_constantBufferData.model, XMMatrixTranspose(XMMatrixRotationY(timeTotal * XM_PIDIV4))); XMStoreFloat4x4(&m_constantBufferData.model, XMMatrixTranspose(XMMatrixRotationY(timeTotal * XM_PIDIV4)));
} }
void QuadRenderer::Render() void QuadRenderer::Render()
@ -257,84 +257,84 @@ void QuadRenderer::Render()
void QuadRenderer::Render(Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTargetView, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencilView) void QuadRenderer::Render(Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTargetView, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencilView)
{ {
const float black[] = {0, 0, 0, 1.0 }; const float black[] = {0, 0, 0, 1.0 };
m_d3dContext->ClearRenderTargetView( m_d3dContext->ClearRenderTargetView(
renderTargetView.Get(), renderTargetView.Get(),
black black
); );
m_d3dContext->ClearDepthStencilView( m_d3dContext->ClearDepthStencilView(
depthStencilView.Get(), depthStencilView.Get(),
D3D11_CLEAR_DEPTH, D3D11_CLEAR_DEPTH,
1.0f, 1.0f,
0 0
); );
if (m_SRV && m_loadingComplete) // Only draw the cube once it is loaded (loading is asynchronous). if (m_SRV && m_loadingComplete) // Only draw the cube once it is loaded (loading is asynchronous).
{ {
m_d3dContext->OMSetRenderTargets( m_d3dContext->OMSetRenderTargets(
1, 1,
renderTargetView.GetAddressOf(), renderTargetView.GetAddressOf(),
depthStencilView.Get() depthStencilView.Get()
); );
m_d3dContext->UpdateSubresource( m_d3dContext->UpdateSubresource(
m_constantBuffer.Get(), m_constantBuffer.Get(),
0, 0,
NULL, NULL,
&m_constantBufferData, &m_constantBufferData,
0, 0,
0 0
); );
UINT stride = sizeof(Vertex); UINT stride = sizeof(Vertex);
UINT offset = 0; UINT offset = 0;
m_d3dContext->IASetVertexBuffers( m_d3dContext->IASetVertexBuffers(
0, 0,
1, 1,
m_vertexBuffer.GetAddressOf(), m_vertexBuffer.GetAddressOf(),
&stride, &stride,
&offset &offset
); );
m_d3dContext->IASetIndexBuffer( m_d3dContext->IASetIndexBuffer(
m_indexBuffer.Get(), m_indexBuffer.Get(),
DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_UINT,
0 0
); );
m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_d3dContext->IASetInputLayout(m_inputLayout.Get()); m_d3dContext->IASetInputLayout(m_inputLayout.Get());
m_d3dContext->VSSetShader( m_d3dContext->VSSetShader(
m_vertexShader.Get(), m_vertexShader.Get(),
nullptr, nullptr,
0 0
); );
m_d3dContext->VSSetConstantBuffers( m_d3dContext->VSSetConstantBuffers(
0, 0,
1, 1,
m_constantBuffer.GetAddressOf() m_constantBuffer.GetAddressOf()
); );
m_d3dContext->PSSetShader( m_d3dContext->PSSetShader(
m_pixelShader.Get(), m_pixelShader.Get(),
nullptr, nullptr,
0 0
); );
m_d3dContext->PSSetShaderResources(0, 1, m_SRV.GetAddressOf()); m_d3dContext->PSSetShaderResources(0, 1, m_SRV.GetAddressOf());
m_d3dContext->PSSetSamplers(0, 1, m_QuadsTexSamplerState.GetAddressOf()); m_d3dContext->PSSetSamplers(0, 1, m_QuadsTexSamplerState.GetAddressOf());
m_d3dContext->OMSetBlendState(m_Transparency.Get(), nullptr, 0xffffffff); m_d3dContext->OMSetBlendState(m_Transparency.Get(), nullptr, 0xffffffff);
m_d3dContext->RSSetState(CCWcullMode.Get()); m_d3dContext->RSSetState(CCWcullMode.Get());
m_d3dContext->DrawIndexed( m_d3dContext->DrawIndexed(
m_indexCount, m_indexCount,
0, 0,
0 0
); );
} }
} }

@ -6,51 +6,51 @@
struct ModelViewProjectionConstantBuffer struct ModelViewProjectionConstantBuffer
{ {
DirectX::XMFLOAT4X4 model; DirectX::XMFLOAT4X4 model;
DirectX::XMFLOAT4X4 view; DirectX::XMFLOAT4X4 view;
DirectX::XMFLOAT4X4 projection; DirectX::XMFLOAT4X4 projection;
}; };
struct Vertex //Overloaded Vertex Structure struct Vertex //Overloaded Vertex Structure
{ {
Vertex(){} Vertex(){}
Vertex(float x, float y, float z, Vertex(float x, float y, float z,
float u, float v) float u, float v)
: pos(x,y,z), texCoord(u, v){} : pos(x,y,z), texCoord(u, v){}
DirectX::XMFLOAT3 pos; DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT2 texCoord; DirectX::XMFLOAT2 texCoord;
}; };
// This class renders a simple quad. // This class renders a simple quad.
ref class QuadRenderer sealed : public Direct3DBase ref class QuadRenderer sealed : public Direct3DBase
{ {
public: public:
QuadRenderer(); QuadRenderer();
void Update(float timeTotal = 0.0f, float timeDelta = 0.0f); void Update(float timeTotal = 0.0f, float timeDelta = 0.0f);
void CreateTextureFromByte(byte * buffer,int width,int height); void CreateTextureFromByte(byte * buffer,int width,int height);
// Direct3DBase methods. // Direct3DBase methods.
virtual void CreateDeviceResources() override; virtual void CreateDeviceResources() override;
virtual void CreateWindowSizeDependentResources() override; virtual void CreateWindowSizeDependentResources() override;
virtual void Render() override; virtual void Render() override;
private: private:
void Render(Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTargetView, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencilView); void Render(Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTargetView, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencilView);
bool m_loadingComplete; bool m_loadingComplete;
uint32 m_indexCount; uint32 m_indexCount;
ModelViewProjectionConstantBuffer m_constantBufferData; ModelViewProjectionConstantBuffer m_constantBufferData;
Microsoft::WRL::ComPtr<ID3D11InputLayout> m_inputLayout; Microsoft::WRL::ComPtr<ID3D11InputLayout> m_inputLayout;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer; Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_indexBuffer; Microsoft::WRL::ComPtr<ID3D11Buffer> m_indexBuffer;
Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vertexShader; Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vertexShader;
Microsoft::WRL::ComPtr<ID3D11PixelShader> m_pixelShader; Microsoft::WRL::ComPtr<ID3D11PixelShader> m_pixelShader;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_constantBuffer; Microsoft::WRL::ComPtr<ID3D11Buffer> m_constantBuffer;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_Texture; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_Texture;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_SRV; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_SRV;
Microsoft::WRL::ComPtr<ID3D11SamplerState> m_QuadsTexSamplerState; Microsoft::WRL::ComPtr<ID3D11SamplerState> m_QuadsTexSamplerState;
Microsoft::WRL::ComPtr<ID3D11BlendState> m_Transparency; Microsoft::WRL::ComPtr<ID3D11BlendState> m_Transparency;
Microsoft::WRL::ComPtr<ID3D11RasterizerState> CCWcullMode; Microsoft::WRL::ComPtr<ID3D11RasterizerState> CCWcullMode;
Microsoft::WRL::ComPtr<ID3D11RasterizerState> CWcullMode; Microsoft::WRL::ComPtr<ID3D11RasterizerState> CWcullMode;
}; };

@ -1,8 +1,8 @@
cbuffer ModelViewProjectionConstantBuffer : register(b0) cbuffer ModelViewProjectionConstantBuffer : register(b0)
{ {
matrix model; matrix model;
matrix view; matrix view;
matrix projection; matrix projection;
}; };
struct VertexInputType struct VertexInputType
@ -34,6 +34,6 @@ PixelInputType main(VertexInputType input)
output.position = mul(output.position, projection); output.position = mul(output.position, projection);
// Store the texture coordinates for the pixel shader. // Store the texture coordinates for the pixel shader.
output.tex = input.tex; output.tex = input.tex;
return output; return output;
} }

@ -1,30 +1,39 @@
<phone:PhoneApplicationPage <phone:PhoneApplicationPage x:Class="PhoneXamlDirect3DApp1.MainPage"
x:Class="PhoneXamlDirect3DApp1.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" FontFamily="{StaticResource PhoneFontFamilyNormal}"
mc:Ignorable="d" FontSize="{StaticResource PhoneFontSizeNormal}"
FontFamily="{StaticResource PhoneFontFamilyNormal}" Foreground="{StaticResource PhoneForegroundBrush}"
FontSize="{StaticResource PhoneFontSizeNormal}" Orientation="Portrait"
Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait"
SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True"
shell:SystemTray.IsVisible="True"> mc:Ignorable="d">
<!--LayoutRoot is the root grid where all page content is placed--> <!-- LayoutRoot is the root grid where all page content is placed -->
<Grid x:Name="LayoutRoot" Background="Transparent"> <Grid x:Name="LayoutRoot" Background="Transparent">
<DrawingSurface x:Name="DrawingSurface" Loaded="DrawingSurface_Loaded" /> <DrawingSurface x:Name="DrawingSurface" Loaded="DrawingSurface_Loaded" />
<StackPanel Margin="40"> <StackPanel Margin="40">
<RadioButton x:Name="Normal" Content="Normal" GroupName="Group1" <RadioButton x:Name="Normal"
Checked="RadioButton_Checked" IsChecked="True"/> Checked="RadioButton_Checked"
<RadioButton x:Name="Gray" Content="Gray" GroupName="Group1" Content="Normal"
Checked="RadioButton_Checked"/> GroupName="Group1"
<RadioButton x:Name="Canny" Content="Canny" GroupName="Group1" IsChecked="True" />
Checked="RadioButton_Checked"/> <RadioButton x:Name="Gray"
<RadioButton x:Name="Sepia" Content="Sepia" GroupName="Group1" Checked="RadioButton_Checked"
Checked="RadioButton_Checked"/> Content="Gray"
GroupName="Group1" />
<RadioButton x:Name="Canny"
Checked="RadioButton_Checked"
Content="Canny"
GroupName="Group1" />
<RadioButton x:Name="Sepia"
Checked="RadioButton_Checked"
Content="Sepia"
GroupName="Group1" />
</StackPanel> </StackPanel>
</Grid> </Grid>

@ -91,5 +91,5 @@ namespace PhoneXamlDirect3DApp1
break; break;
} }
} }
} }
} }

@ -3,7 +3,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Resources; using System.Resources;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("PhoneXamlDirect3DApp1")] [assembly: AssemblyTitle("PhoneXamlDirect3DApp1")]
@ -15,8 +15,8 @@ using System.Resources;
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible // Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from // to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. // COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
@ -26,11 +26,11 @@ using System.Resources;
// Version information for an assembly consists of the following four values: // Version information for an assembly consists of the following four values:
// //
// Major Version // Major Version
// Minor Version // Minor Version
// Build Number // Build Number
// Revision // Revision
// //
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]

@ -6,71 +6,71 @@
ref class BasicTimer sealed ref class BasicTimer sealed
{ {
public: public:
// Initializes internal timer values. // Initializes internal timer values.
BasicTimer() BasicTimer()
{ {
if (!QueryPerformanceFrequency(&m_frequency)) if (!QueryPerformanceFrequency(&m_frequency))
{ {
throw ref new Platform::FailureException(); throw ref new Platform::FailureException();
} }
Reset(); Reset();
} }
// Reset the timer to initial values. // Reset the timer to initial values.
void Reset() void Reset()
{ {
Update(); Update();
m_startTime = m_currentTime; m_startTime = m_currentTime;
m_total = 0.0f; m_total = 0.0f;
m_delta = 1.0f / 60.0f; m_delta = 1.0f / 60.0f;
} }
// Update the timer's internal values. // Update the timer's internal values.
void Update() void Update()
{ {
if (!QueryPerformanceCounter(&m_currentTime)) if (!QueryPerformanceCounter(&m_currentTime))
{ {
throw ref new Platform::FailureException(); throw ref new Platform::FailureException();
} }
m_total = static_cast<float>( m_total = static_cast<float>(
static_cast<double>(m_currentTime.QuadPart - m_startTime.QuadPart) / static_cast<double>(m_currentTime.QuadPart - m_startTime.QuadPart) /
static_cast<double>(m_frequency.QuadPart) static_cast<double>(m_frequency.QuadPart)
); );
if (m_lastTime.QuadPart == m_startTime.QuadPart) if (m_lastTime.QuadPart == m_startTime.QuadPart)
{ {
// If the timer was just reset, report a time delta equivalent to 60Hz frame time. // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
m_delta = 1.0f / 60.0f; m_delta = 1.0f / 60.0f;
} }
else else
{ {
m_delta = static_cast<float>( m_delta = static_cast<float>(
static_cast<double>(m_currentTime.QuadPart - m_lastTime.QuadPart) / static_cast<double>(m_currentTime.QuadPart - m_lastTime.QuadPart) /
static_cast<double>(m_frequency.QuadPart) static_cast<double>(m_frequency.QuadPart)
); );
} }
m_lastTime = m_currentTime; m_lastTime = m_currentTime;
} }
// Duration in seconds between the last call to Reset() and the last call to Update(). // Duration in seconds between the last call to Reset() and the last call to Update().
property float Total property float Total
{ {
float get() { return m_total; } float get() { return m_total; }
} }
// Duration in seconds between the previous two calls to Update(). // Duration in seconds between the previous two calls to Update().
property float Delta property float Delta
{ {
float get() { return m_delta; } float get() { return m_delta; }
} }
private: private:
LARGE_INTEGER m_frequency; LARGE_INTEGER m_frequency;
LARGE_INTEGER m_currentTime; LARGE_INTEGER m_currentTime;
LARGE_INTEGER m_startTime; LARGE_INTEGER m_startTime;
LARGE_INTEGER m_lastTime; LARGE_INTEGER m_lastTime;
float m_total; float m_total;
float m_delta; float m_delta;
}; };

@ -8,303 +8,303 @@ using namespace Windows::Foundation;
using namespace Windows::UI::Core; using namespace Windows::UI::Core;
CubeRenderer::CubeRenderer() : CubeRenderer::CubeRenderer() :
m_loadingComplete(false), m_loadingComplete(false),
m_indexCount(0) m_indexCount(0)
{ {
} }
void CubeRenderer::CreateTextureFromByte(byte* buffer, int width, int height) void CubeRenderer::CreateTextureFromByte(byte* buffer, int width, int height)
{ {
int pixelSize = 4; int pixelSize = 4;
if (m_texture.Get() == nullptr) if (m_texture.Get() == nullptr)
{ {
CD3D11_TEXTURE2D_DESC textureDesc( CD3D11_TEXTURE2D_DESC textureDesc(
DXGI_FORMAT_B8G8R8A8_UNORM, // format DXGI_FORMAT_B8G8R8A8_UNORM, // format
static_cast<UINT>(width), // width static_cast<UINT>(width), // width
static_cast<UINT>(height), // height static_cast<UINT>(height), // height
1, // arraySize 1, // arraySize
1, // mipLevels 1, // mipLevels
D3D11_BIND_SHADER_RESOURCE, // bindFlags D3D11_BIND_SHADER_RESOURCE, // bindFlags
D3D11_USAGE_DYNAMIC, // usage D3D11_USAGE_DYNAMIC, // usage
D3D11_CPU_ACCESS_WRITE, // cpuaccessFlags D3D11_CPU_ACCESS_WRITE, // cpuaccessFlags
1, // sampleCount 1, // sampleCount
0, // sampleQuality 0, // sampleQuality
0 // miscFlags 0 // miscFlags
); );
D3D11_SUBRESOURCE_DATA data; D3D11_SUBRESOURCE_DATA data;
data.pSysMem = buffer; data.pSysMem = buffer;
data.SysMemPitch = pixelSize*width; data.SysMemPitch = pixelSize*width;
data.SysMemSlicePitch = pixelSize*width*height; data.SysMemSlicePitch = pixelSize*width*height;
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateTexture2D( m_d3dDevice->CreateTexture2D(
&textureDesc, &textureDesc,
&data, &data,
m_texture.ReleaseAndGetAddressOf() m_texture.ReleaseAndGetAddressOf()
) )
); );
m_d3dDevice->CreateShaderResourceView(m_texture.Get(), NULL, m_SRV.ReleaseAndGetAddressOf()); m_d3dDevice->CreateShaderResourceView(m_texture.Get(), NULL, m_SRV.ReleaseAndGetAddressOf());
D3D11_SAMPLER_DESC sampDesc; D3D11_SAMPLER_DESC sampDesc;
ZeroMemory(&sampDesc, sizeof(sampDesc)); ZeroMemory(&sampDesc, sizeof(sampDesc));
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0; sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX; sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
m_d3dDevice->CreateSamplerState(&sampDesc, m_cubesTexSamplerState.ReleaseAndGetAddressOf()); m_d3dDevice->CreateSamplerState(&sampDesc, m_cubesTexSamplerState.ReleaseAndGetAddressOf());
} }
else else
{ {
int nRowSpan = width * pixelSize; int nRowSpan = width * pixelSize;
D3D11_MAPPED_SUBRESOURCE mappedResource; D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT hr = m_d3dContext->Map(m_texture.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); HRESULT hr = m_d3dContext->Map(m_texture.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
BYTE* mappedData = static_cast<BYTE*>(mappedResource.pData); BYTE* mappedData = static_cast<BYTE*>(mappedResource.pData);
for (int i = 0; i < height; ++i) for (int i = 0; i < height; ++i)
{ {
memcpy(mappedData + (i*mappedResource.RowPitch), buffer + (i*nRowSpan), nRowSpan); memcpy(mappedData + (i*mappedResource.RowPitch), buffer + (i*nRowSpan), nRowSpan);
} }
m_d3dContext->Unmap(m_texture.Get(), 0); m_d3dContext->Unmap(m_texture.Get(), 0);
} }
} }
void CubeRenderer::CreateDeviceResources() void CubeRenderer::CreateDeviceResources()
{ {
Direct3DBase::CreateDeviceResources(); Direct3DBase::CreateDeviceResources();
D3D11_BLEND_DESC blendDesc; D3D11_BLEND_DESC blendDesc;
ZeroMemory( &blendDesc, sizeof(blendDesc) ); ZeroMemory( &blendDesc, sizeof(blendDesc) );
D3D11_RENDER_TARGET_BLEND_DESC rtbd; D3D11_RENDER_TARGET_BLEND_DESC rtbd;
ZeroMemory( &rtbd, sizeof(rtbd) ); ZeroMemory( &rtbd, sizeof(rtbd) );
rtbd.BlendEnable = TRUE; rtbd.BlendEnable = TRUE;
rtbd.SrcBlend = D3D11_BLEND_SRC_ALPHA; rtbd.SrcBlend = D3D11_BLEND_SRC_ALPHA;
rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA; rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
rtbd.BlendOp = D3D11_BLEND_OP_ADD; rtbd.BlendOp = D3D11_BLEND_OP_ADD;
rtbd.SrcBlendAlpha = D3D11_BLEND_ONE; rtbd.SrcBlendAlpha = D3D11_BLEND_ONE;
rtbd.DestBlendAlpha = D3D11_BLEND_ZERO; rtbd.DestBlendAlpha = D3D11_BLEND_ZERO;
rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD; rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;
rtbd.RenderTargetWriteMask = 0x0f; rtbd.RenderTargetWriteMask = 0x0f;
blendDesc.AlphaToCoverageEnable = false; blendDesc.AlphaToCoverageEnable = false;
blendDesc.RenderTarget[0] = rtbd; blendDesc.RenderTarget[0] = rtbd;
m_d3dDevice->CreateBlendState(&blendDesc, &m_transparency); m_d3dDevice->CreateBlendState(&blendDesc, &m_transparency);
D3D11_RASTERIZER_DESC cmdesc; D3D11_RASTERIZER_DESC cmdesc;
ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC)); ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC));
cmdesc.FillMode = D3D11_FILL_SOLID; cmdesc.FillMode = D3D11_FILL_SOLID;
cmdesc.CullMode = D3D11_CULL_BACK; cmdesc.CullMode = D3D11_CULL_BACK;
cmdesc.DepthClipEnable = TRUE; cmdesc.DepthClipEnable = TRUE;
cmdesc.FrontCounterClockwise = true; cmdesc.FrontCounterClockwise = true;
m_d3dDevice->CreateRasterizerState(&cmdesc, &m_CCWcullMode); m_d3dDevice->CreateRasterizerState(&cmdesc, &m_CCWcullMode);
cmdesc.FrontCounterClockwise = false; cmdesc.FrontCounterClockwise = false;
m_d3dDevice->CreateRasterizerState(&cmdesc, &m_CWcullMode); m_d3dDevice->CreateRasterizerState(&cmdesc, &m_CWcullMode);
auto loadVSTask = DX::ReadDataAsync("SimpleVertexShader.cso"); auto loadVSTask = DX::ReadDataAsync("SimpleVertexShader.cso");
auto loadPSTask = DX::ReadDataAsync("SimplePixelShader.cso"); auto loadPSTask = DX::ReadDataAsync("SimplePixelShader.cso");
auto createVSTask = loadVSTask.then([this](Platform::Array<byte>^ fileData) { auto createVSTask = loadVSTask.then([this](Platform::Array<byte>^ fileData) {
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateVertexShader( m_d3dDevice->CreateVertexShader(
fileData->Data, fileData->Data,
fileData->Length, fileData->Length,
nullptr, nullptr,
&m_vertexShader &m_vertexShader
) )
); );
const D3D11_INPUT_ELEMENT_DESC vertexDesc[] = const D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
{ {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
}; };
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateInputLayout( m_d3dDevice->CreateInputLayout(
vertexDesc, vertexDesc,
ARRAYSIZE(vertexDesc), ARRAYSIZE(vertexDesc),
fileData->Data, fileData->Data,
fileData->Length, fileData->Length,
&m_inputLayout &m_inputLayout
) )
); );
}); });
auto createPSTask = loadPSTask.then([this](Platform::Array<byte>^ fileData) { auto createPSTask = loadPSTask.then([this](Platform::Array<byte>^ fileData) {
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreatePixelShader( m_d3dDevice->CreatePixelShader(
fileData->Data, fileData->Data,
fileData->Length, fileData->Length,
nullptr, nullptr,
&m_pixelShader &m_pixelShader
) )
); );
CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER); CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateBuffer( m_d3dDevice->CreateBuffer(
&constantBufferDesc, &constantBufferDesc,
nullptr, nullptr,
&m_constantBuffer &m_constantBuffer
) )
); );
}); });
auto createCubeTask = (createPSTask && createVSTask).then([this] () { auto createCubeTask = (createPSTask && createVSTask).then([this] () {
Vertex v[] = Vertex v[] =
{ {
// Front Face // Front Face
Vertex(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f), Vertex(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f),
Vertex(-1.0f, 1.0f, -1.0f, 0.0f, 0.0f), Vertex(-1.0f, 1.0f, -1.0f, 0.0f, 0.0f),
Vertex( 1.0f, 1.0f, -1.0f, 1.0f, 0.0f), Vertex( 1.0f, 1.0f, -1.0f, 1.0f, 0.0f),
Vertex( 1.0f, -1.0f, -1.0f, 1.0f, 1.0f), Vertex( 1.0f, -1.0f, -1.0f, 1.0f, 1.0f),
// Back Face // Back Face
Vertex(-1.0f, -1.0f, 1.0f, 1.0f, 1.0f), Vertex(-1.0f, -1.0f, 1.0f, 1.0f, 1.0f),
Vertex( 1.0f, -1.0f, 1.0f, 0.0f, 1.0f), Vertex( 1.0f, -1.0f, 1.0f, 0.0f, 1.0f),
Vertex( 1.0f, 1.0f, 1.0f, 0.0f, 0.0f), Vertex( 1.0f, 1.0f, 1.0f, 0.0f, 0.0f),
Vertex(-1.0f, 1.0f, 1.0f, 1.0f, 0.0f), Vertex(-1.0f, 1.0f, 1.0f, 1.0f, 0.0f),
// Top Face // Top Face
Vertex(-1.0f, 1.0f, -1.0f, 0.0f, 1.0f), Vertex(-1.0f, 1.0f, -1.0f, 0.0f, 1.0f),
Vertex(-1.0f, 1.0f, 1.0f, 0.0f, 0.0f), Vertex(-1.0f, 1.0f, 1.0f, 0.0f, 0.0f),
Vertex( 1.0f, 1.0f, 1.0f, 1.0f, 0.0f), Vertex( 1.0f, 1.0f, 1.0f, 1.0f, 0.0f),
Vertex( 1.0f, 1.0f, -1.0f, 1.0f, 1.0f), Vertex( 1.0f, 1.0f, -1.0f, 1.0f, 1.0f),
// Bottom Face // Bottom Face
Vertex(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f), Vertex(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f),
Vertex( 1.0f, -1.0f, -1.0f, 0.0f, 1.0f), Vertex( 1.0f, -1.0f, -1.0f, 0.0f, 1.0f),
Vertex( 1.0f, -1.0f, 1.0f, 0.0f, 0.0f), Vertex( 1.0f, -1.0f, 1.0f, 0.0f, 0.0f),
Vertex(-1.0f, -1.0f, 1.0f, 1.0f, 0.0f), Vertex(-1.0f, -1.0f, 1.0f, 1.0f, 0.0f),
// Left Face // Left Face
Vertex(-1.0f, -1.0f, 1.0f, 0.0f, 1.0f), Vertex(-1.0f, -1.0f, 1.0f, 0.0f, 1.0f),
Vertex(-1.0f, 1.0f, 1.0f, 0.0f, 0.0f), Vertex(-1.0f, 1.0f, 1.0f, 0.0f, 0.0f),
Vertex(-1.0f, 1.0f, -1.0f, 1.0f, 0.0f), Vertex(-1.0f, 1.0f, -1.0f, 1.0f, 0.0f),
Vertex(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f), Vertex(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f),
// Right Face // Right Face
Vertex( 1.0f, -1.0f, -1.0f, 0.0f, 1.0f), Vertex( 1.0f, -1.0f, -1.0f, 0.0f, 1.0f),
Vertex( 1.0f, 1.0f, -1.0f, 0.0f, 0.0f), Vertex( 1.0f, 1.0f, -1.0f, 0.0f, 0.0f),
Vertex( 1.0f, 1.0f, 1.0f, 1.0f, 0.0f), Vertex( 1.0f, 1.0f, 1.0f, 1.0f, 0.0f),
Vertex( 1.0f, -1.0f, 1.0f, 1.0f, 1.0f), Vertex( 1.0f, -1.0f, 1.0f, 1.0f, 1.0f),
}; };
D3D11_SUBRESOURCE_DATA vertexBufferData = {0}; D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
vertexBufferData.pSysMem = v; vertexBufferData.pSysMem = v;
vertexBufferData.SysMemPitch = 0; vertexBufferData.SysMemPitch = 0;
vertexBufferData.SysMemSlicePitch = 0; vertexBufferData.SysMemSlicePitch = 0;
CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(v), D3D11_BIND_VERTEX_BUFFER); CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(v), D3D11_BIND_VERTEX_BUFFER);
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateBuffer( m_d3dDevice->CreateBuffer(
&vertexBufferDesc, &vertexBufferDesc,
&vertexBufferData, &vertexBufferData,
&m_vertexBuffer &m_vertexBuffer
) )
); );
DWORD indices[] = { DWORD indices[] = {
// Front Face // Front Face
0, 2, 1, 0, 2, 1,
0, 3, 2, 0, 3, 2,
// Back Face // Back Face
4, 6, 5, 4, 6, 5,
4, 7, 6, 4, 7, 6,
// Top Face // Top Face
8, 10, 9, 8, 10, 9,
8, 11, 10, 8, 11, 10,
// Bottom Face // Bottom Face
12, 14, 13, 12, 14, 13,
12, 15, 14, 12, 15, 14,
// Left Face // Left Face
16, 18, 17, 16, 18, 17,
16, 19, 18, 16, 19, 18,
// Right Face // Right Face
20, 22, 21, 20, 22, 21,
20, 23, 22 20, 23, 22
}; };
m_indexCount = ARRAYSIZE(indices); m_indexCount = ARRAYSIZE(indices);
D3D11_SUBRESOURCE_DATA indexBufferData = {0}; D3D11_SUBRESOURCE_DATA indexBufferData = {0};
indexBufferData.pSysMem = indices; indexBufferData.pSysMem = indices;
indexBufferData.SysMemPitch = 0; indexBufferData.SysMemPitch = 0;
indexBufferData.SysMemSlicePitch = 0; indexBufferData.SysMemSlicePitch = 0;
CD3D11_BUFFER_DESC indexBufferDesc(sizeof(indices), D3D11_BIND_INDEX_BUFFER); CD3D11_BUFFER_DESC indexBufferDesc(sizeof(indices), D3D11_BIND_INDEX_BUFFER);
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateBuffer( m_d3dDevice->CreateBuffer(
&indexBufferDesc, &indexBufferDesc,
&indexBufferData, &indexBufferData,
&m_indexBuffer &m_indexBuffer
) )
); );
}); });
createCubeTask.then([this] () { createCubeTask.then([this] () {
m_loadingComplete = true; m_loadingComplete = true;
}); });
} }
void CubeRenderer::CreateWindowSizeDependentResources() void CubeRenderer::CreateWindowSizeDependentResources()
{ {
Direct3DBase::CreateWindowSizeDependentResources(); Direct3DBase::CreateWindowSizeDependentResources();
float aspectRatio = m_windowBounds.Width / m_windowBounds.Height; float aspectRatio = m_windowBounds.Width / m_windowBounds.Height;
float fovAngleY = 70.0f * XM_PI / 180.0f; float fovAngleY = 70.0f * XM_PI / 180.0f;
if (aspectRatio < 1.0f) if (aspectRatio < 1.0f)
{ {
fovAngleY /= aspectRatio; fovAngleY /= aspectRatio;
} }
XMStoreFloat4x4( XMStoreFloat4x4(
&m_constantBufferData.projection, &m_constantBufferData.projection,
XMMatrixTranspose( XMMatrixTranspose(
XMMatrixPerspectiveFovRH( XMMatrixPerspectiveFovRH(
fovAngleY, fovAngleY,
aspectRatio, aspectRatio,
0.01f, 0.01f,
100.0f 100.0f
) )
) )
); );
} }
void CubeRenderer::Update(float timeTotal, float timeDelta) void CubeRenderer::Update(float timeTotal, float timeDelta)
{ {
(void) timeDelta; // Unused parameter. (void) timeDelta; // Unused parameter.
XMVECTOR eye = XMVectorSet(0.0f, 0.0f, 3.f, 0.0f); XMVECTOR eye = XMVectorSet(0.0f, 0.0f, 3.f, 0.0f);
XMVECTOR at = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); XMVECTOR at = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMStoreFloat4x4(&m_constantBufferData.view, XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up))); XMStoreFloat4x4(&m_constantBufferData.view, XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up)));
XMStoreFloat4x4(&m_constantBufferData.model, XMMatrixTranspose(XMMatrixRotationY(timeTotal * XM_PIDIV4))); XMStoreFloat4x4(&m_constantBufferData.model, XMMatrixTranspose(XMMatrixRotationY(timeTotal * XM_PIDIV4)));
} }
@ -319,98 +319,98 @@ void CubeRenderer::Render()
void CubeRenderer::Render(Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTargetView, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencilView) void CubeRenderer::Render(Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTargetView, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencilView)
{ {
const float black[] = {0, 0, 0, 1.0 }; const float black[] = {0, 0, 0, 1.0 };
m_d3dContext->ClearRenderTargetView( m_d3dContext->ClearRenderTargetView(
renderTargetView.Get(), renderTargetView.Get(),
black black
); );
m_d3dContext->ClearDepthStencilView( m_d3dContext->ClearDepthStencilView(
depthStencilView.Get(), depthStencilView.Get(),
D3D11_CLEAR_DEPTH, D3D11_CLEAR_DEPTH,
1.0f, 1.0f,
0 0
); );
// Only draw the cube once it is loaded (loading is asynchronous). // Only draw the cube once it is loaded (loading is asynchronous).
if (!m_SRV || !m_loadingComplete) if (!m_SRV || !m_loadingComplete)
{ {
return; return;
} }
m_d3dContext->OMSetRenderTargets( m_d3dContext->OMSetRenderTargets(
1, 1,
renderTargetView.GetAddressOf(), renderTargetView.GetAddressOf(),
depthStencilView.Get() depthStencilView.Get()
); );
m_d3dContext->UpdateSubresource( m_d3dContext->UpdateSubresource(
m_constantBuffer.Get(), m_constantBuffer.Get(),
0, 0,
NULL, NULL,
&m_constantBufferData, &m_constantBufferData,
0, 0,
0 0
); );
UINT stride = sizeof(Vertex); UINT stride = sizeof(Vertex);
UINT offset = 0; UINT offset = 0;
m_d3dContext->IASetVertexBuffers( m_d3dContext->IASetVertexBuffers(
0, 0,
1, 1,
m_vertexBuffer.GetAddressOf(), m_vertexBuffer.GetAddressOf(),
&stride, &stride,
&offset &offset
); );
m_d3dContext->IASetIndexBuffer( m_d3dContext->IASetIndexBuffer(
m_indexBuffer.Get(), m_indexBuffer.Get(),
DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_UINT,
0 0
); );
m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_d3dContext->IASetInputLayout(m_inputLayout.Get()); m_d3dContext->IASetInputLayout(m_inputLayout.Get());
m_d3dContext->VSSetShader( m_d3dContext->VSSetShader(
m_vertexShader.Get(), m_vertexShader.Get(),
nullptr, nullptr,
0 0
); );
m_d3dContext->VSSetConstantBuffers( m_d3dContext->VSSetConstantBuffers(
0, 0,
1, 1,
m_constantBuffer.GetAddressOf() m_constantBuffer.GetAddressOf()
); );
m_d3dContext->PSSetShader( m_d3dContext->PSSetShader(
m_pixelShader.Get(), m_pixelShader.Get(),
nullptr, nullptr,
0 0
); );
m_d3dContext->PSSetShaderResources( 0, 1, m_SRV.GetAddressOf()); m_d3dContext->PSSetShaderResources( 0, 1, m_SRV.GetAddressOf());
m_d3dContext->PSSetSamplers( 0, 1, m_cubesTexSamplerState.GetAddressOf()); m_d3dContext->PSSetSamplers( 0, 1, m_cubesTexSamplerState.GetAddressOf());
//float blendFactor[] = {0.75f, 0.75f, 0.75f, 1.0f}; //float blendFactor[] = {0.75f, 0.75f, 0.75f, 1.0f};
m_d3dContext->OMSetBlendState(m_transparency.Get(), nullptr, 0xffffffff); m_d3dContext->OMSetBlendState(m_transparency.Get(), nullptr, 0xffffffff);
m_d3dContext->RSSetState(m_CCWcullMode.Get()); m_d3dContext->RSSetState(m_CCWcullMode.Get());
m_d3dContext->DrawIndexed( m_d3dContext->DrawIndexed(
m_indexCount, m_indexCount,
0, 0,
0 0
); );
m_d3dContext->RSSetState(m_CWcullMode.Get()); m_d3dContext->RSSetState(m_CWcullMode.Get());
m_d3dContext->DrawIndexed( m_d3dContext->DrawIndexed(
m_indexCount, m_indexCount,
0, 0,
0 0
); );
} }

@ -7,55 +7,55 @@
struct ModelViewProjectionConstantBuffer struct ModelViewProjectionConstantBuffer
{ {
DirectX::XMFLOAT4X4 model; DirectX::XMFLOAT4X4 model;
DirectX::XMFLOAT4X4 view; DirectX::XMFLOAT4X4 view;
DirectX::XMFLOAT4X4 projection; DirectX::XMFLOAT4X4 projection;
}; };
struct Vertex //Overloaded Vertex Structure struct Vertex //Overloaded Vertex Structure
{ {
Vertex(){} Vertex(){}
Vertex(float x, float y, float z, Vertex(float x, float y, float z,
float u, float v) float u, float v)
: pos(x,y,z), texCoord(u, v){} : pos(x,y,z), texCoord(u, v){}
DirectX::XMFLOAT3 pos; DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT2 texCoord; DirectX::XMFLOAT2 texCoord;
}; };
// This class renders a simple spinning cube. // This class renders a simple spinning cube.
ref class CubeRenderer sealed : public Direct3DBase ref class CubeRenderer sealed : public Direct3DBase
{ {
public: public:
CubeRenderer(); CubeRenderer();
// Direct3DBase methods. // Direct3DBase methods.
virtual void CreateDeviceResources() override; virtual void CreateDeviceResources() override;
virtual void CreateWindowSizeDependentResources() override; virtual void CreateWindowSizeDependentResources() override;
virtual void Render() override; virtual void Render() override;
// Method for updating time-dependent objects. // Method for updating time-dependent objects.
void Update(float timeTotal, float timeDelta); void Update(float timeTotal, float timeDelta);
void CreateTextureFromByte(byte * buffer,int width,int height); void CreateTextureFromByte(byte * buffer,int width,int height);
private: private:
void Render(Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTargetView, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencilView); void Render(Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTargetView, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencilView);
bool m_loadingComplete; bool m_loadingComplete;
Microsoft::WRL::ComPtr<ID3D11InputLayout> m_inputLayout; Microsoft::WRL::ComPtr<ID3D11InputLayout> m_inputLayout;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer; Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_indexBuffer; Microsoft::WRL::ComPtr<ID3D11Buffer> m_indexBuffer;
Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vertexShader; Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vertexShader;
Microsoft::WRL::ComPtr<ID3D11PixelShader> m_pixelShader; Microsoft::WRL::ComPtr<ID3D11PixelShader> m_pixelShader;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_constantBuffer; Microsoft::WRL::ComPtr<ID3D11Buffer> m_constantBuffer;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_texture; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_texture;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_SRV; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_SRV;
Microsoft::WRL::ComPtr<ID3D11SamplerState> m_cubesTexSamplerState; Microsoft::WRL::ComPtr<ID3D11SamplerState> m_cubesTexSamplerState;
uint32 m_indexCount; uint32 m_indexCount;
ModelViewProjectionConstantBuffer m_constantBufferData; ModelViewProjectionConstantBuffer m_constantBufferData;
std::mutex m_mutex; std::mutex m_mutex;
Microsoft::WRL::ComPtr<ID3D11BlendState> m_transparency; Microsoft::WRL::ComPtr<ID3D11BlendState> m_transparency;
Microsoft::WRL::ComPtr<ID3D11RasterizerState> m_CCWcullMode; Microsoft::WRL::ComPtr<ID3D11RasterizerState> m_CCWcullMode;
Microsoft::WRL::ComPtr<ID3D11RasterizerState> m_CWcullMode; Microsoft::WRL::ComPtr<ID3D11RasterizerState> m_CWcullMode;
}; };

@ -15,148 +15,148 @@ Direct3DBase::Direct3DBase()
// Initialize the Direct3D resources required to run. // Initialize the Direct3D resources required to run.
void Direct3DBase::Initialize() void Direct3DBase::Initialize()
{ {
CreateDeviceResources(); CreateDeviceResources();
} }
// These are the resources that depend on the device. // These are the resources that depend on the device.
void Direct3DBase::CreateDeviceResources() void Direct3DBase::CreateDeviceResources()
{ {
// This flag adds support for surfaces with a different color channel ordering // This flag adds support for surfaces with a different color channel ordering
// than the API default. It is required for compatibility with Direct2D. // than the API default. It is required for compatibility with Direct2D.
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#if defined(_DEBUG) #if defined(_DEBUG)
// If the project is in a debug build, enable debugging via SDK Layers with this flag. // If the project is in a debug build, enable debugging via SDK Layers with this flag.
creationFlags |= D3D11_CREATE_DEVICE_DEBUG; creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif #endif
// This array defines the set of DirectX hardware feature levels this app will support. // This array defines the set of DirectX hardware feature levels this app will support.
// Note the ordering should be preserved. // Note the ordering should be preserved.
// Don't forget to declare your application's minimum required feature level in its // Don't forget to declare your application's minimum required feature level in its
// description. All applications are assumed to support 9.1 unless otherwise stated. // description. All applications are assumed to support 9.1 unless otherwise stated.
D3D_FEATURE_LEVEL featureLevels[] = D3D_FEATURE_LEVEL featureLevels[] =
{ {
D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3 D3D_FEATURE_LEVEL_9_3
}; };
// Create the Direct3D 11 API device object and a corresponding context. // Create the Direct3D 11 API device object and a corresponding context.
ComPtr<ID3D11Device> device; ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context; ComPtr<ID3D11DeviceContext> context;
DX::ThrowIfFailed( DX::ThrowIfFailed(
D3D11CreateDevice( D3D11CreateDevice(
nullptr, // Specify nullptr to use the default adapter. nullptr, // Specify nullptr to use the default adapter.
D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_HARDWARE,
nullptr, nullptr,
creationFlags, // Set set debug and Direct2D compatibility flags. creationFlags, // Set set debug and Direct2D compatibility flags.
featureLevels, // List of feature levels this app can support. featureLevels, // List of feature levels this app can support.
ARRAYSIZE(featureLevels), ARRAYSIZE(featureLevels),
D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION. D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION.
&device, // Returns the Direct3D device created. &device, // Returns the Direct3D device created.
&m_featureLevel, // Returns feature level of device created. &m_featureLevel, // Returns feature level of device created.
&context // Returns the device immediate context. &context // Returns the device immediate context.
) )
); );
// Get the Direct3D 11.1 API device and context interfaces. // Get the Direct3D 11.1 API device and context interfaces.
DX::ThrowIfFailed( DX::ThrowIfFailed(
device.As(&m_d3dDevice) device.As(&m_d3dDevice)
); );
DX::ThrowIfFailed( DX::ThrowIfFailed(
context.As(&m_d3dContext) context.As(&m_d3dContext)
); );
} }
// Allocate all memory resources that depend on the window size. // Allocate all memory resources that depend on the window size.
void Direct3DBase::CreateWindowSizeDependentResources() void Direct3DBase::CreateWindowSizeDependentResources()
{ {
// Create a descriptor for the render target buffer. // Create a descriptor for the render target buffer.
CD3D11_TEXTURE2D_DESC renderTargetDesc( CD3D11_TEXTURE2D_DESC renderTargetDesc(
DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM,
static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Width),
static_cast<UINT>(m_renderTargetSize.Height), static_cast<UINT>(m_renderTargetSize.Height),
1, 1,
1, 1,
D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE
); );
renderTargetDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX | D3D11_RESOURCE_MISC_SHARED_NTHANDLE; renderTargetDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX | D3D11_RESOURCE_MISC_SHARED_NTHANDLE;
// Allocate a 2-D surface as the render target buffer. // Allocate a 2-D surface as the render target buffer.
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateTexture2D( m_d3dDevice->CreateTexture2D(
&renderTargetDesc, &renderTargetDesc,
nullptr, nullptr,
&m_renderTarget &m_renderTarget
) )
); );
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateRenderTargetView( m_d3dDevice->CreateRenderTargetView(
m_renderTarget.Get(), m_renderTarget.Get(),
nullptr, nullptr,
&m_renderTargetView &m_renderTargetView
) )
); );
// Create a depth stencil view. // Create a depth stencil view.
CD3D11_TEXTURE2D_DESC depthStencilDesc( CD3D11_TEXTURE2D_DESC depthStencilDesc(
DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_D24_UNORM_S8_UINT,
static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Width),
static_cast<UINT>(m_renderTargetSize.Height), static_cast<UINT>(m_renderTargetSize.Height),
1, 1,
1, 1,
D3D11_BIND_DEPTH_STENCIL D3D11_BIND_DEPTH_STENCIL
); );
ComPtr<ID3D11Texture2D> depthStencil; ComPtr<ID3D11Texture2D> depthStencil;
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateTexture2D( m_d3dDevice->CreateTexture2D(
&depthStencilDesc, &depthStencilDesc,
nullptr, nullptr,
&depthStencil &depthStencil
) )
); );
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D); CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
DX::ThrowIfFailed( DX::ThrowIfFailed(
m_d3dDevice->CreateDepthStencilView( m_d3dDevice->CreateDepthStencilView(
depthStencil.Get(), depthStencil.Get(),
&depthStencilViewDesc, &depthStencilViewDesc,
&m_depthStencilView &m_depthStencilView
) )
); );
// Set the rendering viewport to target the entire window. // Set the rendering viewport to target the entire window.
CD3D11_VIEWPORT viewport( CD3D11_VIEWPORT viewport(
0.0f, 0.0f,
0.0f, 0.0f,
m_renderTargetSize.Width, m_renderTargetSize.Width,
m_renderTargetSize.Height m_renderTargetSize.Height
); );
m_d3dContext->RSSetViewports(1, &viewport); m_d3dContext->RSSetViewports(1, &viewport);
} }
void Direct3DBase::UpdateForRenderResolutionChange(float width, float height) void Direct3DBase::UpdateForRenderResolutionChange(float width, float height)
{ {
m_renderTargetSize.Width = width; m_renderTargetSize.Width = width;
m_renderTargetSize.Height = height; m_renderTargetSize.Height = height;
ID3D11RenderTargetView* nullViews[] = {nullptr}; ID3D11RenderTargetView* nullViews[] = {nullptr};
m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr); m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
m_renderTarget = nullptr; m_renderTarget = nullptr;
m_renderTargetView = nullptr; m_renderTargetView = nullptr;
m_depthStencilView = nullptr; m_depthStencilView = nullptr;
m_d3dContext->Flush(); m_d3dContext->Flush();
CreateWindowSizeDependentResources(); CreateWindowSizeDependentResources();
} }
void Direct3DBase::UpdateForWindowSizeChange(float width, float height) void Direct3DBase::UpdateForWindowSizeChange(float width, float height)
{ {
m_windowBounds.Width = width; m_windowBounds.Width = width;
m_windowBounds.Height = height; m_windowBounds.Height = height;
} }

@ -6,32 +6,32 @@
ref class Direct3DBase abstract ref class Direct3DBase abstract
{ {
internal: internal:
Direct3DBase(); Direct3DBase();
public: public:
virtual void Initialize(); virtual void Initialize();
virtual void CreateDeviceResources(); virtual void CreateDeviceResources();
virtual void CreateWindowSizeDependentResources(); virtual void CreateWindowSizeDependentResources();
virtual void UpdateForRenderResolutionChange(float width, float height); virtual void UpdateForRenderResolutionChange(float width, float height);
virtual void UpdateForWindowSizeChange(float width, float height); virtual void UpdateForWindowSizeChange(float width, float height);
virtual void Render() = 0; virtual void Render() = 0;
internal: internal:
virtual ID3D11Texture2D* GetTexture() virtual ID3D11Texture2D* GetTexture()
{ {
return m_renderTarget.Get(); return m_renderTarget.Get();
} }
protected private: protected private:
// Direct3D Objects. // Direct3D Objects.
Microsoft::WRL::ComPtr<ID3D11Device1> m_d3dDevice; Microsoft::WRL::ComPtr<ID3D11Device1> m_d3dDevice;
Microsoft::WRL::ComPtr<ID3D11DeviceContext1> m_d3dContext; Microsoft::WRL::ComPtr<ID3D11DeviceContext1> m_d3dContext;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_renderTarget; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_renderTarget;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_renderTargetView; Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_renderTargetView;
Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_depthStencilView; Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_depthStencilView;
// Cached renderer properties. // Cached renderer properties.
D3D_FEATURE_LEVEL m_featureLevel; D3D_FEATURE_LEVEL m_featureLevel;
Windows::Foundation::Size m_renderTargetSize; Windows::Foundation::Size m_renderTargetSize;
Windows::Foundation::Rect m_windowBounds; Windows::Foundation::Rect m_windowBounds;
}; };

@ -4,74 +4,74 @@
using namespace PhoneXamlDirect3DApp1Comp; using namespace PhoneXamlDirect3DApp1Comp;
Direct3DContentProvider::Direct3DContentProvider(Direct3DInterop^ controller) : Direct3DContentProvider::Direct3DContentProvider(Direct3DInterop^ controller) :
m_controller(controller) m_controller(controller)
{ {
m_controller->RequestAdditionalFrame += ref new RequestAdditionalFrameHandler([=] () m_controller->RequestAdditionalFrame += ref new RequestAdditionalFrameHandler([=] ()
{ {
if (m_host) if (m_host)
{ {
m_host->RequestAdditionalFrame(); m_host->RequestAdditionalFrame();
} }
}); });
m_controller->RecreateSynchronizedTexture += ref new RecreateSynchronizedTextureHandler([=] () m_controller->RecreateSynchronizedTexture += ref new RecreateSynchronizedTextureHandler([=] ()
{ {
if (m_host) if (m_host)
{ {
m_host->CreateSynchronizedTexture(m_controller->GetTexture(), &m_synchronizedTexture); m_host->CreateSynchronizedTexture(m_controller->GetTexture(), &m_synchronizedTexture);
} }
}); });
} }
// IDrawingSurfaceContentProviderNative interface // IDrawingSurfaceContentProviderNative interface
HRESULT Direct3DContentProvider::Connect(_In_ IDrawingSurfaceRuntimeHostNative* host) HRESULT Direct3DContentProvider::Connect(_In_ IDrawingSurfaceRuntimeHostNative* host)
{ {
m_host = host; m_host = host;
return m_controller->Connect(host); return m_controller->Connect(host);
} }
void Direct3DContentProvider::Disconnect() void Direct3DContentProvider::Disconnect()
{ {
m_controller->Disconnect(); m_controller->Disconnect();
m_host = nullptr; m_host = nullptr;
m_synchronizedTexture = nullptr; m_synchronizedTexture = nullptr;
} }
HRESULT Direct3DContentProvider::PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty) HRESULT Direct3DContentProvider::PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty)
{ {
return m_controller->PrepareResources(presentTargetTime, contentDirty); return m_controller->PrepareResources(presentTargetTime, contentDirty);
} }
HRESULT Direct3DContentProvider::GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle) HRESULT Direct3DContentProvider::GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle)
{ {
HRESULT hr = S_OK; HRESULT hr = S_OK;
if (!m_synchronizedTexture)
{
hr = m_host->CreateSynchronizedTexture(m_controller->GetTexture(), &m_synchronizedTexture);
}
if (!m_synchronizedTexture) // Set output parameters.
{ textureSubRectangle->left = 0.0f;
hr = m_host->CreateSynchronizedTexture(m_controller->GetTexture(), &m_synchronizedTexture); textureSubRectangle->top = 0.0f;
} textureSubRectangle->right = static_cast<FLOAT>(size->width);
textureSubRectangle->bottom = static_cast<FLOAT>(size->height);
// Set output parameters. m_synchronizedTexture.CopyTo(synchronizedTexture);
textureSubRectangle->left = 0.0f;
textureSubRectangle->top = 0.0f;
textureSubRectangle->right = static_cast<FLOAT>(size->width);
textureSubRectangle->bottom = static_cast<FLOAT>(size->height);
m_synchronizedTexture.CopyTo(synchronizedTexture); // Draw to the texture.
if (SUCCEEDED(hr))
{
hr = m_synchronizedTexture->BeginDraw();
// Draw to the texture. if (SUCCEEDED(hr))
if (SUCCEEDED(hr)) {
{ hr = m_controller->GetTexture(size, synchronizedTexture, textureSubRectangle);
hr = m_synchronizedTexture->BeginDraw(); }
if (SUCCEEDED(hr))
{
hr = m_controller->GetTexture(size, synchronizedTexture, textureSubRectangle);
}
m_synchronizedTexture->EndDraw(); m_synchronizedTexture->EndDraw();
} }
return hr; return hr;
} }

@ -8,26 +8,26 @@
#include "Direct3DInterop.h" #include "Direct3DInterop.h"
class Direct3DContentProvider : public Microsoft::WRL::RuntimeClass< class Direct3DContentProvider : public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix>, Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix>,
ABI::Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider, ABI::Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider,
IDrawingSurfaceContentProviderNative> IDrawingSurfaceContentProviderNative>
{ {
public: public:
Direct3DContentProvider(PhoneXamlDirect3DApp1Comp::Direct3DInterop^ controller); Direct3DContentProvider(PhoneXamlDirect3DApp1Comp::Direct3DInterop^ controller);
void ReleaseD3DResources(); void ReleaseD3DResources();
// IDrawingSurfaceContentProviderNative // IDrawingSurfaceContentProviderNative
HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host); HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host);
void STDMETHODCALLTYPE Disconnect(); void STDMETHODCALLTYPE Disconnect();
HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty); HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty);
HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle); HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle);
private: private:
HRESULT InitializeTexture(_In_ const DrawingSurfaceSizeF* size); HRESULT InitializeTexture(_In_ const DrawingSurfaceSizeF* size);
PhoneXamlDirect3DApp1Comp::Direct3DInterop^ m_controller; PhoneXamlDirect3DApp1Comp::Direct3DInterop^ m_controller;
Microsoft::WRL::ComPtr<IDrawingSurfaceRuntimeHostNative> m_host; Microsoft::WRL::ComPtr<IDrawingSurfaceRuntimeHostNative> m_host;
Microsoft::WRL::ComPtr<IDrawingSurfaceSynchronizedTextureNative> m_synchronizedTexture; Microsoft::WRL::ComPtr<IDrawingSurfaceSynchronizedTextureNative> m_synchronizedTexture;
}; };

@ -16,33 +16,33 @@ using namespace Windows::Phone::Input::Interop;
namespace PhoneXamlDirect3DApp1Comp namespace PhoneXamlDirect3DApp1Comp
{ {
void Direct3DInterop::ApplyGrayFilter(const cv::Mat& image) void Direct3DInterop::ApplyGrayFilter(const cv::Mat& image)
{ {
cv::Mat intermediateMat; cv::Mat intermediateMat;
cv::cvtColor(image, intermediateMat, CV_RGBA2GRAY); cv::cvtColor(image, intermediateMat, CV_RGBA2GRAY);
cv::cvtColor(intermediateMat, image, CV_GRAY2BGRA); cv::cvtColor(intermediateMat, image, CV_GRAY2BGRA);
} }
void Direct3DInterop::ApplyCannyFilter(const cv::Mat& image) void Direct3DInterop::ApplyCannyFilter(const cv::Mat& image)
{ {
cv::Mat intermediateMat; cv::Mat intermediateMat;
cv::Canny(image, intermediateMat, 80, 90); cv::Canny(image, intermediateMat, 80, 90);
cv::cvtColor(intermediateMat, image, CV_GRAY2BGRA); cv::cvtColor(intermediateMat, image, CV_GRAY2BGRA);
} }
void Direct3DInterop::ApplySepiaFilter(const cv::Mat& image) void Direct3DInterop::ApplySepiaFilter(const cv::Mat& image)
{ {
const float SepiaKernelData[16] = const float SepiaKernelData[16] =
{ {
/* B */0.131f, 0.534f, 0.272f, 0.f, /* B */0.131f, 0.534f, 0.272f, 0.f,
/* G */0.168f, 0.686f, 0.349f, 0.f, /* G */0.168f, 0.686f, 0.349f, 0.f,
/* R */0.189f, 0.769f, 0.393f, 0.f, /* R */0.189f, 0.769f, 0.393f, 0.f,
/* A */0.000f, 0.000f, 0.000f, 1.f /* A */0.000f, 0.000f, 0.000f, 1.f
}; };
const cv::Mat SepiaKernel(4, 4, CV_32FC1, (void*)SepiaKernelData); const cv::Mat SepiaKernel(4, 4, CV_32FC1, (void*)SepiaKernelData);
cv::transform(image, image, SepiaKernel); cv::transform(image, image, SepiaKernel);
} }
Direct3DInterop::Direct3DInterop() : Direct3DInterop::Direct3DInterop() :
m_timer(ref new BasicTimer()) m_timer(ref new BasicTimer())
@ -144,31 +144,31 @@ namespace PhoneXamlDirect3DApp1Comp
void Direct3DInterop::CreateTexture(const Platform::Array<int>^ buffer,int width,int height, OCVFilterType filter) void Direct3DInterop::CreateTexture(const Platform::Array<int>^ buffer,int width,int height, OCVFilterType filter)
{ {
if (m_renderer) if (m_renderer)
{ {
cv::Mat Lena = cv::Mat(height, width, CV_8UC4); cv::Mat Lena = cv::Mat(height, width, CV_8UC4);
memcpy(Lena.data, buffer->Data, 4 * height*width); memcpy(Lena.data, buffer->Data, 4 * height*width);
switch (filter) switch (filter)
{ {
case OCVFilterType::ePreview: case OCVFilterType::ePreview:
break; break;
case OCVFilterType::eGray: case OCVFilterType::eGray:
ApplyGrayFilter(Lena); ApplyGrayFilter(Lena);
break; break;
case OCVFilterType::eCanny: case OCVFilterType::eCanny:
ApplyCannyFilter(Lena); ApplyCannyFilter(Lena);
break; break;
case OCVFilterType::eSepia: case OCVFilterType::eSepia:
ApplySepiaFilter(Lena); ApplySepiaFilter(Lena);
break; break;
} }
m_renderer->CreateTextureFromByte(Lena.data, width, height); m_renderer->CreateTextureFromByte(Lena.data, width, height);
} }
} }
byte* GetPointerToPixelData( Windows::Storage::Streams::IBuffer ^ pixelBuffer) byte* GetPointerToPixelData( Windows::Storage::Streams::IBuffer ^ pixelBuffer)

@ -15,11 +15,11 @@ namespace PhoneXamlDirect3DApp1Comp
public enum class OCVFilterType public enum class OCVFilterType
{ {
ePreview, ePreview,
eGray, eGray,
eCanny, eCanny,
eSepia, eSepia,
eNumOCVFilterTypes eNumOCVFilterTypes
}; };
public delegate void RequestAdditionalFrameHandler(); public delegate void RequestAdditionalFrameHandler();
@ -29,52 +29,52 @@ public delegate void RecreateSynchronizedTextureHandler();
public ref class Direct3DInterop sealed : public Windows::Phone::Input::Interop::IDrawingSurfaceManipulationHandler public ref class Direct3DInterop sealed : public Windows::Phone::Input::Interop::IDrawingSurfaceManipulationHandler
{ {
public: public:
Direct3DInterop(); Direct3DInterop();
Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider^ CreateContentProvider(); Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider^ CreateContentProvider();
// IDrawingSurfaceManipulationHandler // IDrawingSurfaceManipulationHandler
virtual void SetManipulationHost(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ manipulationHost); virtual void SetManipulationHost(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ manipulationHost);
event RequestAdditionalFrameHandler^ RequestAdditionalFrame; event RequestAdditionalFrameHandler^ RequestAdditionalFrame;
event RecreateSynchronizedTextureHandler^ RecreateSynchronizedTexture; event RecreateSynchronizedTextureHandler^ RecreateSynchronizedTexture;
property Windows::Foundation::Size WindowBounds; property Windows::Foundation::Size WindowBounds;
property Windows::Foundation::Size NativeResolution; property Windows::Foundation::Size NativeResolution;
property Windows::Foundation::Size RenderResolution property Windows::Foundation::Size RenderResolution
{ {
Windows::Foundation::Size get(){ return m_renderResolution; } Windows::Foundation::Size get(){ return m_renderResolution; }
void set(Windows::Foundation::Size renderResolution); void set(Windows::Foundation::Size renderResolution);
} }
void CreateTexture(const Platform::Array<int>^ buffer, int with, int height, OCVFilterType filter); void CreateTexture(const Platform::Array<int>^ buffer, int with, int height, OCVFilterType filter);
protected: protected:
// Event Handlers // Event Handlers
void OnPointerPressed(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerPressed(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args);
void OnPointerMoved(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerMoved(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args);
void OnPointerReleased(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerReleased(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args);
internal: internal:
HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host); HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host);
void STDMETHODCALLTYPE Disconnect(); void STDMETHODCALLTYPE Disconnect();
HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty); HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty);
HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle); HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle);
ID3D11Texture2D* GetTexture(); ID3D11Texture2D* GetTexture();
private: private:
CubeRenderer^ m_renderer; CubeRenderer^ m_renderer;
BasicTimer^ m_timer; BasicTimer^ m_timer;
Windows::Foundation::Size m_renderResolution; Windows::Foundation::Size m_renderResolution;
void ApplyGrayFilter(const cv::Mat& image); void ApplyGrayFilter(const cv::Mat& image);
void ApplyCannyFilter(const cv::Mat& image); void ApplyCannyFilter(const cv::Mat& image);
void ApplySepiaFilter(const cv::Mat& image); void ApplySepiaFilter(const cv::Mat& image);
void UpdateImage(const cv::Mat& image); void UpdateImage(const cv::Mat& image);
cv::Mat Lena; cv::Mat Lena;
unsigned int frameWidth, frameHeight; unsigned int frameWidth, frameHeight;
}; };
} }

@ -6,36 +6,36 @@
namespace DX namespace DX
{ {
inline void ThrowIfFailed(HRESULT hr) inline void ThrowIfFailed(HRESULT hr)
{ {
if (FAILED(hr)) if (FAILED(hr))
{ {
// Set a breakpoint on this line to catch Win32 API errors. // Set a breakpoint on this line to catch Win32 API errors.
throw Platform::Exception::CreateException(hr); throw Platform::Exception::CreateException(hr);
} }
} }
// Function that reads from a binary file asynchronously. // Function that reads from a binary file asynchronously.
inline Concurrency::task<Platform::Array<byte>^> ReadDataAsync(Platform::String^ filename) inline Concurrency::task<Platform::Array<byte>^> ReadDataAsync(Platform::String^ filename)
{ {
using namespace Windows::Storage; using namespace Windows::Storage;
using namespace Concurrency; using namespace Concurrency;
auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation; auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
return create_task(folder->GetFileAsync(filename)).then([] (StorageFile^ file) return create_task(folder->GetFileAsync(filename)).then([] (StorageFile^ file)
{ {
return file->OpenReadAsync(); return file->OpenReadAsync();
}).then([] (Streams::IRandomAccessStreamWithContentType^ stream) }).then([] (Streams::IRandomAccessStreamWithContentType^ stream)
{ {
unsigned int bufferSize = static_cast<unsigned int>(stream->Size); unsigned int bufferSize = static_cast<unsigned int>(stream->Size);
auto fileBuffer = ref new Streams::Buffer(bufferSize); auto fileBuffer = ref new Streams::Buffer(bufferSize);
return stream->ReadAsync(fileBuffer, bufferSize, Streams::InputStreamOptions::None); return stream->ReadAsync(fileBuffer, bufferSize, Streams::InputStreamOptions::None);
}).then([] (Streams::IBuffer^ fileBuffer) -> Platform::Array<byte>^ }).then([] (Streams::IBuffer^ fileBuffer) -> Platform::Array<byte>^
{ {
auto fileData = ref new Platform::Array<byte>(fileBuffer->Length); auto fileData = ref new Platform::Array<byte>(fileBuffer->Length);
Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(fileData); Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(fileData);
return fileData; return fileData;
}); });
} }
} }

@ -1,8 +1,8 @@
cbuffer ModelViewProjectionConstantBuffer : register(b0) cbuffer ModelViewProjectionConstantBuffer : register(b0)
{ {
matrix model; matrix model;
matrix view; matrix view;
matrix projection; matrix projection;
}; };
struct VertexInputType struct VertexInputType
@ -34,6 +34,6 @@ PixelInputType main(VertexInputType input)
output.position = mul(output.position, projection); output.position = mul(output.position, projection);
// Store the texture coordinates for the pixel shader. // Store the texture coordinates for the pixel shader.
output.tex = input.tex; output.tex = input.tex;
return output; return output;
} }

@ -64,6 +64,4 @@ void CopyMatrixToVector(const cv::Mat& mat, std::vector<int>& vector, int size)
vector.push_back(data[i]); vector.push_back(data[i]);
} }
} }

@ -31,7 +31,7 @@ namespace OpenCVXaml
if (Preview.Source != null) if (Preview.Source != null)
{ {
ProcessButton.IsEnabled = false; ProcessButton.IsEnabled = false;
// Get WriteableBitmap. ImageToModify is defined in MainPage.xaml // Get WriteableBitmap. ImageToModify is defined in MainPage.xaml
WriteableBitmap bitmap = new WriteableBitmap(Preview.Source as BitmapSource); WriteableBitmap bitmap = new WriteableBitmap(Preview.Source as BitmapSource);

@ -3,7 +3,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Resources; using System.Resources;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("OpenCVXaml")] [assembly: AssemblyTitle("OpenCVXaml")]
@ -15,8 +15,8 @@ using System.Resources;
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible // Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from // to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. // COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
@ -26,11 +26,11 @@ using System.Resources;
// Version information for an assembly consists of the following four values: // Version information for an assembly consists of the following four values:
// //
// Major Version // Major Version
// Minor Version // Minor Version
// Build Number // Build Number
// Revision // Revision
// //
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]

@ -1,6 +1,6 @@
Building OpenCV Windows Phone Samples Building OpenCV Windows Phone Samples
===================================== =====================================
Samples are created to run against x86 architecture OpenCV binaries. Samples are created to run against x86 architecture OpenCV binaries.
Please follow the instructions in "platforms/winrt/readme.txt" to generate and build OpenCV for Windows Phone 8.0/8.1 Please follow the instructions in "platforms/winrt/readme.txt" to generate and build OpenCV for Windows Phone 8.0/8.1
Loading…
Cancel
Save