blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
3d05c2d32fdc6a0edad06f8e5bdfaaed616eaefd
123272544064bf8ce2173eb5284f11cfc70f7d56
/include/postprocessors/OneDTimeStepCFL.h
7a5a612a5d9d9153c1fce1b8bea197e4dc598a35
[]
no_license
delcmo/eel2d
1aa6eb097ac8e5e983d16445cbf8990f8cf4cd05
a47400e05dc97653f7c2b42f1c32a8223e07bc4a
refs/heads/master
2021-01-21T04:20:00.216736
2016-07-28T17:21:40
2016-07-28T17:21:40
17,618,806
0
1
null
null
null
null
UTF-8
C++
false
false
731
h
#ifndef ONEDTIMESTEPCFL_H #define ONEDTIMESTEPCFL_H #include "ElementPostprocessor.h" #include "OnedEquationOfState.h" class OneDTimeStepCFL; template<> InputParameters validParams<OneDTimeStepCFL>(); class OneDTimeStepCFL : public ElementPostprocessor { public: OneDTimeStepCFL(const InputParameters & parameters); virtual ~OneDTimeStepCFL(); virtual void initialize(); virtual void execute(); virtual Real getValue(); virtual void threadJoin(const UserObject & uo); protected: const VariableValue & _rhoA; const VariableValue & _rhouA; const VariableValue & _rhoEA; const VariableValue & _area; const OneDEquationOfState & _eos; const Real & _cfl; Real _value; }; #endif // ONEDTIMESTEPCFL_H
[ "mxd@ornl.gov" ]
mxd@ornl.gov
ba1e0379e3a460268d4834761c069b32477cbb94
64719c6161762bb753853117f17e6b6ec2f51107
/TestStand/Examples/TestStand Debugging Features/Benchmarks/ActiveX/Class.h
49732991df8da705940e4f9ae6b276a016eedda8
[]
no_license
dmnhwjin/ni-training-july-2016
aba9eb20b976f86eb1b51ee9316350cb5402bb7b
2db946b3f01366af74b867de2b645b68b92d403e
refs/heads/master
2021-01-12T06:35:21.829617
2016-08-01T12:23:01
2016-08-01T12:23:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,203
h
// Class.h: Definition of the CClass class // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_CLASS_H__765D7274_7FA6_11D2_9CE9_00A024767F0A__INCLUDED_) #define AFX_CLASS_H__765D7274_7FA6_11D2_9CE9_00A024767F0A__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CClass class CClass : public CComDualImpl<IClass, &IID_IClass, &LIBID_BENCHMARKLib>, public ISupportErrorInfo, public CComObjectRoot, public CComCoClass<CClass,&CLSID_Class> { public: CClass() {} BEGIN_COM_MAP(CClass) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IClass) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() //DECLARE_NOT_AGGREGATABLE(CClass) // Remove the comment from the line above if you don't want your object to // support aggregation. DECLARE_REGISTRY_RESOURCEID(IDR_Class) // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // IClass public: STDMETHOD(DoNothing)(); }; #endif // !defined(AFX_CLASS_H__765D7274_7FA6_11D2_9CE9_00A024767F0A__INCLUDED_)
[ "afeique@gmail.com" ]
afeique@gmail.com
7e239bc061230e741785573d4ed8f5ef38881f80
e5d5fa28999bcc6c642bb42dda93afd38e272b81
/UVA/APOAPC_2nd/512 - Spreadsheet Tracking/solve1.cc
4429bb9eb7675bf7d4aa1d4be5f13e1c50fc0337
[]
no_license
chiahsun/problem_solving
cd3105969983d16d3d5d416d4a0d5797d4b58e91
559fafa92dd5516058bdcea82a438eadf5aa1ede
refs/heads/master
2023-02-05T06:11:27.536617
2023-01-26T10:51:23
2023-01-26T10:51:23
30,732,382
3
0
null
null
null
null
UTF-8
C++
false
false
3,432
cc
#include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> const bool debug = false; const int MAX = 50 + 3; int M[MAX][MAX]; int main() { int nrow, ncolumn; int posSpreadSheet = 1; while (scanf("%d%d", &nrow, &ncolumn) == 2 and nrow > 0 and ncolumn > 0) { if (posSpreadSheet != 1) { printf("\n"); } printf("Spreadsheet #%d\n", posSpreadSheet); ++posSpreadSheet; int ncmd; scanf("%d", &ncmd); getchar(); // read the newline std::vector<std::string> vecCmd; while (ncmd--) { std::string line; std::getline(std::cin, line); vecCmd.push_back(line); if (debug) std::cout << "cmd = " << line << std::endl; } int nquery; scanf("%d", &nquery); while (nquery--) { int posx, posy; scanf("%d%d", &posx, &posy); if (debug) std::cout << "cur pos = (" << posx << ", " << posy << ")" << std::endl; int oldx = posx, oldy = posy; bool vanish = false; std::stringstream ss; for (int i = 0; i < vecCmd.size(); ++i) { ss.clear(); ss << vecCmd[i]; std::string curCmd; ss >> curCmd; std::string numLabel; if (curCmd != "EX") ss >> numLabel; // no use of number of label in command if (debug) std::cout << "Cur cmd : " << curCmd << std::endl; int x; if (curCmd == "DR") { int ndelete = 0; while (ss >> x) { if (x < posx) ++ndelete; else if (x == posx) { vanish = true; break; } } posx -= ndelete; } else if (curCmd == "DC") { int ndelete = 0; while (ss >> x) { if (x < posy) ++ndelete; else if (x == posy) { vanish = true; break; } } posy -= ndelete; } else if (curCmd == "IR") { int nadd = 0; while (ss >> x) { if (x <= posx) ++nadd; } posx += nadd; } else if (curCmd == "IC") { int nadd = 0; while (ss >> x) { if (x <= posy) ++nadd; } posy += nadd; } else if (curCmd == "EX") { int x1, y1, x2, y2; ss >> x1 >> y1 >> x2 >> y2; if (x1 == posx && y1 == posy) { posx = x2; posy = y2; } else if (x2 == posx && y2 == posy) { posx = x1; posy = y1; } } if (debug) std::cout << "Update to (" << posx << ", " << posy << ")" << std::endl; if (vanish) break; } if (vanish) { printf("Cell data in (%d,%d) GONE\n", oldx, oldy); } else { printf("Cell data in (%d,%d) moved to (%d,%d)\n", oldx, oldy, posx, posy); } } } return 0; }
[ "chiahsun0814@gmail.com" ]
chiahsun0814@gmail.com
e386cf890ee536b77ff339d5c3797f102c65ae22
d8614b7a8ef7b69ef1b778a584d8d5f6efd15272
/lite/api/paddle_place.cc
ccacb027d682b5388e44b05075b66f436c3e2668
[ "Apache-2.0" ]
permissive
hcj5206/Paddle-Lite
101084b4a255a8d02036de8129a9fcaf9d2cd278
eed7a506cef5d2ba6a076a34e4f51d3b5f60cddd
refs/heads/develop
2020-08-29T09:14:53.560933
2019-10-28T06:44:34
2019-10-28T06:44:34
217,991,085
0
0
Apache-2.0
2019-11-06T03:59:40
2019-10-28T07:40:57
null
UTF-8
C++
false
false
5,044
cc
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/api/paddle_place.h" #include "lite/utils/cp_logging.h" #include "lite/utils/hash.h" #include "lite/utils/replace_stl/stream.h" #include "lite/utils/string.h" namespace paddle { namespace lite_api { size_t Place::hash() const { std::hash<int> h; size_t hash = h(static_cast<int>(target)); hash = lite::hash_combine(hash, static_cast<int>(precision)); hash = lite::hash_combine(hash, static_cast<int>(layout)); hash = lite::hash_combine(hash, static_cast<int>(device)); return hash; } bool operator<(const Place& a, const Place& b) { if (a.target != b.target) return a.target < b.target; if (a.precision != b.precision) return a.precision < b.precision; if (a.layout != b.layout) return a.layout < b.layout; if (a.device != b.device) return a.device < b.device; return false; } std::string Place::DebugString() const { STL::stringstream os; os << TargetToStr(target) << "/" << PrecisionToStr(precision) << "/" << DataLayoutToStr(layout); return os.str(); } const std::string& TargetToStr(TargetType target) { static const std::string target2string[] = {"unk", "host", "x86", "cuda", "arm", "opencl", "any", "fpga", "npu", "xpu"}; auto x = static_cast<int>(target); CHECK_LT(x, static_cast<int>(TARGET(NUM))); return target2string[x]; } const std::string& PrecisionToStr(PrecisionType precision) { static const std::string precision2string[] = {"unk", "float", "int8_t", "int32_t", "any", "float16", "bool", "int64_t", "int16_t"}; auto x = static_cast<int>(precision); CHECK_LT(x, static_cast<int>(PRECISION(NUM))); return precision2string[x]; } const std::string& DataLayoutToStr(DataLayoutType layout) { static const std::string datalayout2string[] = {"unk", "NCHW", "any", "NHWC"}; auto x = static_cast<int>(layout); CHECK_LT(x, static_cast<int>(DATALAYOUT(NUM))); return datalayout2string[x]; } const std::string& TargetRepr(TargetType target) { static const std::string target2string[] = {"kUnk", "kHost", "kX86", "kCUDA", "kARM", "kOpenCL", "kAny", "kFPGA", "kNPU", "kXPU"}; auto x = static_cast<int>(target); CHECK_LT(x, static_cast<int>(TARGET(NUM))); return target2string[x]; } const std::string& PrecisionRepr(PrecisionType precision) { static const std::string precision2string[] = {"kUnk", "kFloat", "kInt8", "kInt32", "kAny", "kFP16", "kBool", "kInt64", "kInt16"}; auto x = static_cast<int>(precision); CHECK_LT(x, static_cast<int>(PRECISION(NUM))); return precision2string[x]; } const std::string& DataLayoutRepr(DataLayoutType layout) { static const std::string datalayout2string[] = { "kUnk", "kNCHW", "kAny", "kNHWC"}; auto x = static_cast<int>(layout); CHECK_LT(x, static_cast<int>(DATALAYOUT(NUM))); return datalayout2string[x]; } } // namespace lite_api } // namespace paddle
[ "noreply@github.com" ]
noreply@github.com
3329e1ec24850d5a53aa77f1a4f1292e69c53572
9ca40cc9cf848aba3e998f0342cd4ba29c20c0f3
/1544/seungwoo.cpp
84c2121a48a4e656949cde1627a9211b14dd594a
[]
no_license
SWTube/BAEKJOON
68db54310886bec10d6fdf7c615bffb4dee89bbc
bccf404fa1dd7add8f4f02dbfd260ddbf148137a
refs/heads/main
2023-03-14T07:32:02.241634
2021-03-18T08:28:20
2021-03-18T08:28:20
331,839,474
3
5
null
2021-02-09T15:46:02
2021-01-22T04:48:42
C++
UTF-8
C++
false
false
1,035
cpp
#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <string> std::string makeString(std::queue<char>& q) { std::string str = ""; for (int i = 0; i < q.size(); i++) { str += q.front(); q.push(q.front()); q.pop(); } return str; } int main() { std::ios::sync_with_stdio(false); std::cout.tie(NULL); std::cin.tie(NULL); int N; std::cin >> N; std::vector<std::string> v; for (int i = 0; i < N; i++) { std::string s; std::cin >> s; if (v.size() == 0) { v.push_back(s); } else { std::queue<char> q; for (int k = 0; k < s.size(); k++) { q.push(s[k]); } bool issame = false; for (int j = 0; j < v.size(); j++) { for (int k = 0; k < s.size(); k++) { std::string compstr = makeString(q); if (compstr == v[j]) { issame = true; break; } q.push(q.front()); q.pop(); } if (issame) { break; } } if (!issame) { v.push_back(s); } } } std::cout << v.size() << "\n"; return 0; }
[ "64199550+SW0000J@users.noreply.github.com" ]
64199550+SW0000J@users.noreply.github.com
ace242c7cc97c5b421e5f3177b0d6cd979d9ad65
e1d6417b995823e507a1e53ff81504e4bc795c8f
/gbk/server/Server/Server/Skills/ImpactLogic/StdImpact038.cpp
18057ba37acefb95f1dece0b9b0acca131c22818
[]
no_license
cjmxp/pap_full
f05d9e3f9390c2820a1e51d9ad4b38fe044e05a6
1963a8a7bda5156a772ccb3c3e35219a644a1566
refs/heads/master
2020-12-02T22:50:41.786682
2013-11-15T08:02:30
2013-11-15T08:02:30
null
0
0
null
null
null
null
GB18030
C++
false
false
500
cpp
/////////////////////////////////////////////////////////////////////////////// // 文件名:StdImpact038.cpp // 程序员:高骐 // 功能说明:效果--只显示特效用, 不需要具体的实现,只要一个逻辑空壳 // // 修改记录: // // // /////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "StdImpact038.h" namespace Combat_Module { using namespace Combat_Module::Skill_Module; namespace Impact_Module { }; };
[ "viticm@126.com" ]
viticm@126.com
6a18074db21575605712aa03fb4de6c93a3dcdd8
c87095bd13b9080224324b3a6dd4fd538912d97e
/Direct3D/Fog/d3d_obj.h
4242c685d79e946a017846f4809ddb7a5f691bd7
[ "MIT" ]
permissive
Agrelimos/tutorials
6a0a8ef6652a44bd5a35b59bf192326c831367ff
7d2953b8fbb5c56a921a17e7e3cac3d1f4fbb41b
refs/heads/master
2020-04-01T05:26:56.560609
2018-10-13T18:45:56
2018-10-13T18:45:56
152,903,588
0
0
MIT
2018-10-13T18:44:42
2018-10-13T18:44:42
null
UTF-8
C++
false
false
5,853
h
#ifndef D3D_OBJ_H #define D3D_OBJ_H #include <d3d9.h> #include <d3dx9.h> #include <d3dx9math.h> #include <assert.h> #include "vertex_types.h" #include "camera.h" // Our 3D Object that allows for rendering and setting // projection, view, and world matrices class CD3DObj { public: CD3DObj() { /* do nothing */ } // Constructor static bool init(HWND hwnd); // Initializes our 3D Object static void begin(); // Begins a scene static void end(); // Ends a scene // Sets all rendering states such as z-buffering, culling, etc // to a default state static void setDefaultRenderState(); // Fog methods -- Return true on success, false otherwise static bool setFogColor(DWORD color); static bool setPixelFogMode(D3DFOGMODE mode); static bool setVertexFogMode(D3DFOGMODE mode); static bool setFogStart(float start); static bool setFogEnd(float end); static bool setFogDensity(float density); // Turns fog on or off static bool setFogActive(bool onOrOff); // Goes between windowed and full screen static bool toggleFullScreen(); // Renders a list of SVertex as triangles static bool render(SVertex *vertList, int numVerts); // Renders a indexed list of SVertex as triangles static bool render(SVertex *vertList, int numVerts, WORD *indexList, int numIndices); // Renders a list of SVertex as line segments static bool renderLine(SVertex *vertList, int numVerts); // Functions to set either the projection, view, or world matrix static void setProjMatrix(float fov, float aspectRatio, float nearClip, float farClip); static void setViewMatrix(const CPos &eye, const CPos &target); static void setViewMatrix(const CCamera *camera); static void setWorldMatrix(const D3DXMATRIX *matrix); // Clears the viewport color and z-buffer static bool clear(int color = D3DCOLOR_XRGB(0,0,0), float zDepth = 1.0f); static void deinit(); // Free up our 3D Object ~CD3DObj() { /* do nothing */ }; // Deconstuctor // This is our D3D interface used to create other D3D objects/interfaces. static IDirect3D9 *mInterface; // This is our D3D device which allows "direct" access to the graphics card // It is our main device for primitive rendering functionality static IDirect3DDevice9 *mDevice; private: static HRESULT mResult; // Used for error checking static bool mFullScreen; // True if we're full screen, false otherwise static HWND mHWND; // Copy of the window's hwnd // Perspective matrix parameters static float mFOV; // Field of view static float mNearClip; // Near clip plane static float mFarClip; // Far clip plane static float mAspectRatio; // Width / Height of viewable screen static bool createDevice(); // Creates the IDirect3DDevice9 static void setPresentationParams(D3DPRESENT_PARAMETERS &params); // Fills D3DPRESENT_PARAMETERS // We make the copy constructor and assignment operator private because // we do NOT want anyone accidentally making a copy of this class CD3DObj(const CD3DObj &obj) {} CD3DObj& operator =(CD3DObj &obj) { return *this; } }; // Here we define our global 3D object extern CD3DObj *g3D; #endif /*#ifndef D3D_OBJ_H #define D3D_OBJ_H #include <d3d9.h> #include <d3dx9.h> #include <d3dx9math.h> #include <d3d9caps.h> #include "vertex_types.h" #include "camera.h" const float kPi = 3.14159265f; const float kPiOver180 = kPi / 180.0f; #define DEG2RAD(x) (x * kPiOver180) // Converts degrees to radians // Creates an ARGB color #define ARGB(A, R, G, B) ( (int)((A & 0xFF) << 24 | \ (R & 0xFF) << 16 | \ (G & 0xFF) << 8 | \ (B & 0xFF)) ) // Gets the A, R, G, and B from an ARGB color #define GET_A(c) ((c >> 24) & 0xFF) #define GET_R(c) ((c >> 16) & 0xFF) #define GET_G(c) ((c >> 8) & 0xFF) #define GET_B(c) (c & 0xFF) const float kFOV = DEG2RAD(60); // Default Field Of View const float kNearClip = 1.0f; // Default Near Clip Plane const float kFarClip = 8192.0f; // Default Far Clip Plane // Here is our 3D Object to handle all of our 3D needs -- It will create our needed D3D interfaces // and allow us to render a list or vertices of a vertex type that we created class CD3DObj { public: CD3DObj(); // Constructor bool init(HWND hwnd); // Initializes our 3D Object void initToDefaultParams(); // Initializes all parameters to a default value void begin(); // Begins a scene void end(); // Ends a scene void setViewMatrix(const CCamera *camera); // Sets the view matrix based on "camera" void setProjMatrix(); // Sets the projection matrix void setWorldMatrix(int which, D3DXMATRIX *matrix); // Sets a world matrix // Fog methods -- Return true on success, false otherwise bool setFogStatus(bool onOrOff); bool setFogColor(int color); bool setPixelFogMode(D3DFOGMODE mode); bool setVertexFogMode(D3DFOGMODE mode); bool setFogStart(float start); bool setFogEnd(float end); bool setFogDensity(float density); // Renders the passed in vertex list using the passed in index list bool render(SVertex *vList, int vertCount, WORD *iList, int indexCount); // Clears the viewport's color and Z-buffer bool clear(int color = D3DCOLOR_XRGB(0,0,0), float zDepth = 1.0f); ~CD3DObj(); // Deconstructor private: // We'll use this to create other D3D objects/interfaces. IDirect3D9 *d3d_interface; // We'll use this for all our rendering needs IDirect3DDevice9 *d3d_device; float fov; // Field of view float aspect_ratio; // Aspect ratio float near_clip; // Near clip plane float far_clip; // Far clip plane HRESULT result; // Used for error checking // We make the copy constructor and assignment operator private because // we do NOT want anyone accidentally making a copy of this class CD3DObj(const CD3DObj &obj) {} CD3DObj& operator =(CD3DObj &obj) { return *this; } }; // Our global 3D object extern CD3DObj *g3D; #endif*/
[ "staff@gametutorials.com" ]
staff@gametutorials.com
e2535a111514e49ae7036e6992ea1290f6d8cacf
8567438779e6af0754620a25d379c348e4cd5a5d
/content/browser/renderer_host/media/media_devices_manager_unittest.cc
68b86e5a8a4ba8b6dfc10c8e7ab983638d9eb802
[ "BSD-3-Clause" ]
permissive
thngkaiyuan/chromium
c389ac4b50ccba28ee077cbf6115c41b547955ae
dab56a4a71f87f64ecc0044e97b4a8f247787a68
refs/heads/master
2022-11-10T02:50:29.326119
2017-04-08T12:28:57
2017-04-08T12:28:57
84,073,924
0
1
BSD-3-Clause
2022-10-25T19:47:15
2017-03-06T13:04:15
null
UTF-8
C++
false
false
24,032
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/media/media_devices_manager.h" #include <memory> #include <string> #include "base/bind.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "content/browser/renderer_host/media/video_capture_manager.h" #include "content/public/test/test_browser_thread_bundle.h" #include "media/audio/audio_device_name.h" #include "media/audio/fake_audio_log_factory.h" #include "media/audio/fake_audio_manager.h" #include "media/capture/video/fake_video_capture_device_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::SaveArg; namespace content { namespace { // Number of client enumerations to simulate on each test run. // This allows testing that a single call to low-level enumeration functions // is performed when cache is enabled, regardless of the number of client calls. const int kNumCalls = 3; // This class mocks the audio manager and overrides some methods to ensure that // we can run simulate device changes. class MockAudioManager : public media::FakeAudioManager { public: MockAudioManager() : FakeAudioManager(base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get(), &fake_audio_log_factory_), num_output_devices_(2), num_input_devices_(2) {} ~MockAudioManager() override {} MOCK_METHOD1(MockGetAudioInputDeviceNames, void(media::AudioDeviceNames*)); MOCK_METHOD1(MockGetAudioOutputDeviceNames, void(media::AudioDeviceNames*)); void GetAudioInputDeviceNames( media::AudioDeviceNames* device_names) override { DCHECK(device_names->empty()); for (size_t i = 0; i < num_input_devices_; i++) { device_names->push_back(media::AudioDeviceName( std::string("fake_device_name_") + base::SizeTToString(i), std::string("fake_device_id_") + base::SizeTToString(i))); } MockGetAudioInputDeviceNames(device_names); } void GetAudioOutputDeviceNames( media::AudioDeviceNames* device_names) override { DCHECK(device_names->empty()); for (size_t i = 0; i < num_output_devices_; i++) { device_names->push_back(media::AudioDeviceName( std::string("fake_device_name_") + base::SizeTToString(i), std::string("fake_device_id_") + base::SizeTToString(i))); } MockGetAudioOutputDeviceNames(device_names); } media::AudioParameters GetDefaultOutputStreamParameters() override { return media::AudioParameters(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, media::CHANNEL_LAYOUT_STEREO, 48000, 16, 128); } media::AudioParameters GetOutputStreamParameters( const std::string& device_id) override { return media::AudioParameters(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, media::CHANNEL_LAYOUT_STEREO, 48000, 16, 128); } void SetNumAudioOutputDevices(size_t num_devices) { num_output_devices_ = num_devices; } void SetNumAudioInputDevices(size_t num_devices) { num_input_devices_ = num_devices; } private: media::FakeAudioLogFactory fake_audio_log_factory_; size_t num_output_devices_; size_t num_input_devices_; DISALLOW_COPY_AND_ASSIGN(MockAudioManager); }; // This class mocks the video capture device factory and overrides some methods // to ensure that we can simulate device changes. class MockVideoCaptureDeviceFactory : public media::FakeVideoCaptureDeviceFactory { public: MockVideoCaptureDeviceFactory() {} ~MockVideoCaptureDeviceFactory() override {} MOCK_METHOD0(MockGetDeviceDescriptors, void()); void GetDeviceDescriptors( media::VideoCaptureDeviceDescriptors* device_descriptors) override { media::FakeVideoCaptureDeviceFactory::GetDeviceDescriptors( device_descriptors); MockGetDeviceDescriptors(); } }; class MockMediaDeviceChangeSubscriber : public MediaDeviceChangeSubscriber { public: MOCK_METHOD2(OnDevicesChanged, void(MediaDeviceType, const MediaDeviceInfoArray&)); }; } // namespace class MediaDevicesManagerTest : public ::testing::Test { public: MediaDevicesManagerTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), video_capture_device_factory_(nullptr) {} ~MediaDevicesManagerTest() override {} MOCK_METHOD1(MockCallback, void(const MediaDeviceEnumeration&)); void EnumerateCallback(base::RunLoop* run_loop, const MediaDeviceEnumeration& result) { MockCallback(result); run_loop->Quit(); } protected: void SetUp() override { audio_manager_.reset(new MockAudioManager()); video_capture_manager_ = new VideoCaptureManager( std::unique_ptr<media::VideoCaptureDeviceFactory>( new MockVideoCaptureDeviceFactory()), base::ThreadTaskRunnerHandle::Get()); video_capture_manager_->RegisterListener(nullptr); video_capture_device_factory_ = static_cast<MockVideoCaptureDeviceFactory*>( video_capture_manager_->video_capture_device_factory()); media_devices_manager_.reset(new MediaDevicesManager( audio_manager_.get(), video_capture_manager_, nullptr)); } void EnableCache(MediaDeviceType type) { media_devices_manager_->SetCachePolicy( type, MediaDevicesManager::CachePolicy::SYSTEM_MONITOR); } // Must outlive MediaDevicesManager as ~MediaDevicesManager() verifies it's // running on the IO thread. TestBrowserThreadBundle thread_bundle_; std::unique_ptr<MediaDevicesManager> media_devices_manager_; scoped_refptr<VideoCaptureManager> video_capture_manager_; MockVideoCaptureDeviceFactory* video_capture_device_factory_; std::unique_ptr<MockAudioManager, media::AudioManagerDeleter> audio_manager_; private: DISALLOW_COPY_AND_ASSIGN(MediaDevicesManagerTest); }; TEST_F(MediaDevicesManagerTest, EnumerateNoCacheAudioInput) { EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)) .Times(kNumCalls); EXPECT_CALL(*video_capture_device_factory_, MockGetDeviceDescriptors()) .Times(0); EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)).Times(0); EXPECT_CALL(*this, MockCallback(_)).Times(kNumCalls); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_INPUT] = true; for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); } } TEST_F(MediaDevicesManagerTest, EnumerateNoCacheVideoInput) { EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)).Times(0); EXPECT_CALL(*video_capture_device_factory_, MockGetDeviceDescriptors()) .Times(kNumCalls); EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)).Times(0); EXPECT_CALL(*this, MockCallback(_)).Times(kNumCalls); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true; for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); } } TEST_F(MediaDevicesManagerTest, EnumerateNoCacheAudioOutput) { EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)).Times(0); EXPECT_CALL(*video_capture_device_factory_, MockGetDeviceDescriptors()) .Times(0); EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)) .Times(kNumCalls); EXPECT_CALL(*this, MockCallback(_)).Times(kNumCalls); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT] = true; for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); } } TEST_F(MediaDevicesManagerTest, EnumerateNoCacheAudio) { EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)) .Times(kNumCalls); EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)) .Times(kNumCalls); EXPECT_CALL(*this, MockCallback(_)).Times(kNumCalls); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_INPUT] = true; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT] = true; for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); } } TEST_F(MediaDevicesManagerTest, EnumerateCacheAudio) { EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)).Times(1); EXPECT_CALL(*video_capture_device_factory_, MockGetDeviceDescriptors()) .Times(0); EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)).Times(1); EXPECT_CALL(*this, MockCallback(_)).Times(kNumCalls); EnableCache(MEDIA_DEVICE_TYPE_AUDIO_INPUT); EnableCache(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_INPUT] = true; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT] = true; for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); } } TEST_F(MediaDevicesManagerTest, EnumerateCacheVideo) { EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)).Times(0); EXPECT_CALL(*video_capture_device_factory_, MockGetDeviceDescriptors()) .Times(1); EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)).Times(0); EXPECT_CALL(*this, MockCallback(_)).Times(kNumCalls); EnableCache(MEDIA_DEVICE_TYPE_VIDEO_INPUT); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true; for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); } } TEST_F(MediaDevicesManagerTest, EnumerateCacheAudioWithDeviceChanges) { MediaDeviceEnumeration enumeration; EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)).Times(2); EXPECT_CALL(*video_capture_device_factory_, MockGetDeviceDescriptors()) .Times(0); EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)).Times(2); EXPECT_CALL(*this, MockCallback(_)) .Times(2 * kNumCalls) .WillRepeatedly(SaveArg<0>(&enumeration)); size_t num_audio_input_devices = 5; size_t num_audio_output_devices = 3; audio_manager_->SetNumAudioInputDevices(num_audio_input_devices); audio_manager_->SetNumAudioOutputDevices(num_audio_output_devices); EnableCache(MEDIA_DEVICE_TYPE_AUDIO_INPUT); EnableCache(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_INPUT] = true; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT] = true; for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); EXPECT_EQ(num_audio_input_devices, enumeration[MEDIA_DEVICE_TYPE_AUDIO_INPUT].size()); EXPECT_EQ(num_audio_output_devices, enumeration[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT].size()); } // Simulate device change num_audio_input_devices = 3; num_audio_output_devices = 4; audio_manager_->SetNumAudioInputDevices(num_audio_input_devices); audio_manager_->SetNumAudioOutputDevices(num_audio_output_devices); media_devices_manager_->OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO); for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); EXPECT_EQ(num_audio_input_devices, enumeration[MEDIA_DEVICE_TYPE_AUDIO_INPUT].size()); EXPECT_EQ(num_audio_output_devices, enumeration[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT].size()); } } TEST_F(MediaDevicesManagerTest, EnumerateCacheVideoWithDeviceChanges) { MediaDeviceEnumeration enumeration; EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)).Times(0); EXPECT_CALL(*video_capture_device_factory_, MockGetDeviceDescriptors()) .Times(2); EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)).Times(0); EXPECT_CALL(*this, MockCallback(_)) .Times(2 * kNumCalls) .WillRepeatedly(SaveArg<0>(&enumeration)); // Simulate device change size_t num_video_input_devices = 5; video_capture_device_factory_->SetToDefaultDevicesConfig( num_video_input_devices); EnableCache(MEDIA_DEVICE_TYPE_VIDEO_INPUT); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true; for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); EXPECT_EQ(num_video_input_devices, enumeration[MEDIA_DEVICE_TYPE_VIDEO_INPUT].size()); } // Simulate device change num_video_input_devices = 9; video_capture_device_factory_->SetToDefaultDevicesConfig( num_video_input_devices); media_devices_manager_->OnDevicesChanged( base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE); for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); EXPECT_EQ(num_video_input_devices, enumeration[MEDIA_DEVICE_TYPE_VIDEO_INPUT].size()); } } TEST_F(MediaDevicesManagerTest, EnumerateCacheAllWithDeviceChanges) { MediaDeviceEnumeration enumeration; EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)).Times(2); EXPECT_CALL(*video_capture_device_factory_, MockGetDeviceDescriptors()) .Times(2); EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)).Times(2); EXPECT_CALL(*this, MockCallback(_)) .Times(2 * kNumCalls) .WillRepeatedly(SaveArg<0>(&enumeration)); size_t num_audio_input_devices = 5; size_t num_video_input_devices = 4; size_t num_audio_output_devices = 3; audio_manager_->SetNumAudioInputDevices(num_audio_input_devices); video_capture_device_factory_->SetToDefaultDevicesConfig( num_video_input_devices); audio_manager_->SetNumAudioOutputDevices(num_audio_output_devices); EnableCache(MEDIA_DEVICE_TYPE_AUDIO_INPUT); EnableCache(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT); EnableCache(MEDIA_DEVICE_TYPE_VIDEO_INPUT); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_INPUT] = true; devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT] = true; for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); EXPECT_EQ(num_audio_input_devices, enumeration[MEDIA_DEVICE_TYPE_AUDIO_INPUT].size()); EXPECT_EQ(num_video_input_devices, enumeration[MEDIA_DEVICE_TYPE_VIDEO_INPUT].size()); EXPECT_EQ(num_audio_output_devices, enumeration[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT].size()); } // Simulate device changes num_audio_input_devices = 3; num_video_input_devices = 2; num_audio_output_devices = 4; audio_manager_->SetNumAudioInputDevices(num_audio_input_devices); video_capture_device_factory_->SetToDefaultDevicesConfig( num_video_input_devices); audio_manager_->SetNumAudioOutputDevices(num_audio_output_devices); media_devices_manager_->OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO); media_devices_manager_->OnDevicesChanged( base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE); for (int i = 0; i < kNumCalls; i++) { base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); EXPECT_EQ(num_audio_input_devices, enumeration[MEDIA_DEVICE_TYPE_AUDIO_INPUT].size()); EXPECT_EQ(num_video_input_devices, enumeration[MEDIA_DEVICE_TYPE_VIDEO_INPUT].size()); EXPECT_EQ(num_audio_output_devices, enumeration[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT].size()); } } TEST_F(MediaDevicesManagerTest, SubscribeDeviceChanges) { EXPECT_CALL(*audio_manager_, MockGetAudioOutputDeviceNames(_)).Times(3); EXPECT_CALL(*video_capture_device_factory_, MockGetDeviceDescriptors()) .Times(3); EXPECT_CALL(*audio_manager_, MockGetAudioInputDeviceNames(_)).Times(3); size_t num_audio_input_devices = 5; size_t num_video_input_devices = 4; size_t num_audio_output_devices = 3; audio_manager_->SetNumAudioInputDevices(num_audio_input_devices); video_capture_device_factory_->SetToDefaultDevicesConfig( num_video_input_devices); audio_manager_->SetNumAudioOutputDevices(num_audio_output_devices); // Run an enumeration to make sure |media_devices_manager_| has the new // configuration. EXPECT_CALL(*this, MockCallback(_)); MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_INPUT] = true; devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true; devices_to_enumerate[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT] = true; base::RunLoop run_loop; media_devices_manager_->EnumerateDevices( devices_to_enumerate, base::Bind(&MediaDevicesManagerTest::EnumerateCallback, base::Unretained(this), &run_loop)); run_loop.Run(); // Add device-change event subscribers. MockMediaDeviceChangeSubscriber subscriber_audio_input; MockMediaDeviceChangeSubscriber subscriber_video_input; MockMediaDeviceChangeSubscriber subscriber_audio_output; MockMediaDeviceChangeSubscriber subscriber_all; media_devices_manager_->SubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_AUDIO_INPUT, &subscriber_audio_input); media_devices_manager_->SubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_VIDEO_INPUT, &subscriber_video_input); media_devices_manager_->SubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, &subscriber_audio_output); media_devices_manager_->SubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_AUDIO_INPUT, &subscriber_all); media_devices_manager_->SubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_VIDEO_INPUT, &subscriber_all); media_devices_manager_->SubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, &subscriber_all); MediaDeviceInfoArray notification_audio_input; MediaDeviceInfoArray notification_video_input; MediaDeviceInfoArray notification_audio_output; MediaDeviceInfoArray notification_all_audio_input; MediaDeviceInfoArray notification_all_video_input; MediaDeviceInfoArray notification_all_audio_output; EXPECT_CALL(subscriber_audio_input, OnDevicesChanged(MEDIA_DEVICE_TYPE_AUDIO_INPUT, _)) .Times(1) .WillOnce(SaveArg<1>(&notification_audio_input)); EXPECT_CALL(subscriber_video_input, OnDevicesChanged(MEDIA_DEVICE_TYPE_VIDEO_INPUT, _)) .Times(1) .WillOnce(SaveArg<1>(&notification_video_input)); EXPECT_CALL(subscriber_audio_output, OnDevicesChanged(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, _)) .Times(1) .WillOnce(SaveArg<1>(&notification_audio_output)); EXPECT_CALL(subscriber_all, OnDevicesChanged(MEDIA_DEVICE_TYPE_AUDIO_INPUT, _)) .Times(2) .WillRepeatedly(SaveArg<1>(&notification_all_audio_input)); EXPECT_CALL(subscriber_all, OnDevicesChanged(MEDIA_DEVICE_TYPE_VIDEO_INPUT, _)) .Times(2) .WillRepeatedly(SaveArg<1>(&notification_all_video_input)); EXPECT_CALL(subscriber_all, OnDevicesChanged(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, _)) .Times(2) .WillRepeatedly(SaveArg<1>(&notification_all_audio_output)); // Simulate device changes. num_audio_input_devices = 3; num_video_input_devices = 2; num_audio_output_devices = 4; audio_manager_->SetNumAudioInputDevices(num_audio_input_devices); video_capture_device_factory_->SetToDefaultDevicesConfig( num_video_input_devices); audio_manager_->SetNumAudioOutputDevices(num_audio_output_devices); media_devices_manager_->OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO); media_devices_manager_->OnDevicesChanged( base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE); base::RunLoop().RunUntilIdle(); EXPECT_EQ(num_audio_input_devices, notification_audio_input.size()); EXPECT_EQ(num_video_input_devices, notification_video_input.size()); EXPECT_EQ(num_audio_output_devices, notification_audio_output.size()); EXPECT_EQ(num_audio_input_devices, notification_all_audio_input.size()); EXPECT_EQ(num_video_input_devices, notification_all_video_input.size()); EXPECT_EQ(num_audio_output_devices, notification_all_audio_output.size()); media_devices_manager_->UnsubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_AUDIO_INPUT, &subscriber_audio_input); media_devices_manager_->UnsubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_VIDEO_INPUT, &subscriber_video_input); media_devices_manager_->UnsubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, &subscriber_audio_output); // Simulate further device changes. Only the objects still subscribed to the // device-change events will receive notifications. num_audio_input_devices = 2; num_video_input_devices = 1; num_audio_output_devices = 3; audio_manager_->SetNumAudioInputDevices(num_audio_input_devices); video_capture_device_factory_->SetToDefaultDevicesConfig( num_video_input_devices); audio_manager_->SetNumAudioOutputDevices(num_audio_output_devices); media_devices_manager_->OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO); media_devices_manager_->OnDevicesChanged( base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE); base::RunLoop().RunUntilIdle(); EXPECT_EQ(num_audio_input_devices, notification_all_audio_input.size()); EXPECT_EQ(num_video_input_devices, notification_all_video_input.size()); EXPECT_EQ(num_audio_output_devices, notification_all_audio_output.size()); } } // namespace content
[ "hedonist.ky@gmail.com" ]
hedonist.ky@gmail.com
ac3db9ffcd944f62faf11eaf008d79e8f362a532
85b104e0047588247d95578583d86c7aacd484ca
/11-17_message_queue.cpp
ed29fdeda6dfc3ab9634e5a7d2bb0c33fd7c52c5
[]
no_license
artisdom/cpp_recipes_code
4dc897a1e6fe838db1fbb60a807c3a6d747fe61c
fea587d01c9e62dfd46e453745a0804301ddbd7e
refs/heads/master
2020-03-07T16:39:04.642781
2018-04-16T00:48:28
2018-04-16T00:48:28
127,588,643
0
0
null
null
null
null
UTF-8
C++
false
false
4,868
cpp
#include <cassert> #include <future> //#include <conditional> #include <condition_variable> #include <mutex> #include <vector> #include <iostream> using namespace std; class RunningTotal { private: int m_Value{ 0 }; bool m_Finished{ false }; public: RunningTotal& operator+=(int value) { m_Value += value; return *this; } RunningTotal& operator-=(int value) { m_Value -= value; return *this; } RunningTotal& Finish() { m_Finished = true; return *this; } int operator *() const throw(int) { if (!m_Finished) { throw m_Value; } return m_Value; } }; template <typename T> class MessageQueue { private: using Queue = vector<T>; using QueueIterator = typename Queue::iterator; Queue m_A; Queue m_B; Queue* m_Producer{ &m_A }; Queue* m_Consumer{ &m_B }; QueueIterator m_ConsumerIterator{ m_B.end() }; condition_variable& m_MessageCondition; condition_variable m_ConsumptionFinished; mutex m_MutexProducer; mutex m_MutexConsumer; unsigned int m_SwapCount{ 0 }; public: MessageQueue(condition_variable& messageCondition) : m_MessageCondition{ messageCondition } { } unsigned int GetCount() const { return m_SwapCount; } void Add(T&& operation) { unique_lock<mutex> lock{ m_MutexProducer }; m_Producer->insert(m_Producer->end(), std::move(operation)); } void BeginConsumption() { m_MutexConsumer.lock(); } T consume() { T operation; if (m_Consumer->size() > 0) { operation = *m_ConsumerIterator; m_ConsumerIterator = m_Consumer->erase(m_ConsumerIterator); assert(m_ConsumerIterator == m_Consumer->begin()); } return operation; } void EndConsumption() { assert(m_Consumer->size() == 0); m_MutexConsumer.unlock(); m_ConsumptionFinished.notify_all(); } unsigned int Swap() { unique_lock<mutex> lockB{ m_MutexConsumer }; m_ConsumptionFinished.wait(lockB, [this]() { return m_Consumer->size() == 0; }); unique_lock<mutex> lockA{ m_MutexProducer }; Queue* temp{ m_Producer }; m_Producer = m_Consumer; m_Consumer = temp; m_ConsumerIterator = m_Consumer->begin(); m_MessageCondition.notify_all(); return m_SwapCount++; } }; using RunningTotalOperation = function<RunningTotal&()>; using RunningTotalMessageQueue = MessageQueue<RunningTotalOperation>; int Task(reference_wrapper<mutex> messageQueueMutex, reference_wrapper<condition_variable> messageCondition, reference_wrapper<RunningTotalMessageQueue> messageQueueRef) { int result{0}; RunningTotalMessageQueue& messageQueue = messageQueueRef.get(); unsigned int currentSwapCount{ 0 }; bool finished{ false }; while (!finished) { unique_lock<mutex> lock{ messageQueueMutex.get() }; messageCondition.get().wait(lock, [&messageQueue, &currentSwapCount]() { return currentSwapCount != messageQueue.GetCount(); } ); messageQueue.BeginConsumption(); currentSwapCount = messageQueue.GetCount(); while (RunningTotalOperation operation{ messageQueue.consume() }) { RunningTotal& runningTotal = operation(); try { result = *runningTotal; finished = true; break; } catch (int param) { // nothing to do, not finished yet! cout << "Total not yet finished, current is: " << param << endl; } } messageQueue.EndConsumption(); } return result; } int main(int argc, char* argv[]) { RunningTotal runningTotal; mutex messageQueueMutex; condition_variable messageQueueCondition; RunningTotalMessageQueue messageQueue(messageQueueCondition); auto myFuture = async(launch::async, Task, ref(messageQueueMutex), ref(messageQueueCondition), ref(messageQueue)); messageQueue.Add(bind(&RunningTotal::operator+=, &runningTotal, 3)); messageQueue.Swap(); messageQueue.Add(bind(&RunningTotal::operator-=, &runningTotal, 100)); messageQueue.Add(bind(&RunningTotal::operator+=, &runningTotal, 100000)); messageQueue.Add(bind(&RunningTotal::operator-=, &runningTotal, 256)); messageQueue.Swap(); messageQueue.Add(bind(&RunningTotal::operator-=, &runningTotal, 100)); messageQueue.Add(bind(&RunningTotal::operator+=, &runningTotal, 100000)); messageQueue.Add(bind(&RunningTotal::operator-=, &runningTotal, 256)); messageQueue.Swap(); messageQueue.Add(bind(&RunningTotal::Finish, &runningTotal)); messageQueue.Swap(); cout << "The final total is: " << myFuture.get() << endl; return 0; }
[ "xigang.feng@ericsson.com" ]
xigang.feng@ericsson.com
35e459a1203b8d1b627c05f0a2514f602f5fbc98
ac2c7ce45a28c8ceb10d543944db90f6025e8a58
/src/testprog/gltf2/litrot.cpp
9a982cfcfa160381742bcc3f36033e29beef8e9d
[ "MIT", "BSD-3-Clause", "Zlib", "BSL-1.0" ]
permissive
degarashi/revenant
a5997ccc9090690abd03a19e749606c9cdf935d4
9e671320a5c8790f6bdd1b14934f81c37819f7b3
refs/heads/master
2021-01-11T00:15:06.876412
2019-09-08T13:00:26
2019-09-08T13:00:26
70,564,404
0
0
null
null
null
null
UTF-8
C++
false
false
1,578
cpp
#include "litrot.hpp" #include "../../input/input.hpp" #include "../../imgui_sdl2.hpp" namespace rev::test { // -------------- LitRot -------------- LitRot::LitRot(): _rot(frea::Quat::Identity()) {} void LitRot::update( const HActC& dir_x, const HActC& dir_y, const frea::Vec3& right, const frea::Vec3& up ) { const float dx = dir_x->getValueAsFloat()*70, dy = dir_y->getValueAsFloat()*70; const auto q = frea::Quat::Rotation(up, frea::DegF(-dx)) * frea::Quat::Rotation(right, frea::DegF(-dy)); _rot= q * _rot; } frea::Vec3 LitRot::getDir() const { return _rot.getDir(); } // -------------- LitRot -------------- LitRotObj::LitRotObj(): _press(false) { const auto hM = Mouse::OpenMouse(0); _act[Act::DirX] = mgr_input.makeAction("lit_x"); _act[Act::DirX]->addLink(hM, InputFlag::Axis, 0); _act[Act::DirY] = mgr_input.makeAction("lit_y"); _act[Act::DirY]->addLink(hM, InputFlag::Axis, 1); _act[Act::LitBtn] = mgr_input.makeAction("lit_b"); _act[Act::LitBtn]->addLink(hM, InputFlag::Button, 1); } void LitRotObj::update( const frea::Vec3& right, const frea::Vec3& up ) { if(_press) { LitRot::update(_act[Act::DirX], _act[Act::DirY], right, up); if(!_act[Act::LitBtn]->isKeyPressing()) { const auto hM = Mouse::OpenMouse(0); hM->setMouseMode(MouseMode::Absolute); _press = false; } } else { if(_act[Act::LitBtn]->isKeyPressed()) { if(!mgr_gui.pointerOnGUI()) { const auto hM = Mouse::OpenMouse(0); hM->setMouseMode(MouseMode::Relative); _press = true; } } } } }
[ "slice013@gmail.com" ]
slice013@gmail.com
2d297c13078e37402480a72f6e9524a8b4d63c99
e3e8b7056b8c5a604cc1a576da0d6d5134870f93
/src/lc124/lc124.cpp
cf79512574177496f4a5b53c1c1ad7cc6a473eb5
[]
no_license
zou-song/leetcode
a2acc8d01538f8bc84dbb83f11c24fe876cd071b
5172da312cba7e185d155386bc5527432c40c2f8
refs/heads/master
2020-04-25T14:57:22.251872
2019-05-20T11:59:18
2019-05-20T11:59:18
172,860,827
0
0
null
2019-05-20T11:59:19
2019-02-27T06:55:26
C++
UTF-8
C++
false
false
1,084
cpp
#include "lc.h" typedef LCBinaryTreeNode<int> TreeNode; class Solution { public: int maxPathSum(TreeNode* root, int& ret) { if (!root) return 0; if (!root->left && !root->right) { if (root->val > ret) ret = root->val; return root->val; } int left = maxPathSum(root->left, ret); int right = maxPathSum(root->right, ret); vector<int> v(4); v[0] = root->val; v[1] = root->val + left; v[2] = root->val + right; v[3] = root->val + left + right; int tmp = *max_element(v.begin(), v.end()); if (tmp > ret) ret = tmp; return *max_element(v.begin(), v.end() - 1); } int maxPathSum(TreeNode* root) { int ret = INT_MIN; maxPathSum(root, ret); return ret; } }; int main(int argc, char const *argv[]) { string line; while (getline(cin, line)) { LCBinaryTree<int> btree; walkString(btree, line); cout << toString(Solution().maxPathSum(btree.root)) << endl; } return 0; }
[ "zousong0322@qq.com" ]
zousong0322@qq.com
6dc94c146e39003acf138f19e3529fcc38b13d61
3e89ec754c2d89dc6595ade63cbbdb9282c3b4c9
/EditDlg.h
30b327641275be961a55b73bdb05982def9bb472
[]
no_license
pglen/cryptosticky
9450a645c17977e1327f28d8f78baf8ebad3e12e
ef6c3521020c912ee2be3c7b988480e0899a6b0c
refs/heads/master
2021-01-11T23:33:45.106041
2017-09-20T22:02:15
2017-09-20T22:02:15
78,600,380
0
0
null
null
null
null
UTF-8
C++
false
false
5,929
h
/* =====[ EditDlg.h ]========================================== Description: The CryptoSticky project, implementation of the EditDlg.h Defines the behavior for the application. Compiled: MS-VC 6.00 Notes: <Empty Notes> Revisions: REV DATE BY DESCRIPTION ---- -------- ----------- ---------------------------- 0.00 6/3/2009 Peter Glen Initial version. ======================================================================= */ #if !defined(AFX_EDITDLG_H__DAA2C590_81D4_4443_B53B_2C6F692D9866__INCLUDED_) #define AFX_EDITDLG_H__DAA2C590_81D4_4443_B53B_2C6F692D9866__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // EditDlg.h : header file // #include <io.h> #include <sys/types.h> #include <sys/stat.h> #include "xbutton.h" #include "PGedit.h" #include "ymemo.h" #include "waveedit.h" #include "PlaySound.h" #include "RecordSound.h" #include "Speak.h" #include "label.h" #include "xedit.h" #define CURR_MEMO_VER 3 ///////////////////////////////////////////////////////////////////////////// // CEditDlg dialog class CEditDlg : public CDialog { static void CEditDlg::StaticSound(void *org, char *buff, int len); public: CEditDlg(CWnd* pParent = NULL); // standard constructor int m_BackColor; int Sound(char *buff, int len); CString memoroot, memorootp; CString caption, title, file, str; int fresh, ro; CYmemo *st; CRecordSound recsnd; CPlaySound playsound; HTREEITEM newhandle; protected: #ifdef SPEAK CSpeak sp; #endif CString oldbutt; void OnCancel(); void Prop_ampm(); void SetAla(CTime ct); void UpdateAla(); void OnOK(void); void LoadMemo(); void Decorate(); CString m_sound, section12, btext, btext2; MemoSupp memo; struct _stat old_sbuff; //CPGedit pged; public: // Dialog Data //{{AFX_DATA(CEditDlg) enum { IDD = IDD_DIALOG1 }; CXButton m_b19; CXButton m_b35; CXButton m_b34; CXButton m_b17; CXButton m_b9; CXButton m_b5; CXButton m_b8; CwaveEdit m_wav; CPGedit m_body; CXButton m_b7; CXButton m_b14; CXButton m_b13; CXButton m_b12; CXButton m_b11; CXButton m_b4; CxEdit m_folderc; CPGedit m_chead; CXButton m_3; CXButton m_2; CXButton m_1; CXButton m_can; CXButton m_ok; CSpinButtonCtrl m_spin2; CSpinButtonCtrl m_spin1; BOOL m_center; CString m_hh; CString m_mm; CString m_alatime; CString m_aladate; BOOL m_ala; CString m_us; BOOL m_persist; BOOL m_red; BOOL m_soundon; CString m_head; BOOL m_folder; BOOL m_beep; CString m_ampm; BOOL m_text; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CEditDlg) public: virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CEditDlg) virtual BOOL OnInitDialog(); afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); afx_msg void OnDeltaposSpin1(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposSpin2(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg void OnSelchangeMonthcalendar1(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnChangeEdit2(); afx_msg void OnChangeEdit4(); afx_msg void OnSelectMonthcalendar1(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnReleasedcaptureMonthcalendar1(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnCheck1(); afx_msg void OnCheck3(); afx_msg void OnCheck4(); afx_msg void OnButton3(); afx_msg void OnButton1(); afx_msg void OnButton2(); afx_msg void OnCheck8(); afx_msg void OnCheck5(); afx_msg void OnButton4(); afx_msg void OnButton11(); afx_msg void OnButton12(); afx_msg void OnRadio1(); afx_msg void OnRadio2(); afx_msg void OnButton13(); afx_msg void OnButton14(); afx_msg void OnButton7(); afx_msg void OnCheck9(); afx_msg void OnButton5(); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnButton8(); afx_msg void OnButton9(); afx_msg void OnDestroy(); afx_msg void OnButton17(); afx_msg void OnButton34(); afx_msg void OnButton35(); afx_msg void OnCheck13(); afx_msg void OnButton19(); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); afx_msg BOOL OnEraseBkgnd(CDC* pDC); CLabel m_titletext; CxEdit m_redcheck; CxEdit m_centertext; CxEdit m_persisttext; CxEdit m_autotext; CxEdit m_calframe; CxEdit m_alaframe; CxEdit m_alaframe2; CxEdit m_hourt; CxEdit m_mint; CxEdit m_ampmt; CxEdit m_alaht; CxEdit m_alamint; CxEdit m_alarmampmt; CxEdit m_check3t; CxEdit check4t; CxEdit m_check5t; CxEdit m_check13t; CxEdit m_cant; CxEdit m_can2t; CxEdit m_radio1; CxEdit m_radio2; afx_msg void OnBnClickedOk(); afx_msg void OnEnChangeEdit1(); CXButton m_decr; afx_msg void OnBnClickedButton38(); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_EDITDLG_H__DAA2C590_81D4_4443_B53B_2C6F692D9866__INCLUDED_)
[ "peterglen99@gmail.com" ]
peterglen99@gmail.com
f561127f2d919f49e2dd9051725ea009ab762587
f533ffc74134940f99a1badaa486998a291e5f62
/YAWT/src/YAWT/Interfaces/Windows/WindowsWindow.h
f0e781c92f6ed024ff28d4f699d1d9fddb8f55c6
[]
no_license
Dargish/YAWT
da548e4f605d16484056dfddb4d8d2b48ad58db0
39ae501a763aae565a0f79d76d0cd1a82afce8ab
refs/heads/master
2021-01-01T05:38:09.732802
2015-01-04T02:40:18
2015-01-04T02:40:18
28,562,071
0
0
null
null
null
null
UTF-8
C++
false
false
580
h
#pragma once #include "../../AbstractPrivateWindow.h" #if defined _WIN32 #include <Windows.h> namespace yawt { namespace interfaces { namespace windows { class WindowsWindow : public AbstractPrivateWindow { public: WindowsWindow(long width, long height, bool fullScreen); virtual ~WindowsWindow(); virtual bool create(); virtual void show(); virtual void* handle() const; static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); private: HINSTANCE m_hInstance; HWND m_hWnd; }; } } } #endif
[ "Dargish@gmail.com" ]
Dargish@gmail.com
75787ce37feca29c06b1a4f6abf00f7bd5563c22
e036996cf06e9143ca093c045e29fdb7ff8ee4f9
/morse_code_transmitter/morse_code_transmitter.ino
530bd753aa7aa493bf41478d2b00f2184ae14514
[]
no_license
blackchacal/morseduino
39a819435b176663208316af2cb20e9900e7e1c3
ec3a108583b912d3dfcfbc37cfcbea8f086061b1
refs/heads/master
2020-06-16T04:10:30.786996
2019-07-13T00:28:58
2019-07-13T00:32:24
195,476,496
0
0
null
null
null
null
UTF-8
C++
false
false
5,837
ino
/** * @Project: Morse code Emitter/Receiver * @Description: This project consists on a Morse code emitter and receiver modules. * The goal is for the modules comunicate with each other using morse code * IR light signals. The user sends some text through the serial port to * the emitter module which encodes it to morse code and sends to the receiver * via IR signals. The receiver then translates the signals back to text and * shows it through a LCD display. * * @Module: Emitter * * @Author: Ricardo Tonet <ribeiro.tonet@gmail.com> (github: https://github.com/blackchacal) */ /** * International Morse code is composed of five elements: * * 1. short mark, dot or "dit" (.): "dot duration" is one time unit long * 2. longer mark, dash or "dah" (_): three time units long * 3. inter-element gap between the dots and dashes within a character: one dot duration or one unit long * 4. short gap (between letters): three time units long * 5. medium gap (between words): seven time units long */ /************************************************************** * Constants and Variables * **************************************************************/ // Constants const unsigned int TIME_UNIT = 50; // one time unit: 50 ms const unsigned int SOUND_FREQ = 880; // 440 Hz (Sol) // Pins int LedPin = 2; int BuzzPin = 3; // Vars unsigned long time = 0; /************************************************************** * Functions * **************************************************************/ String translateMessage(String msg) { String tmsg; // Translated message String charCode; unsigned int msgSize = msg.length(); for (int i = 0; i < msgSize; i++) { charCode = convertCharacterToMorseCode(msg[i]); tmsg += charCode + " "; } tmsg.trim(); return tmsg; } void sendMessage(String msg) { Serial.println('"'+msg+'"'); convertMorseCodeToSignal(msg); } String convertCharacterToMorseCode(char c) { String code; switch(c) { case 'a': case 'A': code = ".-"; break; case 'b': case 'B': code = "-..."; break; case 'c': case 'C': code = "-.-."; break; case 'd': case 'D': code = "-.."; break; case 'e': case 'E': code = "."; break; case 'f': case 'F': code = "..-."; break; case 'g': case 'G': code = "--."; break; case 'h': case 'H': code = "...."; break; case 'i': case 'I': code = ".."; break; case 'j': case 'J': code = ".---"; break; case 'k': case 'K': code = "-.-"; break; case 'l': case 'L': code = ".-.."; break; case 'm': case 'M': code = "--"; break; case 'n': case 'N': code = "-."; break; case 'o': case 'O': code = "---"; break; case 'p': case 'P': code = ".--."; break; case 'q': case 'Q': code = "--.-"; break; case 'r': case 'R': code = ".-."; break; case 's': case 'S': code = "..."; break; case 't': case 'T': code = "-"; break; case 'u': case 'U': code = "..-"; break; case 'v': case 'V': code = "...-"; break; case 'w': case 'W': code = ".--"; break; case 'x': case 'X': code = "-..-"; break; case 'y': case 'Y': code = "-.--"; break; case 'z': case 'Z': code = "--.."; break; case '1': code = ".----"; break; case '2': code = "..---"; break; case '3': code = "...--"; break; case '4': code = "....-"; break; case '5': code = "....."; break; case '6': code = "-...."; break; case '7': code = "--..."; break; case '8': code = "---.."; break; case '9': code = "----."; break; case '0': code = "-----"; break; case ' ': code = " "; default: code = ""; break; } return code; } void convertMorseCodeToSignal(String code) { unsigned int codeSize = code.length(); for (int i = 0; i < codeSize; i++) { sendDotDashSpace(code.charAt(i)); } } /** * Converts Morse Code (dash-dot-space) into sound or light. */ void sendDotDashSpace(char c) { switch (c) { case '.': tone(BuzzPin, SOUND_FREQ, TIME_UNIT); sendLightSignal(TIME_UNIT); delay(TIME_UNIT); break; case '-': tone(BuzzPin, SOUND_FREQ, TIME_UNIT*3); sendLightSignal(TIME_UNIT*3); delay(TIME_UNIT); break; case ' ': delay(TIME_UNIT); break; } } /** * Sends morse code via LED (IR or Normal). */ void sendLightSignal(unsigned int timeUnit) { digitalWrite(LedPin, HIGH); delay(timeUnit); digitalWrite(LedPin, LOW); } /************************************************************** * Main Code * **************************************************************/ void setup() { Serial.begin(9600); pinMode(LedPin, OUTPUT); pinMode(BuzzPin, OUTPUT); } void loop() { String message; String morseMessage; while (Serial.available()) { // Get text message from serial port message = Serial.readString(); Serial.print(message+": "); if (message.length() > 0) { // Translate text message to morse code message morseMessage = translateMessage(message); // Send morse code message to receiver sendMessage(morseMessage); } } }
[ "ribeiro.tonet@gmail.com" ]
ribeiro.tonet@gmail.com
be5097b41e88e3a48007dde903d79f256b304fc0
217dc5e7628ffa689134c9001085d272aca5d22d
/copy/Project/Tuffy_Travel_06/tuffytravel.cpp
41b083c3c1dba17d5b462083bc20f82af465b0c9
[ "MIT" ]
permissive
markjcasas/CPSC121
167c59cbc654f622eace478d362a555a2a1a0121
5fa87edbc7d9a8d278aea182c34342402454a444
refs/heads/master
2021-06-14T01:12:31.011610
2019-12-22T04:30:18
2019-12-22T04:30:18
254,465,752
0
0
null
2020-04-09T19:55:42
2020-04-09T19:55:41
null
UTF-8
C++
false
false
246
cpp
#include "route.hpp" #include <fstream> #include <iostream> int main() { RouteManager main_object; std::cout << "Welcome to TuffyTravel!\n\n"; action(main_object); std::cout << "\nThank you for using TuffyTravel!" << '\n'; return 0; }
[ "zpeskin@csu.fullerton.edu" ]
zpeskin@csu.fullerton.edu
d77076579d916999fc311a4ae0358b76252f4b95
b637aa670e887b254d83c2359050639b08ea8898
/Vulkan_Class_0/MxUtils.h
62c97e8f8837c7db2690893d1f13e2ad27d6cef2
[]
no_license
VirFunc/LearnVulkan
7f99fd649d56df76013c2f91eae2e8714ccc4b60
c299588b42ad9fff3fb1f9f22bd78361654a076e
refs/heads/master
2020-04-07T13:25:44.186504
2019-02-11T06:25:55
2019-02-11T06:25:55
158,407,007
0
1
null
null
null
null
UTF-8
C++
false
false
2,792
h
#pragma once #ifndef _MX_UTILS_H_ #define _MX_UTILS_H_ #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #define GLM_ENABLE_EXPERIMENTAL #include<glm/glm.hpp> #include<glm/gtc/matrix_transform.hpp> #include<glm/gtx/euler_angles.hpp> #include<glm/gtc/quaternion.hpp> #include<glm/gtx/quaternion.hpp> namespace Mix { constexpr float MX_EPSILON = 0.000001f; constexpr float MX_PI = 3.141593f; // //MxSpace enum class MxSpace { World, Self }; glm::quat rotateBetweenVec(const glm::vec3& from, const glm::vec3& to); struct MxAxis { glm::vec3 x; glm::vec3 y; glm::vec3 z; static const glm::vec3 initX; static const glm::vec3 initY; static const glm::vec3 initZ; MxAxis(); void applyRotateMat(const glm::mat4& matrix); void rotateFromInit(const glm::mat4& matrix); }; //MxTransform class MxTransform { private: glm::vec3 mPosition; glm::vec3 mScale; MxAxis mAxis; glm::quat mQuaternion; void quaternionUpdated(); public: MxTransform(); //set position in world coordinates void setPosition(const glm::vec3& position) { mPosition = position; }; void setPosition(const float x, const float y, const float z) { setPosition(glm::vec3(x, y, z)); }; glm::vec3 getPosition() const { return mPosition; }; //get rotation in world coordinates stored as quaternion glm::quat getRotation() const { return mQuaternion; }; //get rotation in world coordinates as euler angles glm::vec3 getEulerAngles() const; //get local coordinates const MxAxis& getAxis() const { return mAxis; }; glm::vec3 getForward() const { return mAxis.x; }; glm::vec3 getRight() const { return -mAxis.y; }; glm::vec3 getUp() const { return mAxis.z; }; void translate(const glm::vec3& translation, const MxSpace relativeTo = MxSpace::Self); void translate(const float x, const float y, const float z, const MxSpace relativeTo = MxSpace::Self); void rotate(const glm::vec3& eulers, const MxSpace relativeTo = MxSpace::Self); void rotate(const float xAngle, const float yAngle, const float zAngle, const MxSpace relativeTo = MxSpace::Self) { rotate(glm::vec3(xAngle, yAngle, zAngle), relativeTo); }; void rotate(const glm::vec3& axis, const float angle, const MxSpace relativeTo = MxSpace::Self) { rotate(glm::eulerAngles(glm::angleAxis(angle, axis)), relativeTo); } //rotates about axis passing through point in world coordinates by angle radians void rotateAround(const glm::vec3& point, const glm::vec3& axis, const float angle); void scale(const glm::vec3& scale, const MxSpace relativeTo = MxSpace::Self); void lookAt(const glm::vec3& worldPosition, const glm::vec3& worldUp = MxAxis::initZ); void lookAt(const MxTransform& target, const glm::vec3& worldUp = MxAxis::initZ); }; } #endif
[ "x1239392454@outlook.com" ]
x1239392454@outlook.com
5aee0c478edac8ebeb8fc2c855bf3bae6cc97938
8be083e9fbf15606201217d6c4b87c929e418065
/tags/release-0.7/commands/rescale-cmd.hh
01a2c82a76cbc3361aab8c4c5660e7151aceaff1
[ "Apache-2.0" ]
permissive
BGCX067/faint-graphics-editor-svn-to-git
430768d441f3e9b353fbc128e132f7406ee48c0e
dad252f820d29ab336bcfa57138625dae6dfed60
refs/heads/master
2021-01-13T00:56:26.685520
2015-12-28T14:22:44
2015-12-28T14:22:44
48,752,914
1
1
null
null
null
null
UTF-8
C++
false
false
1,112
hh
// Copyright 2012 Lukas Kemmer // // Licensed under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You // may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. #ifndef FAINT_RESCALE_CMD_HH #define FAINT_RESCALE_CMD_HH #include "commands/command.hh" #include "geo/intsize.hh" class RescaleCommand : public Command { public: RescaleCommand( const IntSize&, ScaleQuality::type ); ~RescaleCommand(); void Do( CommandContext& ); void DoRaster( CommandContext& ); std::string Name() const; Point Translate( const Point& ) const; void Undo( CommandContext& ); private: IntSize m_size; IntSize m_oldSize; ScaleQuality::type m_quality; Command* m_objectResize; }; #endif
[ "you@example.com" ]
you@example.com
c5f77ce314aa5cb93ad99147521fe0f5d5d0bef9
c4951609929228cda38a4ff7ab4c3b443331b3b5
/Qt/src/chapter04/ks04_15/province.h
0e15b569ece00ba24ce9ff9a180b165225dba093
[]
no_license
519984307/master
7d392347933687c13203f2b169ebd78aed4a3334
0edcd54006ce8dda4fe5716d4cda6620ef352abd
refs/heads/master
2023-03-16T04:02:50.491312
2019-10-25T07:05:08
2019-10-25T07:05:08
null
0
0
null
null
null
null
GB18030
C++
false
false
2,093
h
/*! * Copyright (C) 2018 女儿叫老白 * 版权所有。 * 代码仅用于课程《Qt入门与提高-GUI产品开发》的学习,请勿传播。 * 免责声明:代码不保证稳定性,请勿用作商业用途,否则后果自负。 \file: province.h \brief 省(州)类定义文件。 \author 女儿叫老白 星点分享: http://xingdianketang.cn/ \Date 2018/10 */ #ifndef _PROVINCE_H_ #define _PROVINCE_H_ #include <QList> #include <QString> #include "serialize.h" class CCity; class CCountry; // 省(州)类 //----------------------------------------- class CProvince { public: CProvince(); ~CProvince(); /** * @brief 设置省(州)名称. * @param[in] strName 省(州)名称 * @return void */ void setName(const QString& str) {m_strName = str;} /** * @brief 获取省(州)名称. * @return 省(州)名称 */ QString getName(void) const {return m_strName;} /** * @brief 设置省(州)所在国家 * @param[in] pCountry 省(州)所在国家 * @return void */ void setCountry(CCountry* pCountry) {m_pCountry = pCountry;} /** * @brief 获取省(州)所在国家 * @return 省(州)所在国家 */ CCountry* getCountry(void) const {return m_pCountry;} /** * @brief 添加城市 * @param[in] pCity 城市 * @return 添加后的城市个数 */ int addCity(CCity* pCity); /** * @brief 添加城市 * @param[out] lstCities 城市列表 * @return 已有城市个数 */ int getCities(QList<CCity*>& lstCities) const { lstCities = m_lstCities; return lstCities.size(); } /** * @brief 用来把类对象进行二进制方式序列化的函数。本接口内部已经调用QDataStream::setByteOrder(QDataStream::LittleEndian)。 * @param[in] ds 文件流对象。 * @param[in|out] pError 错误信息。 * @return ESerializeCode枚举值。 */ ESerializeCode serializeBinary(QDataStream& ds, QString* pError) const; private: QString m_strName; CCountry* m_pCountry; QList<CCity*> m_lstCities; }; #endif // for _PROVINCE_H_
[ "xin_nian13@163.com" ]
xin_nian13@163.com
1e24a25889976e48497efd02d713c22808962aff
650965dfff8359969a8d09979ce1cb464a6b72e0
/Volumn_025/poj_3404_Bridge_over_a_rough_river.cpp
d3b099e5b1e4bb39b006fb7aba61134879cededc
[ "Apache-2.0" ]
permissive
antonio081014/ACM-POJ-CodeBase
124b5541c5f3ed95e19d2fc7d9ba7aceea8cf71e
fda83207fa5c4ffd09f16880ff4e34a742716269
refs/heads/master
2020-05-26T07:46:07.987029
2013-11-07T18:25:07
2013-11-07T18:25:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,253
cpp
//Fri May 21 15:37:01 CDT 2010 #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; long long crossriver(vector<int> v, int T) { if (T == 1) { return v[0]; } if (T == 2) { return v[1]; } if (T == 3) { return v[0] + v[1] + v[2]; } if (v[0] + 3 * v[1] + v[T - 1] > 2 * v[0] + v[1] + v[T - 2] + v[T - 1]) { return 2 * v[0] + v[T - 2] + v[T - 1] + crossriver(v, T - 2); } else { return v[0] + 2 * v[1] + v[T - 1] + crossriver(v, T - 2); } } int main(int argc, const char* argv[]) { // freopen("input.in", "r", stdin); // freopen("output.out", "w", stdout); int T; while(cin >> T) { vector<int> v; for(int i=0; i<T; i++) { int number; cin >> number; v.push_back(number); } sort(v.begin(), v.end()); cout << crossriver(v, T) << endl; } // fclose(stdin); // fclose(stdout); return 0; }
[ "antonio081014@antonio081014.com" ]
antonio081014@antonio081014.com
fadf3fd59e16567c3a2a8895e5acee641a97d73d
8cd27adf6e46f7847753ca8e9794cceb79d67a7d
/writeMat.h
d0e9b9cb40ba4868498801b128f8260f7a6f1405
[ "ISC" ]
permissive
mohamed-helala/stereo-correspondence
fb0182e0e9ee27478a4a4c5136b3cf93e1aced63
c8a89b69633702522fc16a9e7f4457c4f1f1c2f9
refs/heads/master
2021-01-16T18:19:17.694275
2015-02-16T21:31:52
2015-02-16T21:31:52
30,889,105
5
1
null
null
null
null
UTF-8
C++
false
false
392
h
#ifndef WRITEMAT_H #define WRITEMAT_H #endif // WRITEMAT_H #ifndef __OPENCV_ALL_HPP__ #include <opencv2/opencv.hpp> #endif #ifndef _STDLIB_H #include <stdlib.h> #endif #ifndef _STDIO_H #include <stdio.h> #endif #ifndef _GCC_WRAP_STDINT_H #include <stdint.h> #endif using namespace cv; void writeMat( Mat const& mat, const char* filename, const char* varName = "A", bool bgr2rgb = true );
[ "mohamed.helala@gmail.com" ]
mohamed.helala@gmail.com
4fe7ee98b0b22af922245fa1a9c455593df3f701
589ed46e35667dcbcb55385cc1f9b52011b01b6a
/5-using the Access Specifier Private in Classes.cpp
abde76e0ac421f0290d5919230b05bd4545d54a4
[]
no_license
divyanshukumar10/Object-Oriented-Programming
b45df9d2b47a2bf93b762f3e05ae6ed17fff7167
5fe4d78c49d529e1093cfb1e3417113becf672ed
refs/heads/main
2023-02-23T09:45:41.048954
2021-02-02T16:25:58
2021-02-02T16:25:58
309,039,696
0
0
null
null
null
null
UTF-8
C++
false
false
377
cpp
#include <iostream> #include <string> using namespace std; class Human { private: int age; int getAge() { return age-5; } public: void displayAge() { cout << getAge() << endl; } void setAge(int value) { age = value; } }; int main() { Human divyanshu; divyanshu.setAge(24); divyanshu.displayAge(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
933b56c4bfecd9c360750063027875f7c536a271
d8ef5e822414f83a846d2e9244d7affd249cffe0
/thrust/system/cuda/detail/async/exclusive_scan.h
8735f74191c7e3b777582856882d4ba6f7105cd5
[ "Apache-2.0" ]
permissive
pavahora/rocThrust
4c44550b914a388c214151437267d6c4d3388cd4
158c18e7470d10472a1735c75cf8e49a66625a2d
refs/heads/master
2023-09-02T03:17:31.655975
2021-10-27T17:25:47
2021-10-27T17:25:47
424,659,134
0
0
null
null
null
null
UTF-8
C++
false
false
7,019
h
/****************************************************************************** * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include <thrust/detail/config.h> #include <thrust/detail/cpp14_required.h> #if THRUST_CPP_DIALECT >= 2014 #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC #include <thrust/iterator/iterator_traits.h> #include <thrust/system/cuda/config.h> #include <thrust/system/cuda/detail/async/customization.h> #include <thrust/system/cuda/detail/util.h> #include <thrust/system/cuda/future.h> #include <thrust/type_traits/remove_cvref.h> #include <thrust/distance.h> #include <type_traits> // TODO specialize for thrust::plus to use e.g. ExclusiveSum instead of ExcScan // - Note that thrust::plus<> is transparent, cub::Sum is not. This should be // fixed in CUB first). // - Need to check if CUB actually optimizes for sums before putting in effort THRUST_NAMESPACE_BEGIN namespace system { namespace cuda { namespace detail { template <typename DerivedPolicy, typename ForwardIt, typename Size, typename OutputIt, typename InitialValueType, typename BinaryOp> unique_eager_event async_exclusive_scan_n(execution_policy<DerivedPolicy>& policy, ForwardIt first, Size n, OutputIt out, InitialValueType init, BinaryOp op) { using Dispatch32 = cub::DispatchScan<ForwardIt, OutputIt, BinaryOp, InitialValueType, thrust::detail::int32_t>; using Dispatch64 = cub::DispatchScan<ForwardIt, OutputIt, BinaryOp, InitialValueType, thrust::detail::int64_t>; auto const device_alloc = get_async_device_allocator(policy); unique_eager_event ev; // Determine temporary device storage requirements. cudaError_t status; size_t tmp_size = 0; { THRUST_INDEX_TYPE_DISPATCH2(status, Dispatch32::Dispatch, Dispatch64::Dispatch, n, (nullptr, tmp_size, first, out, op, init, n_fixed, nullptr, THRUST_DEBUG_SYNC_FLAG)); thrust::cuda_cub::throw_on_error(status, "after determining tmp storage " "requirements for exclusive_scan"); } // Allocate temporary storage. auto content = uninitialized_allocate_unique_n<thrust::detail::uint8_t>( device_alloc, tmp_size ); void* const tmp_ptr = raw_pointer_cast(content.get()); // Set up stream with dependencies. cudaStream_t const user_raw_stream = thrust::cuda_cub::stream(policy); if (thrust::cuda_cub::default_stream() != user_raw_stream) { ev = make_dependent_event( std::tuple_cat( std::make_tuple( std::move(content), unique_stream(nonowning, user_raw_stream) ), extract_dependencies(std::move(thrust::detail::derived_cast(policy))))); } else { ev = make_dependent_event( std::tuple_cat( std::make_tuple(std::move(content)), extract_dependencies(std::move(thrust::detail::derived_cast(policy))))); } // Run scan. { THRUST_INDEX_TYPE_DISPATCH2(status, Dispatch32::Dispatch, Dispatch64::Dispatch, n, (tmp_ptr, tmp_size, first, out, op, init, n_fixed, user_raw_stream, THRUST_DEBUG_SYNC_FLAG)); thrust::cuda_cub::throw_on_error(status, "after dispatching exclusive_scan kernel"); } return ev; } }}} // namespace system::cuda::detail namespace cuda_cub { // ADL entry point. template <typename DerivedPolicy, typename ForwardIt, typename Sentinel, typename OutputIt, typename InitialValueType, typename BinaryOp> auto async_exclusive_scan(execution_policy<DerivedPolicy>& policy, ForwardIt first, Sentinel&& last, OutputIt&& out, InitialValueType &&init, BinaryOp&& op) THRUST_RETURNS( thrust::system::cuda::detail::async_exclusive_scan_n( policy, first, distance(first, THRUST_FWD(last)), THRUST_FWD(out), THRUST_FWD(init), THRUST_FWD(op) ) ) } // namespace cuda_cub THRUST_NAMESPACE_END #endif // THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC #endif // C++14
[ "noreply@github.com" ]
noreply@github.com
6dc88b5d274ae6bae634655fee9090084c679c5c
37fd62cabffa130f99cd13031644ff36395e8fc7
/timed_commitment/bit_utils.h
c6c917b6f366418ac164bb32baa297f9e2c332a5
[]
no_license
wacban/SellingInformation
5094e683a66aa02268899e72b3cf077289e93631
888c8b4683bdb48b47abfb66ede21c4ebcd8b2be
refs/heads/master
2021-01-13T02:16:07.128018
2016-02-14T22:43:50
2016-02-14T22:43:50
41,244,929
1
0
null
null
null
null
UTF-8
C++
false
false
415
h
#ifndef _BIT_UTILS_H_ #define _BIT_UTILS_H_ #include <vector> #include <string> #include <cryptopp/integer.h> class BitUtils { public: static std::vector<bool> string_to_bits(const std::string&); static std::vector<bool> integer_to_bits(const CryptoPP::Integer&); static std::string bits_to_string(const std::vector<bool> &); static CryptoPP::Integer bits_to_integer(const std::vector<bool> &); }; #endif
[ "wac.banasik@gmail.com" ]
wac.banasik@gmail.com
a7d7a8c98e7b20ac48b6ca9d2d600cdd7518db92
0508304aeb1d50db67a090eecb7436b13f06583d
/nemo/src/test/app_test.cpp
6d7ade42086e24e9eb23d3a491cbaa894414f299
[]
no_license
BackupTheBerlios/nemo
229a7c64901162cf8359f7ddb3a7dd4d05763196
1511021681e9efd91e394191bb00313f0112c628
refs/heads/master
2016-08-03T16:33:46.947041
2004-04-28T01:51:58
2004-04-28T01:51:58
40,045,282
0
0
null
null
null
null
UTF-8
C++
false
false
2,219
cpp
// Standard Includes ----------------------------------------------------------- #include <stdio.h> // System Includes ------------------------------------------------------------- #include <Application.h> #include <Handler.h> #include <Looper.h> #include <OS.h> // Macros ---------------------------------------------------------------------- // Types ----------------------------------------------------------------------- class TApplication: public BApplication { public: //------------------------------------------------------------------------------ TApplication() : BApplication("Test App") { }; //------------------------------------------------------------------------------ virtual ~TApplication() { } //------------------------------------------------------------------------------ void ReadyToRun() { printf("TApplication: In ReadyToRun()\n"); thread_id th = spawn_thread(test_func, "Test Function", B_NORMAL_PRIORITY, NULL); resume_thread(th); } //------------------------------------------------------------------------------ void MessageReceived(BMessage *message) { printf("TApplication: got message %d\n", message->what); BApplication::MessageReceived(message); } //------------------------------------------------------------------------------ static int32 test_func(void *arg) { while(true) { int i; printf("\nEnter message code to send to be_app (-1 to exit): "); scanf("%d", &i); if(i == -1) { be_app->PostMessage(B_QUIT_REQUESTED); break; } be_app->PostMessage(i); } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ }; // Globals --------------------------------------------------------------------- // Function Prototypes --------------------------------------------------------- // Main ------------------------------------------------------------------------ int main(void) { TApplication *app = new TApplication; app->Run(); delete app; return 0; } // Functions -------------------------------------------------------------------
[ "mahmoudfg" ]
mahmoudfg
2b4922209e5f2ffdc506222d27e325de35d48508
f5394bc5f3a76459a9afd34778e6fbee786080ef
/main.cpp
cd035eb4efe84d22c83c10315865cade0e77fe2d
[]
no_license
jacob-pugsley/SimpleCalc
6fba6271488f0d0460d2b225d3416b877653c07d
64213d787f81e2a1a6516c0029146d237374b71d
refs/heads/master
2020-04-02T19:45:03.991978
2018-10-25T22:41:56
2018-10-25T22:41:56
154,745,138
0
0
null
null
null
null
UTF-8
C++
false
false
193
cpp
#include <iostream> #include "ui_calc.h" #include "mainwindow.h" int main( int argc, char *argv[] ){ QApplication app( argc, argv ); MainWindow window; window.show(); return app.exec(); }
[ "jacob.pugsley@wsu.edu" ]
jacob.pugsley@wsu.edu
7b91cf07e51e0ced919075b5d684e20f409ba13e
b0dd7779c225971e71ae12c1093dc75ed9889921
/libs/spirit/test/qi/int3.cpp
d7bba1cf2787fa429c80086b83d8eff9d44e60f2
[ "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
6,899
cpp
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser Copyright (c) 2011 Bryce Lelbach Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #include "int.hpp" #include <boost/spirit/include/qi_rule.hpp> int main() { using spirit_test::test; using spirit_test::test_attr; /////////////////////////////////////////////////////////////////////////// // parameterized signed integer tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::int_; int i; BOOST_TEST(test("123456", int_(123456))); BOOST_TEST(!test("123456", int_(654321))); BOOST_TEST(test_attr("123456", int_(123456), i)); BOOST_TEST(i == 123456); BOOST_TEST(!test_attr("123456", int_(654321), i)); BOOST_TEST(test("+123456", int_(123456))); BOOST_TEST(!test("+123456", int_(654321))); BOOST_TEST(test_attr("+123456", int_(123456), i)); BOOST_TEST(i == 123456); BOOST_TEST(!test_attr("+123456", int_(654321), i)); BOOST_TEST(test("-123456", int_(-123456))); BOOST_TEST(!test("-123456", int_(123456))); BOOST_TEST(test_attr("-123456", int_(-123456), i)); BOOST_TEST(i == -123456); BOOST_TEST(!test_attr("-123456", int_(123456), i)); BOOST_TEST(test(max_int, int_(INT_MAX))); BOOST_TEST(test_attr(max_int, int_(INT_MAX), i)); BOOST_TEST(i == INT_MAX); BOOST_TEST(test(min_int, int_(INT_MIN))); BOOST_TEST(test_attr(min_int, int_(INT_MIN), i)); BOOST_TEST(i == INT_MIN); // with leading zeros BOOST_TEST(test("0000000000123456", int_(123456))); BOOST_TEST(test_attr("0000000000123456", int_(123456), i)); BOOST_TEST(i == 123456); } /////////////////////////////////////////////////////////////////////////// // parameterized long long tests /////////////////////////////////////////////////////////////////////////// #ifdef BOOST_HAS_LONG_LONG { using boost::spirit::long_long; boost::long_long_type ll; BOOST_TEST(test("1234567890123456789" , long_long(1234567890123456789LL))); BOOST_TEST(!test("1234567890123456789" , long_long(0))); BOOST_TEST(test_attr("1234567890123456789" , long_long(1234567890123456789LL), ll)); BOOST_TEST(ll == 1234567890123456789LL); BOOST_TEST(!test_attr("1234567890123456789" , long_long(0), ll)); BOOST_TEST(test("-1234567890123456789" , long_long(-1234567890123456789LL))); BOOST_TEST(!test("-1234567890123456789" , long_long(1234567890123456789LL))); BOOST_TEST(test_attr("-1234567890123456789" , long_long(-1234567890123456789LL), ll)); BOOST_TEST(ll == -1234567890123456789LL); BOOST_TEST(!test_attr("-1234567890123456789" , long_long(1234567890123456789LL), ll)); BOOST_TEST(test(max_long_long, long_long(LONG_LONG_MAX))); BOOST_TEST(test_attr(max_long_long, long_long(LONG_LONG_MAX), ll)); BOOST_TEST(ll == LONG_LONG_MAX); BOOST_TEST(test(min_long_long, long_long(LONG_LONG_MIN))); BOOST_TEST(test_attr(min_long_long, long_long(LONG_LONG_MIN), ll)); BOOST_TEST(ll == LONG_LONG_MIN); } #endif /////////////////////////////////////////////////////////////////////////// // parameterized short_ and long_ tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::short_; using boost::spirit::long_; int i; BOOST_TEST(test("12345", short_(12345))); BOOST_TEST(!test("12345", short_(54321))); BOOST_TEST(test_attr("12345", short_(12345), i)); BOOST_TEST(i == 12345); BOOST_TEST(!test_attr("12345", short_(54321), i)); BOOST_TEST(test("1234567890", long_(1234567890L))); BOOST_TEST(!test("1234567890", long_(987654321L))); BOOST_TEST(test_attr("1234567890", long_(1234567890L), i)); BOOST_TEST(i == 1234567890); BOOST_TEST(!test_attr("1234567890", long_(987654321L), i)); } /////////////////////////////////////////////////////////////////////////// // parameterized action tests /////////////////////////////////////////////////////////////////////////// { using boost::phoenix::ref; using boost::spirit::ascii::space; using boost::spirit::qi::int_; using boost::spirit::qi::_1; int n, m; BOOST_TEST(test("123", int_(123)[ref(n) = _1])); BOOST_TEST(n == 123); BOOST_TEST(!test("123", int_(321)[ref(n) = _1])); BOOST_TEST(test_attr("789", int_(789)[ref(n) = _1], m)); BOOST_TEST(n == 789 && m == 789); BOOST_TEST(!test_attr("789", int_(987)[ref(n) = _1], m)); BOOST_TEST(test(" 456", int_(456)[ref(n) = _1], space)); BOOST_TEST(n == 456); BOOST_TEST(!test(" 456", int_(654)[ref(n) = _1], space)); } /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::int_; using boost::spirit::qi::_1; using boost::spirit::qi::_val; using boost::spirit::qi::space; int i = 0; int j = 0; BOOST_TEST(test_attr("456", int_[_val = _1], i) && i == 456); BOOST_TEST(test_attr(" 456", int_[_val = _1], j, space) && j == 456); } /////////////////////////////////////////////////////////////////////////// // parameterized lazy tests /////////////////////////////////////////////////////////////////////////// { using boost::phoenix::ref; using boost::spirit::qi::int_; int n = 123, m = 321; BOOST_TEST(test("123", int_(ref(n)))); BOOST_TEST(!test("123", int_(ref(m)))); } /////////////////////////////////////////////////////////////////////////// // parameterized custom int tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::int_; using boost::spirit::qi::int_parser; custom_int i; BOOST_TEST(test_attr("-123456", int_(-123456), i)); int_parser<custom_int, 10, 1, 2> int2; BOOST_TEST(test_attr("-12", int2(-12), i)); } return boost::report_errors(); }
[ "tvaneerd@rim.com" ]
tvaneerd@rim.com
f31c09b26ed4c0d984a543188dbcef18e5888fe7
485156ab080907777c4dca48e1ca9c2cf0770d52
/Olymp/HSE/2018/9-10/demo2/A/tests_gen.cpp
ee3d0657de1ed5094e9308df35626a83e4fe2b95
[]
no_license
AleksanderKirintsev/study
33957bcf1c911a00bcac585f644440ef8311e9a1
70e1be6171d08b7faed184254db4b0d9a661c45f
refs/heads/master
2022-02-04T09:08:56.162788
2020-04-21T16:16:15
2020-04-21T16:16:15
141,019,743
0
0
null
2022-01-22T14:13:28
2018-07-15T10:54:45
C++
UTF-8
C++
false
false
1,071
cpp
#include <iostream> #include <cstdlib> #include <ctime> #include <fstream> #include <string> using namespace std; #define NLIM 10 #define TLIM 10 int main() { int n, h[10], m[10], s[10], ans; srand ( time ( NULL ) ); for ( int t = 3; t < TLIM; t++ ) { n = 1 + rand() % NLIM; cout << n << endl; for ( int i = 0; i < n; i++ ) { h[i] = rand() % 24; m[i] = rand() % 60; s[i] = rand() % 60; cout << h[i]/10 << h[i]%10 << ":" << m[i]/10 << m[i]%10 << ":" << s[i]/10 << s[i]%10 << endl; } cin >> ans; cout << endl; ofstream infile ( "tests\\" + to_string ( t / 10 ) + to_string ( t ) ); infile << n << endl; for ( int i = 0; i < n; i++ ) { infile << h[i]/10 << h[i]%10 << ":" << m[i]/10 << m[i]%10 << ":" << s[i]/10 << s[i]%10 << endl; } infile.close(); ofstream afile ( "tests\\" + to_string ( t / 10 ) + to_string ( t ) + ".a" ); afile << ans; afile.close(); } return 0; }
[ "kirintsev00@mail.ru" ]
kirintsev00@mail.ru
d9943f473fe33fd0daa0f4e38eac9718c85d1be0
5a2fc075dae6635adf76bc664f2fae357cfbec65
/Zone.h
edd50e903aadcd0b7da253b5aed4ace10ff14b91
[]
no_license
JinxedNation/C-Food-Game
58638ce2922da24d619ec2e758bec72c63334b5d
527351b8ed2a954e5a13944052e72d1414180990
refs/heads/master
2023-01-01T16:18:13.820557
2020-10-27T13:54:49
2020-10-27T13:54:49
307,641,414
0
0
null
null
null
null
UTF-8
C++
false
false
987
h
#pragma once #include<glm.hpp> #include<GL/glut.h> #include"BoundingBox.h" #include"Object.h" class Zone { public: Zone() {} Zone(glm::vec3 mX, glm::vec3 mN); void SetMax(glm::vec3 pos) { max = pos; } void SetMin(glm::vec3 pos) { min = pos; } glm::vec3 GetMax() const { return max; } glm::vec3 GetMin() const { return min; } void SetZoneBox(BoundingBox b) { zoneBox = b; } BoundingBox GetZoneBox() const { return zoneBox; } void SetColour(glm::vec3 c) { colour = c; } glm::vec3 GetColour() const { return colour; } void SetPlayer(glm::vec3 p) { player = p; } glm::vec3 GetPlayer() const { return player; } void Update(); void SetInZone(bool z) { inZone = z; } bool GetInZOne() const { return inZone; } void SetActive(bool z) { active = z; } bool GetActive() const { return active; } void Change(glm::vec3 mX, glm::vec3 mN); private: bool active; glm::vec3 max; glm::vec3 min; BoundingBox zoneBox; glm::vec3 colour; glm::vec3 player; bool inZone; };
[ "noreply@github.com" ]
noreply@github.com
7cfea44bfe8d0150cf494cae7b26b0d45589169d
298eed34e7d74b1db43cb512a009377656d5cf6c
/CritterGroupGenerator/CritterGroupGenerator/src/gameObjects/CritterWave.cpp
08a31e52f5deff4a3a85e623c1708cfd640bf0c7
[ "MIT" ]
permissive
sli-fox/A1
c796e03b0e97580310502846400c23b5d815c569
55b4296ef8c479d8407e743f01bd9b0d5a8d9e2e
refs/heads/master
2020-04-29T09:19:45.922851
2014-10-21T09:20:23
2014-10-21T09:20:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,579
cpp
#include <CritterWave.h> /** @brief This constructor sets the type and number of critters * for the wave. */ CritterWave::CritterWave(int numOfCritters, CritterFactory::CritterType type) : numOfCritters(numOfCritters), type(type) { } /** @brief This destructor iterates through the map, calling a deallocator which deletes * Critter* references in a wave. */ CritterWave::~CritterWave() { for_each(_m_critter_wave.begin(), _m_critter_wave.end(), CritterWaveDeallocator()); } void CritterWave::addCritter(int id, Critter* critter) { _m_critter_wave.insert(std::pair<int, Critter*>(id, critter)); } /** Iterate through the map, looking for the given Critter id, * if found, delete the pointer and remove the Critter* from the map. */ void CritterWave::removeCritter(int id) { std::map<int, Critter*>::iterator results = _m_critter_wave.find(id); if (results != _m_critter_wave.end()) { delete results->second; _m_critter_wave.erase(results); } } /** Iterate through the map, looking for the given Critter id. * If end of map is reached, return null, else return the Critter*. */ Critter* CritterWave::findCritter(int id) const { std::map<int, Critter*>::const_iterator results = _m_critter_wave.find(id); if (results == _m_critter_wave.end()) return NULL; return results->second; } int CritterWave::getCritterCount() const { return _m_critter_wave.size(); } void CritterWave::spawnAtStartCell(int critter_id, int row, int col) { this->findCritter(critter_id)->row = row; this->findCritter(critter_id)->col = col; }
[ "stephanie.zhongsui.li@gmail.com" ]
stephanie.zhongsui.li@gmail.com
9eee2483ebcd3e360cf8c24c49a8dfde2f4e2eb0
87cc68a0f70ecefb07ab35ad8cb2474299ff895c
/isisdaeApp/src/MonitorSpectrumPV.cpp
09035c82fe1a60078d9e79b83af5282d53c98798
[]
no_license
ISISComputingGroup/EPICS-isisdae
0515c90a7c3983ebed3e0f5a2dd0243e7389fa9c
37cdec60674ac7de508faa777f8cca0df989e25d
refs/heads/master
2023-08-31T07:19:12.482864
2023-08-25T12:09:04
2023-08-25T12:09:04
40,836,791
0
0
null
2023-08-25T12:09:06
2015-08-16T19:49:20
C++
UTF-8
C++
false
false
1,022
cpp
#include "exServer.h" #include "gddApps.h" #include "isisdaeInterface.h" MonitorSpectrumPV::MonitorSpectrumPV(exServer & cas, pvInfo &setup, bool preCreateFlag, bool scanOnIn, const std::string& axis, int mon, int period) : SpectrumPV(cas, setup, preCreateFlag, scanOnIn, axis, 0/*spec*/, period), m_monitor(mon) { updateSpectrum(); } bool MonitorSpectrumPV::getNewValue(smartGDDPointer& pDD) { if (updateSpectrum()) { return SpectrumPV::getNewValue(pDD); } else { return false; } } bool MonitorSpectrumPV::updateSpectrum() { try { m_spec = cas.iface()->getSpectrumNumberForMonitor(m_monitor); } catch(const std::exception& ex) { m_spec = 0; std::cerr << "CAS: Exception in MonitorSpectrumPV::updateSpectrum(): " << ex.what() << std::endl; return false; } catch(...) { m_spec = 0; std::cerr << "CAS: Exception in MonitorSpectrumPV::updateSpectrum()" << std::endl; return false; } return true; }
[ "freddie.akeroyd@stfc.ac.uk" ]
freddie.akeroyd@stfc.ac.uk
869f00768cbc0bd906f662b285304af6d6b952f2
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/net/http/http_auth_cache_unittest.cc
c0509ce1d50c1d323e8c45aca802e679bcdfa43a
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
23,144
cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "net/base/net_errors.h" #include "net/http/http_auth_cache.h" #include "net/http/http_auth_handler.h" #include "testing/gtest/include/gtest/gtest.h" using base::ASCIIToUTF16; namespace net { namespace { class MockAuthHandler : public HttpAuthHandler { public: MockAuthHandler(HttpAuth::Scheme scheme, const std::string& realm, HttpAuth::Target target) { // Can't use initializer list since these are members of the base class. auth_scheme_ = scheme; realm_ = realm; score_ = 1; target_ = target; properties_ = 0; } HttpAuth::AuthorizationResult HandleAnotherChallenge( HttpAuthChallengeTokenizer* challenge) override { return HttpAuth::AUTHORIZATION_RESULT_REJECT; } protected: bool Init(HttpAuthChallengeTokenizer* challenge, const SSLInfo& ssl_info) override { return false; // Unused. } int GenerateAuthTokenImpl(const AuthCredentials*, const HttpRequestInfo*, const CompletionCallback& callback, std::string* auth_token) override { *auth_token = "mock-credentials"; return OK; } private: ~MockAuthHandler() override {} }; const char kRealm1[] = "Realm1"; const char kRealm2[] = "Realm2"; const char kRealm3[] = "Realm3"; const char kRealm4[] = "Realm4"; const char kRealm5[] = "Realm5"; const base::string16 k123(ASCIIToUTF16("123")); const base::string16 k1234(ASCIIToUTF16("1234")); const base::string16 kAdmin(ASCIIToUTF16("admin")); const base::string16 kAlice(ASCIIToUTF16("alice")); const base::string16 kAlice2(ASCIIToUTF16("alice2")); const base::string16 kPassword(ASCIIToUTF16("password")); const base::string16 kRoot(ASCIIToUTF16("root")); const base::string16 kUsername(ASCIIToUTF16("username")); const base::string16 kWileCoyote(ASCIIToUTF16("wilecoyote")); AuthCredentials CreateASCIICredentials(const char* username, const char* password) { return AuthCredentials(ASCIIToUTF16(username), ASCIIToUTF16(password)); } } // namespace // Test adding and looking-up cache entries (both by realm and by path). TEST(HttpAuthCacheTest, Basic) { GURL origin("http://www.google.com"); HttpAuthCache cache; HttpAuthCache::Entry* entry; // Add cache entries for 4 realms: "Realm1", "Realm2", "Realm3" and // "Realm4" std::unique_ptr<HttpAuthHandler> realm1_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm1, HttpAuth::AUTH_SERVER)); cache.Add(origin, realm1_handler->realm(), realm1_handler->auth_scheme(), "Basic realm=Realm1", CreateASCIICredentials("realm1-user", "realm1-password"), "/foo/bar/index.html"); std::unique_ptr<HttpAuthHandler> realm2_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm2, HttpAuth::AUTH_SERVER)); cache.Add(origin, realm2_handler->realm(), realm2_handler->auth_scheme(), "Basic realm=Realm2", CreateASCIICredentials("realm2-user", "realm2-password"), "/foo2/index.html"); std::unique_ptr<HttpAuthHandler> realm3_basic_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm3, HttpAuth::AUTH_PROXY)); cache.Add( origin, realm3_basic_handler->realm(), realm3_basic_handler->auth_scheme(), "Basic realm=Realm3", CreateASCIICredentials("realm3-basic-user", "realm3-basic-password"), std::string()); std::unique_ptr<HttpAuthHandler> realm3_digest_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_DIGEST, kRealm3, HttpAuth::AUTH_PROXY)); cache.Add(origin, realm3_digest_handler->realm(), realm3_digest_handler->auth_scheme(), "Digest realm=Realm3", CreateASCIICredentials("realm3-digest-user", "realm3-digest-password"), "/baz/index.html"); std::unique_ptr<HttpAuthHandler> realm4_basic_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm4, HttpAuth::AUTH_SERVER)); cache.Add(origin, realm4_basic_handler->realm(), realm4_basic_handler->auth_scheme(), "Basic realm=Realm4", CreateASCIICredentials("realm4-basic-user", "realm4-basic-password"), "/"); // There is no Realm5 entry = cache.Lookup(origin, kRealm5, HttpAuth::AUTH_SCHEME_BASIC); EXPECT_TRUE(NULL == entry); // While Realm3 does exist, the origin scheme is wrong. entry = cache.Lookup(GURL("https://www.google.com"), kRealm3, HttpAuth::AUTH_SCHEME_BASIC); EXPECT_TRUE(NULL == entry); // Realm, origin scheme ok, authentication scheme wrong entry = cache.Lookup (GURL("http://www.google.com"), kRealm1, HttpAuth::AUTH_SCHEME_DIGEST); EXPECT_TRUE(NULL == entry); // Valid lookup by origin, realm, scheme. entry = cache.Lookup( GURL("http://www.google.com:80"), kRealm3, HttpAuth::AUTH_SCHEME_BASIC); ASSERT_FALSE(NULL == entry); EXPECT_EQ(HttpAuth::AUTH_SCHEME_BASIC, entry->scheme()); EXPECT_EQ(kRealm3, entry->realm()); EXPECT_EQ("Basic realm=Realm3", entry->auth_challenge()); EXPECT_EQ(ASCIIToUTF16("realm3-basic-user"), entry->credentials().username()); EXPECT_EQ(ASCIIToUTF16("realm3-basic-password"), entry->credentials().password()); // Valid lookup by origin, realm, scheme when there's a duplicate // origin, realm in the cache entry = cache.Lookup( GURL("http://www.google.com:80"), kRealm3, HttpAuth::AUTH_SCHEME_DIGEST); ASSERT_FALSE(NULL == entry); EXPECT_EQ(HttpAuth::AUTH_SCHEME_DIGEST, entry->scheme()); EXPECT_EQ(kRealm3, entry->realm()); EXPECT_EQ("Digest realm=Realm3", entry->auth_challenge()); EXPECT_EQ(ASCIIToUTF16("realm3-digest-user"), entry->credentials().username()); EXPECT_EQ(ASCIIToUTF16("realm3-digest-password"), entry->credentials().password()); // Valid lookup by realm. entry = cache.Lookup(origin, kRealm2, HttpAuth::AUTH_SCHEME_BASIC); ASSERT_FALSE(NULL == entry); EXPECT_EQ(HttpAuth::AUTH_SCHEME_BASIC, entry->scheme()); EXPECT_EQ(kRealm2, entry->realm()); EXPECT_EQ("Basic realm=Realm2", entry->auth_challenge()); EXPECT_EQ(ASCIIToUTF16("realm2-user"), entry->credentials().username()); EXPECT_EQ(ASCIIToUTF16("realm2-password"), entry->credentials().password()); // Check that subpaths are recognized. HttpAuthCache::Entry* realm2_entry = cache.Lookup( origin, kRealm2, HttpAuth::AUTH_SCHEME_BASIC); HttpAuthCache::Entry* realm4_entry = cache.Lookup( origin, kRealm4, HttpAuth::AUTH_SCHEME_BASIC); EXPECT_FALSE(NULL == realm2_entry); EXPECT_FALSE(NULL == realm4_entry); // Realm4 applies to '/' and Realm2 applies to '/foo2/'. // LookupByPath() should return the closest enclosing path. // Positive tests: entry = cache.LookupByPath(origin, "/foo2/index.html"); EXPECT_TRUE(realm2_entry == entry); entry = cache.LookupByPath(origin, "/foo2/foobar.html"); EXPECT_TRUE(realm2_entry == entry); entry = cache.LookupByPath(origin, "/foo2/bar/index.html"); EXPECT_TRUE(realm2_entry == entry); entry = cache.LookupByPath(origin, "/foo2/"); EXPECT_TRUE(realm2_entry == entry); entry = cache.LookupByPath(origin, "/foo2"); EXPECT_TRUE(realm4_entry == entry); entry = cache.LookupByPath(origin, "/"); EXPECT_TRUE(realm4_entry == entry); // Negative tests: entry = cache.LookupByPath(origin, "/foo3/index.html"); EXPECT_FALSE(realm2_entry == entry); entry = cache.LookupByPath(origin, std::string()); EXPECT_FALSE(realm2_entry == entry); // Confirm we find the same realm, different auth scheme by path lookup HttpAuthCache::Entry* realm3_digest_entry = cache.Lookup(origin, kRealm3, HttpAuth::AUTH_SCHEME_DIGEST); EXPECT_FALSE(NULL == realm3_digest_entry); entry = cache.LookupByPath(origin, "/baz/index.html"); EXPECT_TRUE(realm3_digest_entry == entry); entry = cache.LookupByPath(origin, "/baz/"); EXPECT_TRUE(realm3_digest_entry == entry); entry = cache.LookupByPath(origin, "/baz"); EXPECT_FALSE(realm3_digest_entry == entry); // Confirm we find the same realm, different auth scheme by path lookup HttpAuthCache::Entry* realm3DigestEntry = cache.Lookup(origin, kRealm3, HttpAuth::AUTH_SCHEME_DIGEST); EXPECT_FALSE(NULL == realm3DigestEntry); entry = cache.LookupByPath(origin, "/baz/index.html"); EXPECT_TRUE(realm3DigestEntry == entry); entry = cache.LookupByPath(origin, "/baz/"); EXPECT_TRUE(realm3DigestEntry == entry); entry = cache.LookupByPath(origin, "/baz"); EXPECT_FALSE(realm3DigestEntry == entry); // Lookup using empty path (may be used for proxy). entry = cache.LookupByPath(origin, std::string()); EXPECT_FALSE(NULL == entry); EXPECT_EQ(HttpAuth::AUTH_SCHEME_BASIC, entry->scheme()); EXPECT_EQ(kRealm3, entry->realm()); } TEST(HttpAuthCacheTest, AddPath) { HttpAuthCache::Entry entry; // All of these paths have a common root /1/2/2/4/5/ entry.AddPath("/1/2/3/4/5/x.txt"); entry.AddPath("/1/2/3/4/5/y.txt"); entry.AddPath("/1/2/3/4/5/z.txt"); EXPECT_EQ(1U, entry.paths_.size()); EXPECT_EQ("/1/2/3/4/5/", entry.paths_.front()); // Add a new entry (not a subpath). entry.AddPath("/1/XXX/q"); EXPECT_EQ(2U, entry.paths_.size()); EXPECT_EQ("/1/XXX/", entry.paths_.front()); EXPECT_EQ("/1/2/3/4/5/", entry.paths_.back()); // Add containing paths of /1/2/3/4/5/ -- should swallow up the deeper paths. entry.AddPath("/1/2/3/4/x.txt"); EXPECT_EQ(2U, entry.paths_.size()); EXPECT_EQ("/1/2/3/4/", entry.paths_.front()); EXPECT_EQ("/1/XXX/", entry.paths_.back()); entry.AddPath("/1/2/3/x"); EXPECT_EQ(2U, entry.paths_.size()); EXPECT_EQ("/1/2/3/", entry.paths_.front()); EXPECT_EQ("/1/XXX/", entry.paths_.back()); entry.AddPath("/index.html"); EXPECT_EQ(1U, entry.paths_.size()); EXPECT_EQ("/", entry.paths_.front()); } // Calling Add when the realm entry already exists, should append that // path. TEST(HttpAuthCacheTest, AddToExistingEntry) { HttpAuthCache cache; GURL origin("http://www.foobar.com:70"); const std::string auth_challenge = "Basic realm=MyRealm"; std::unique_ptr<HttpAuthHandler> handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, "MyRealm", HttpAuth::AUTH_SERVER)); HttpAuthCache::Entry* orig_entry = cache.Add( origin, handler->realm(), handler->auth_scheme(), auth_challenge, CreateASCIICredentials("user1", "password1"), "/x/y/z/"); cache.Add(origin, handler->realm(), handler->auth_scheme(), auth_challenge, CreateASCIICredentials("user2", "password2"), "/z/y/x/"); cache.Add(origin, handler->realm(), handler->auth_scheme(), auth_challenge, CreateASCIICredentials("user3", "password3"), "/z/y"); HttpAuthCache::Entry* entry = cache.Lookup( origin, "MyRealm", HttpAuth::AUTH_SCHEME_BASIC); EXPECT_TRUE(entry == orig_entry); EXPECT_EQ(ASCIIToUTF16("user3"), entry->credentials().username()); EXPECT_EQ(ASCIIToUTF16("password3"), entry->credentials().password()); EXPECT_EQ(2U, entry->paths_.size()); EXPECT_EQ("/z/", entry->paths_.front()); EXPECT_EQ("/x/y/z/", entry->paths_.back()); } TEST(HttpAuthCacheTest, Remove) { GURL origin("http://foobar2.com"); std::unique_ptr<HttpAuthHandler> realm1_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm1, HttpAuth::AUTH_SERVER)); std::unique_ptr<HttpAuthHandler> realm2_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm2, HttpAuth::AUTH_SERVER)); std::unique_ptr<HttpAuthHandler> realm3_basic_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm3, HttpAuth::AUTH_SERVER)); std::unique_ptr<HttpAuthHandler> realm3_digest_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_DIGEST, kRealm3, HttpAuth::AUTH_SERVER)); HttpAuthCache cache; cache.Add(origin, realm1_handler->realm(), realm1_handler->auth_scheme(), "basic realm=Realm1", AuthCredentials(kAlice, k123), "/"); cache.Add(origin, realm2_handler->realm(), realm2_handler->auth_scheme(), "basic realm=Realm2", CreateASCIICredentials("bob", "princess"), "/"); cache.Add(origin, realm3_basic_handler->realm(), realm3_basic_handler->auth_scheme(), "basic realm=Realm3", AuthCredentials(kAdmin, kPassword), "/"); cache.Add(origin, realm3_digest_handler->realm(), realm3_digest_handler->auth_scheme(), "digest realm=Realm3", AuthCredentials(kRoot, kWileCoyote), "/"); // Fails, because there is no realm "Realm5". EXPECT_FALSE(cache.Remove( origin, kRealm5, HttpAuth::AUTH_SCHEME_BASIC, AuthCredentials(kAlice, k123))); // Fails because the origin is wrong. EXPECT_FALSE(cache.Remove(GURL("http://foobar2.com:100"), kRealm1, HttpAuth::AUTH_SCHEME_BASIC, AuthCredentials(kAlice, k123))); // Fails because the username is wrong. EXPECT_FALSE(cache.Remove( origin, kRealm1, HttpAuth::AUTH_SCHEME_BASIC, AuthCredentials(kAlice2, k123))); // Fails because the password is wrong. EXPECT_FALSE(cache.Remove( origin, kRealm1, HttpAuth::AUTH_SCHEME_BASIC, AuthCredentials(kAlice, k1234))); // Fails because the authentication type is wrong. EXPECT_FALSE(cache.Remove( origin, kRealm1, HttpAuth::AUTH_SCHEME_DIGEST, AuthCredentials(kAlice, k123))); // Succeeds. EXPECT_TRUE(cache.Remove( origin, kRealm1, HttpAuth::AUTH_SCHEME_BASIC, AuthCredentials(kAlice, k123))); // Fails because we just deleted the entry! EXPECT_FALSE(cache.Remove( origin, kRealm1, HttpAuth::AUTH_SCHEME_BASIC, AuthCredentials(kAlice, k123))); // Succeed when there are two authentication types for the same origin,realm. EXPECT_TRUE(cache.Remove( origin, kRealm3, HttpAuth::AUTH_SCHEME_DIGEST, AuthCredentials(kRoot, kWileCoyote))); // Succeed as above, but when entries were added in opposite order cache.Add(origin, realm3_digest_handler->realm(), realm3_digest_handler->auth_scheme(), "digest realm=Realm3", AuthCredentials(kRoot, kWileCoyote), "/"); EXPECT_TRUE(cache.Remove( origin, kRealm3, HttpAuth::AUTH_SCHEME_BASIC, AuthCredentials(kAdmin, kPassword))); // Make sure that removing one entry still leaves the other available for // lookup. HttpAuthCache::Entry* entry = cache.Lookup( origin, kRealm3, HttpAuth::AUTH_SCHEME_DIGEST); EXPECT_FALSE(NULL == entry); } TEST(HttpAuthCacheTest, UpdateStaleChallenge) { HttpAuthCache cache; GURL origin("http://foobar2.com"); std::unique_ptr<HttpAuthHandler> digest_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_DIGEST, kRealm1, HttpAuth::AUTH_PROXY)); HttpAuthCache::Entry* entry_pre = cache.Add( origin, digest_handler->realm(), digest_handler->auth_scheme(), "Digest realm=Realm1," "nonce=\"s3MzvFhaBAA=4c520af5acd9d8d7ae26947529d18c8eae1e98f4\"", CreateASCIICredentials("realm-digest-user", "realm-digest-password"), "/baz/index.html"); ASSERT_TRUE(entry_pre != NULL); EXPECT_EQ(2, entry_pre->IncrementNonceCount()); EXPECT_EQ(3, entry_pre->IncrementNonceCount()); EXPECT_EQ(4, entry_pre->IncrementNonceCount()); bool update_success = cache.UpdateStaleChallenge( origin, digest_handler->realm(), digest_handler->auth_scheme(), "Digest realm=Realm1," "nonce=\"claGgoRXBAA=7583377687842fdb7b56ba0555d175baa0b800e3\"," "stale=\"true\""); EXPECT_TRUE(update_success); // After the stale update, the entry should still exist in the cache and // the nonce count should be reset to 0. HttpAuthCache::Entry* entry_post = cache.Lookup( origin, digest_handler->realm(), digest_handler->auth_scheme()); ASSERT_TRUE(entry_post != NULL); EXPECT_EQ(2, entry_post->IncrementNonceCount()); // UpdateStaleChallenge will fail if an entry doesn't exist in the cache. bool update_failure = cache.UpdateStaleChallenge( origin, kRealm2, digest_handler->auth_scheme(), "Digest realm=Realm2," "nonce=\"claGgoRXBAA=7583377687842fdb7b56ba0555d175baa0b800e3\"," "stale=\"true\""); EXPECT_FALSE(update_failure); } TEST(HttpAuthCacheTest, UpdateAllFrom) { GURL origin("http://example.com"); std::string path("/some/path"); std::string another_path("/another/path"); std::unique_ptr<HttpAuthHandler> realm1_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm1, HttpAuth::AUTH_SERVER)); std::unique_ptr<HttpAuthHandler> realm2_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm2, HttpAuth::AUTH_PROXY)); std::unique_ptr<HttpAuthHandler> realm3_digest_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_DIGEST, kRealm3, HttpAuth::AUTH_SERVER)); std::unique_ptr<HttpAuthHandler> realm4_handler(new MockAuthHandler( HttpAuth::AUTH_SCHEME_BASIC, kRealm4, HttpAuth::AUTH_SERVER)); HttpAuthCache first_cache; HttpAuthCache::Entry* entry; first_cache.Add(origin, realm1_handler->realm(), realm1_handler->auth_scheme(), "basic realm=Realm1", AuthCredentials(kAlice, k123), path); first_cache.Add(origin, realm2_handler->realm(), realm2_handler->auth_scheme(), "basic realm=Realm2", AuthCredentials(kAlice2, k1234), path); first_cache.Add(origin, realm3_digest_handler->realm(), realm3_digest_handler->auth_scheme(), "digest realm=Realm3", AuthCredentials(kRoot, kWileCoyote), path); entry = first_cache.Add( origin, realm3_digest_handler->realm(), realm3_digest_handler->auth_scheme(), "digest realm=Realm3", AuthCredentials(kRoot, kWileCoyote), another_path); EXPECT_EQ(2, entry->IncrementNonceCount()); HttpAuthCache second_cache; // Will be overwritten by kRoot:kWileCoyote. second_cache.Add(origin, realm3_digest_handler->realm(), realm3_digest_handler->auth_scheme(), "digest realm=Realm3", AuthCredentials(kAlice2, k1234), path); // Should be left intact. second_cache.Add(origin, realm4_handler->realm(), realm4_handler->auth_scheme(), "basic realm=Realm4", AuthCredentials(kAdmin, kRoot), path); second_cache.UpdateAllFrom(first_cache); // Copied from first_cache. entry = second_cache.Lookup(origin, kRealm1, HttpAuth::AUTH_SCHEME_BASIC); EXPECT_TRUE(NULL != entry); EXPECT_EQ(kAlice, entry->credentials().username()); EXPECT_EQ(k123, entry->credentials().password()); // Copied from first_cache. entry = second_cache.Lookup(origin, kRealm2, HttpAuth::AUTH_SCHEME_BASIC); EXPECT_TRUE(NULL != entry); EXPECT_EQ(kAlice2, entry->credentials().username()); EXPECT_EQ(k1234, entry->credentials().password()); // Overwritten from first_cache. entry = second_cache.Lookup(origin, kRealm3, HttpAuth::AUTH_SCHEME_DIGEST); EXPECT_TRUE(NULL != entry); EXPECT_EQ(kRoot, entry->credentials().username()); EXPECT_EQ(kWileCoyote, entry->credentials().password()); // Nonce count should get copied. EXPECT_EQ(3, entry->IncrementNonceCount()); // All paths should get copied. entry = second_cache.LookupByPath(origin, another_path); EXPECT_TRUE(NULL != entry); EXPECT_EQ(kRoot, entry->credentials().username()); EXPECT_EQ(kWileCoyote, entry->credentials().password()); // Left intact in second_cache. entry = second_cache.Lookup(origin, kRealm4, HttpAuth::AUTH_SCHEME_BASIC); EXPECT_TRUE(NULL != entry); EXPECT_EQ(kAdmin, entry->credentials().username()); EXPECT_EQ(kRoot, entry->credentials().password()); } // Test fixture class for eviction tests (contains helpers for bulk // insertion and existence testing). class HttpAuthCacheEvictionTest : public testing::Test { protected: HttpAuthCacheEvictionTest() : origin_("http://www.google.com") { } std::string GenerateRealm(int realm_i) { return base::StringPrintf("Realm %d", realm_i); } std::string GeneratePath(int realm_i, int path_i) { return base::StringPrintf("/%d/%d/x/y", realm_i, path_i); } void AddRealm(int realm_i) { AddPathToRealm(realm_i, 0); } void AddPathToRealm(int realm_i, int path_i) { cache_.Add(origin_, GenerateRealm(realm_i), HttpAuth::AUTH_SCHEME_BASIC, std::string(), AuthCredentials(kUsername, kPassword), GeneratePath(realm_i, path_i)); } void CheckRealmExistence(int realm_i, bool exists) { const HttpAuthCache::Entry* entry = cache_.Lookup( origin_, GenerateRealm(realm_i), HttpAuth::AUTH_SCHEME_BASIC); if (exists) { EXPECT_FALSE(entry == NULL); EXPECT_EQ(GenerateRealm(realm_i), entry->realm()); } else { EXPECT_TRUE(entry == NULL); } } void CheckPathExistence(int realm_i, int path_i, bool exists) { const HttpAuthCache::Entry* entry = cache_.LookupByPath(origin_, GeneratePath(realm_i, path_i)); if (exists) { EXPECT_FALSE(entry == NULL); EXPECT_EQ(GenerateRealm(realm_i), entry->realm()); } else { EXPECT_TRUE(entry == NULL); } } GURL origin_; HttpAuthCache cache_; static const int kMaxPaths = HttpAuthCache::kMaxNumPathsPerRealmEntry; static const int kMaxRealms = HttpAuthCache::kMaxNumRealmEntries; }; // Add the maxinim number of realm entries to the cache. Each of these entries // must still be retrievable. Next add three more entries -- since the cache is // full this causes FIFO eviction of the first three entries. TEST_F(HttpAuthCacheEvictionTest, RealmEntryEviction) { for (int i = 0; i < kMaxRealms; ++i) AddRealm(i); for (int i = 0; i < kMaxRealms; ++i) CheckRealmExistence(i, true); for (int i = 0; i < 3; ++i) AddRealm(i + kMaxRealms); for (int i = 0; i < 3; ++i) CheckRealmExistence(i, false); for (int i = 0; i < kMaxRealms; ++i) CheckRealmExistence(i + 3, true); } // Add the maximum number of paths to a single realm entry. Each of these // paths should be retrievable. Next add 3 more paths -- since the cache is // full this causes FIFO eviction of the first three paths. TEST_F(HttpAuthCacheEvictionTest, RealmPathEviction) { for (int i = 0; i < kMaxPaths; ++i) AddPathToRealm(0, i); for (int i = 1; i < kMaxRealms; ++i) AddRealm(i); for (int i = 0; i < 3; ++i) AddPathToRealm(0, i + kMaxPaths); for (int i = 0; i < 3; ++i) CheckPathExistence(0, i, false); for (int i = 0; i < kMaxPaths; ++i) CheckPathExistence(0, i + 3, true); for (int i = 0; i < kMaxRealms; ++i) CheckRealmExistence(i, true); } } // namespace net
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
94390089095c75277e46a6e20f90dc406908886d
f0ea79491cfb50e917fda11c4f04f3171b59fb25
/gematria.h
ba167c2ce2cfdea420f85d0e059c92394edc8a78
[ "Unlicense" ]
permissive
pigeonism/gtk-gematria-old
eb8655af161ed83616c772b98175ff7823732957
25482d2c81e82a5c97d5159a8439d7e94ce9831f
refs/heads/master
2022-12-03T05:39:01.391722
2020-08-14T18:03:32
2020-08-14T18:03:32
287,594,184
0
0
null
2020-08-14T18:02:14
2020-08-14T18:01:18
null
UTF-8
C++
false
false
496
h
#ifndef GEMATRIA_H #define GEMATRIA_H #include <string> using namespace std; class gematria { public: gematria(); virtual ~gematria(); int check_alpha(char letter, string method); void testShorten(); void numerate(string msg); void setMethod(string method); string getResult(); protected: private: string alpha; int total; string useMethod; string numeratedText; }; #endif // GEMATRIA_H
[ "noreply@github.com" ]
noreply@github.com
91f15afebb06afdb1e8fa0bb397d28303f2206ac
b305b0166f5b8a59bbf5c21d91b17e69f69605f2
/客户端组件/游戏广场/DlgTablePassword.cpp
76f01a4a0345f434d4c24324f006752d45b1f706
[]
no_license
daxingyou/CPFrom
22da827e6b77ec84b7984ed5519abc97ac3b65be
434015e1df062ee345cc49b7c3cb663c466dc55f
refs/heads/master
2021-12-10T10:28:41.732011
2016-08-11T03:00:04
2016-08-11T03:00:04
null
0
0
null
null
null
null
GB18030
C++
false
false
2,268
cpp
#include "Stdafx.h" #include "DlgTablePassword.h" ////////////////////////////////////////////////////////////////////////// BEGIN_MESSAGE_MAP(CDlgTablePassword, CSkinDialog) END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////////// //构造函数 CDlgTablePassword::CDlgTablePassword() : CSkinDialog(IDD_DLG_TABLE_PASSWORD) { //设置变量 ZeroMemory(m_szString,sizeof(m_szString)); ZeroMemory(m_szPassword,sizeof(m_szPassword)); return; } //析构函数 CDlgTablePassword::~CDlgTablePassword() { } //控件绑定 VOID CDlgTablePassword::DoDataExchange(CDataExchange * pDX) { __super::DoDataExchange(pDX); //按钮控件 DDX_Control(pDX, IDOK, m_btOk); DDX_Control(pDX, IDCANCEL, m_btCancel); //其他控件 DDX_Control(pDX, IDC_STRING, m_stString); DDX_Control(pDX, IDC_PASSWORD, m_edPassword); } //配置函数 BOOL CDlgTablePassword::OnInitDialog() { __super::OnInitDialog(); //设置标题 SetWindowText(TEXT("桌子密码")); //设置提示 m_stString.SetWindowText(m_szString); //限制输入 m_edPassword.LimitText(LEN_PASSWORD-1); m_edPassword.SetWindowText(m_szPassword); return FALSE; } //确定函数 VOID CDlgTablePassword::OnOK() { //需要密码判断 bool bNeed = (m_szPassword[0]==0); //获取密码 m_edPassword.GetWindowText(m_szPassword,CountArray(m_szPassword)); //密码判断 if (bNeed && m_szPassword[0]==0) { //提示消息 CInformation Information(this); Information.ShowMessageBox(TEXT("游戏桌密码不能为空,请重新输入!"),MB_ICONINFORMATION); //设置焦点 m_edPassword.SetFocus(); return; } __super::OnOK(); } //绘画消息 VOID CDlgTablePassword::OnDrawClientArea(CDC * pDC, INT nWidth, INT nHeight) { //加载资源 CPngImageSB ImageTablePasswd; ImageTablePasswd.LoadImage(AfxGetInstanceHandle(),TEXT("TABLE_PASSWORD")); //绘画图标 ImageTablePasswd.DrawImage(pDC,25,70); return; } //设置提示 VOID CDlgTablePassword::SetPromptString(LPCTSTR pszString) { //设置控件 if (m_stString.m_hWnd!=NULL) { m_stString.SetWindowText(pszString); } //设置提示 lstrcpyn(m_szString,pszString,CountArray(m_szString)); return; } //////////////////////////////////////////////////////////////////////////
[ "121888719@qq.com" ]
121888719@qq.com
2e34ff303cc7a1d3426ab850ab27550819407dd0
674213909e4e328bd7622c22d2533251f30ab268
/2016_2ndSem_C++_ChessSetupAlgorithm/Project/program/Bicia.cpp
eb786ba5a0c0175096c7fd7256803f33b3161939
[]
no_license
wojtek960506/OldUniversityProjects
48c4d13627149c2c7325e6d8cfc22a7822e0397f
9f4b9170b4c014025c866c55c3fde18788c0e91a
refs/heads/master
2020-04-27T09:33:49.870704
2019-03-06T22:27:35
2019-03-06T22:27:35
174,220,017
0
0
null
null
null
null
UTF-8
C++
false
false
16,156
cpp
#include "Szachy.hpp" //POLA BITE void Pionek::PolaBite(Plansza & P) // pion moze bic tylko po skosie w dol o jedno pole { if(wiersz+1 <= P.dlugosc-1 && kolumna-1 >= 0) if((--P.plansza[wiersz+1][kolumna-1])==-1) //lewy dolny rog P.ile_zostalo--; if(wiersz+1 <= P.dlugosc-1 && kolumna+1 <= P.szerokosc-1) if((--P.plansza[wiersz+1][kolumna+1])==-1) //prawy dolny rog P.ile_zostalo--; } void Krol::PolaBite(Plansza & P) //krol moze bic we wszystkich kierunkach o jedno pole { if(wiersz-1 >= 0 && kolumna-1 >= 0) if((--P.plansza[wiersz-1][kolumna-1])==-1) //lewy gorny rog P.ile_zostalo--; if(wiersz-1 >= 0) if((--P.plansza[wiersz-1][kolumna])==-1) //gora P.ile_zostalo--; if(wiersz-1 >= 0 && kolumna+1 <= P.szerokosc-1) if((--P.plansza[wiersz-1][kolumna+1])==-1) //prawy gorny rog P.ile_zostalo--; if(kolumna-1 >= 0) if((--P.plansza[wiersz][kolumna-1])==-1) //lewo P.ile_zostalo--; if(wiersz+1 <= P.dlugosc-1 && kolumna-1 >= 0) if((--P.plansza[wiersz+1][kolumna-1])==-1) //lewy dolny rog P.ile_zostalo--; if(wiersz+1 <= P.dlugosc-1) if((--P.plansza[wiersz+1][kolumna])==-1) //dol P.ile_zostalo--; if(wiersz+1 <= P.dlugosc-1 && kolumna+1 <= P.szerokosc-1) if((--P.plansza[wiersz+1][kolumna+1])==-1) //prawy dolny rog P.ile_zostalo--; if(kolumna <= P.szerokosc-1) if((--P.plansza[wiersz][kolumna+1])==-1) //prawo P.ile_zostalo--; } void Kon::PolaBite(Plansza & P) //rozklad bic konia { if(wiersz+1 <= P.dlugosc-1 && kolumna+2 <= P.szerokosc-1) if((--P.plansza[wiersz+1][kolumna+2])==-1) //dwa w prawo, jeden w dol P.ile_zostalo--; if(wiersz+2 <= P.dlugosc-1 && kolumna+1 <= P.szerokosc-1) if((--P.plansza[wiersz+2][kolumna+1])==-1) //jeden w prawo, dwa w dol P.ile_zostalo--; if(wiersz+2 <= P.dlugosc-1 && kolumna-1 >= 0) if((--P.plansza[wiersz+2][kolumna-1])==-1) //jeden w lewo, dwa w dol P.ile_zostalo--; if(wiersz+1 <= P.dlugosc-1 && kolumna-2 >= 0) if((--P.plansza[wiersz+1][kolumna-2])==-1) //dwa w lewo, jeden w dol P.ile_zostalo--; if(wiersz-1 >= 0 && kolumna-2 >= 0) if((--P.plansza[wiersz-1][kolumna-2])==-1) //dwa w lewo, jeden w gore P.ile_zostalo--; if(wiersz-2 >= 0 && kolumna-1 >= 0) if((--P.plansza[wiersz-2][kolumna-1])==-1) //jeden w lewo, dwa w gore P.ile_zostalo--; if(wiersz-2 >= 0 && kolumna+1 <= P.szerokosc-1) if((--P.plansza[wiersz-2][kolumna+1])==-1) //jeden w prawo, dwa w gore P.ile_zostalo--; if(wiersz-1 >= 0 && kolumna +2 <= P.szerokosc-1) if((--P.plansza[wiersz-1][kolumna+2])==-1) //dwa w prawo, jeden w gore P.ile_zostalo--; } void Goniec::PolaBite(Plansza & P) { //jesli numer wiersza jest wiekszy niz zero to jedziemy po przekatnych w gore for(int i=1;i<=wiersz;i++) { if(kolumna-i >= 0) if((--P.plansza[wiersz-i][kolumna-i])==-1) //po przekatnej w gore w lewo P.ile_zostalo--; if(kolumna+i <= P.szerokosc-1) if((--P.plansza[wiersz-i][kolumna+i])==-1) //po przekatnej w gore w prawo P.ile_zostalo--; } //jesli numer wiersza jest mniejszy niz dlugosc-1 szachownicy to idziemy po przekatnych w dol for(int i=1;i<=P.dlugosc-1-wiersz;i++) { if(kolumna-i >= 0) if((--P.plansza[wiersz+i][kolumna-i])==-1) //po przekatnej w dol w lewo P.ile_zostalo--; if(kolumna+i <= P.szerokosc-1) if((--P.plansza[wiersz+i][kolumna+i])==-1) //po przekatnej w dol w prawo P.ile_zostalo--; } } void Wieza::PolaBite(Plansza & P) { for(int i=1;i<=wiersz;i++) { if((--P.plansza[wiersz-i][kolumna])==-1) //po kolumnie w gore P.ile_zostalo--; } for(int i=1;i<=P.dlugosc-1-wiersz;i++) { if((--P.plansza[wiersz+i][kolumna])==-1) //po kolumnie w dol P.ile_zostalo--; } for(int i=1;i<=kolumna;i++) { if((--P.plansza[wiersz][kolumna-i])==-1) //po wierszu w lewo P.ile_zostalo--; } for(int i=1;i<=P.szerokosc-1-kolumna;i++) //po wierszu w prawo { if((--P.plansza[wiersz][kolumna+i])==-1) P.ile_zostalo--; } } void Hetman::PolaBite(Plansza & P) { //jesli numer wiersza jest wiekszy niz zero to jedziemy po przekatnych i kolumnach w gore for(int i=1;i<=wiersz;i++) { if(kolumna-i >= 0) if((--P.plansza[wiersz-i][kolumna-i])==-1) //po przekatnej w gore w lewo P.ile_zostalo--; if(kolumna+i <= P.szerokosc-1) if((--P.plansza[wiersz-i][kolumna+i])==-1) //po przekatnej w gore w prawo P.ile_zostalo--; if((--P.plansza[wiersz-i][kolumna])==-1) //po kolumnie w gore P.ile_zostalo--; } //jesli numer wiersza jest mniejszy niz dlugosc-1 szachownicy to idziemy po przekatnych i kolumnach w dol for(int i=1;i<=P.dlugosc-1-wiersz;i++) { if(kolumna-i >= 0) if((--P.plansza[wiersz+i][kolumna-i])==-1) //po przekatnej w dol w lewo P.ile_zostalo--; if(kolumna+i <= P.szerokosc-1) if((--P.plansza[wiersz+i][kolumna+i])==-1) //po przekatnej w dol w prawo P.ile_zostalo--; if((--P.plansza[wiersz+i][kolumna])==-1) //po kolumnie w dol P.ile_zostalo--; } //po przekatnej niekoniecznie mamy tyle samo pol co po kolumnie for(int i=1;i<=kolumna;i++) { if((--P.plansza[wiersz][kolumna-i])==-1) //po wierszu w lewo P.ile_zostalo--; } for(int i=1;i<=P.szerokosc-1-kolumna;i++) //po wierszu w prawo { if((--P.plansza[wiersz][kolumna+i])==-1) P.ile_zostalo--; } } //funkcje bic w ktorych sprawdzamy, czy czy przy ustawianiu figura ustawiana nie bije figur juz stojących bool Pionek::CzyBije(const Plansza & P) // pion moze bic tylko po skosie w dol o jedno pole { if(wiersz+1 <= P.dlugosc-1 && kolumna-1 >= 0) if((P.plansza[wiersz+1][kolumna-1])>0) //lewy dolny rog return true; if(wiersz+1 <= P.dlugosc-1 && kolumna+1 <= P.szerokosc-1) if((P.plansza[wiersz+1][kolumna+1])>0) //prawy dolny rog return true; return false; //jesli ustawiona figura nie bije zadnej figury, ktora juz jest na planszy } bool Krol::CzyBije(const Plansza & P) // pion moze bic tylko po skosie w dol o jedno pole { if(wiersz-1 >= 0 && kolumna-1 >= 0) if((P.plansza[wiersz-1][kolumna-1])>0) //lewy gorny rog return true; if(wiersz-1 >= 0) if((P.plansza[wiersz-1][kolumna])>0) //gora return true; if(wiersz-1 >= 0 && kolumna+1 <= P.szerokosc-1) if((P.plansza[wiersz-1][kolumna+1])>0) //prawy gorny rog return true; if(kolumna-1 >= 0) if((P.plansza[wiersz][kolumna-1])>0) //lewo return true; if(wiersz+1 <= P.dlugosc-1 && kolumna-1 >= 0) if((P.plansza[wiersz+1][kolumna-1])>0) //lewy dolny rog return true; if(wiersz+1 <= P.dlugosc-1) if((P.plansza[wiersz+1][kolumna])>0) //dol return true; if(wiersz+1 <= P.dlugosc-1 && kolumna+1 <= P.szerokosc-1) if((P.plansza[wiersz+1][kolumna+1])>0) //prawy dolny rog return true; if(kolumna+1 <= P.szerokosc-1) if((P.plansza[wiersz][kolumna+1])>0) //prawo return true; return false; //jesli ustawiona figura nie bije zadnej figury, ktora juz jest na planszy } bool Kon::CzyBije(const Plansza & P) // pion moze bic tylko po skosie w dol o jedno pole { if(wiersz+1 <= P.dlugosc-1 && kolumna+2 <= P.szerokosc-1) if((P.plansza[wiersz+1][kolumna+2])>0) //dwa w prawo, jeden w dol return true; if(wiersz+2 <= P.dlugosc-1 && kolumna+1 <= P.szerokosc-1) if((P.plansza[wiersz+2][kolumna+1])>0) //jeden w prawo, dwa w dol return true; if(wiersz+2 <= P.dlugosc-1 && kolumna-1 >= 0) if((P.plansza[wiersz+2][kolumna-1])>0) //jeden w lewo, dwa w dol return true; if(wiersz+1 <= P.dlugosc-1 && kolumna-2 >= 0) if((P.plansza[wiersz+1][kolumna-2])>0) //dwa w lewo, jeden w dol return true; if(wiersz-1 >= 0 && kolumna-2 >= 0) if((P.plansza[wiersz-1][kolumna-2])>0) //dwa w lewo, jeden w gore return true; if(wiersz-2 >= 0 && kolumna-1 >= 0) if((P.plansza[wiersz-2][kolumna-1])>0) //jeden w lewo, dwa w gore return true; if(wiersz-2 >= 0 && kolumna+1 <= P.szerokosc-1) if((P.plansza[wiersz-2][kolumna+1])>0) //jeden w prawo, dwa w gore return true; if(wiersz-1 >= 0 && kolumna +2 <= P.szerokosc-1) if((P.plansza[wiersz-1][kolumna+2])>0) //dwa w prawo, jeden w gore return true; return false; //jesli ustawiona figura nie bije zadnej figury, ktora juz jest na planszy } bool Goniec::CzyBije(const Plansza & P) // pion moze bic tylko po skosie w dol o jedno pole { //jesli numer wiersza jest wiekszy niz zero to jedziemy po przekatnych w gore for(int i=1;i<=wiersz;i++) { if(kolumna-i >= 0) if((P.plansza[wiersz-i][kolumna-i])>0) //po przekatnej w gore w lewo return true; if(kolumna+i <= P.szerokosc-1) if((P.plansza[wiersz-i][kolumna+i])>0) //po przekatnej w gore w prawo return true; } //jesli numer wiersza jest mniejszy niz dlugosc-1 szachownicy to idziemy po przekatnych w dol for(int i=1;i<=P.dlugosc-1-wiersz;i++) { if(kolumna-i >= 0) if((P.plansza[wiersz+i][kolumna-i])>0) //po przekatnej w dol w lewo return true; if(kolumna+i <= P.szerokosc-1) if((P.plansza[wiersz+i][kolumna+i])>0) //po przekatnej w dol w prawo return true; } return false; //jesli ustawiona figura nie bije zadnej figury, ktora juz jest na planszy } bool Wieza::CzyBije(const Plansza & P) // pion moze bic tylko po skosie w dol o jedno pole { for(int i=1;i<=wiersz;i++) { if((P.plansza[wiersz-i][kolumna])>0) //po kolumnie w gore return true; } for(int i=1;i<=P.dlugosc-1-wiersz;i++) { if((P.plansza[wiersz+i][kolumna])>0) //po kolumnie w dol return true; } for(int i=1;i<=kolumna;i++) { if((P.plansza[wiersz][kolumna-i])>0) //po wierszu w lewo return true; } for(int i=1;i<=P.szerokosc-1-kolumna;i++) //po wierszu w prawo { if((P.plansza[wiersz][kolumna+i])>0) return true; } return false; //jesli ustawiona figura nie bije zadnej figury, ktora juz jest na planszy } bool Hetman::CzyBije(const Plansza & P) // pion moze bic tylko po skosie w dol o jedno pole { //jesli numer wiersza jest wiekszy niz zero to jedziemy po przekatnych i kolumnach w gore for(int i=1;i<=wiersz;i++) { if(kolumna-i >= 0) if((P.plansza[wiersz-i][kolumna-i])>0) //po przekatnej w gore w lewo return true; if(kolumna+i <= P.szerokosc-1) if((P.plansza[wiersz-i][kolumna+i])>0) //po przekatnej w gore w prawo return true; if((P.plansza[wiersz-i][kolumna])>0) //po kolumnie w gore return true; } //jesli numer wiersza jest mniejszy niz dlugosc-1 szachownicy to idziemy po przekatnych i kolumnach w dol for(int i=1;i<=P.dlugosc-1-wiersz;i++) { if(kolumna-i >= 0) if((P.plansza[wiersz+i][kolumna-i])>0) //po przekatnej w dol w lewo return true; if(kolumna+i <= P.szerokosc-1) if((P.plansza[wiersz+i][kolumna+i])>0) //po przekatnej w dol w prawo return true; if((P.plansza[wiersz+i][kolumna])>0) //po kolumnie w dol return true; } //po przekatnej niekoniecznie mamy tyle samo pol co po kolumnie for(int i=1;i<=kolumna;i++) { if((P.plansza[wiersz][kolumna-i])>0) //po wierszu w lewo return true; } for(int i=1;i<=P.szerokosc-1-kolumna;i++) //po wierszu w prawo { if((P.plansza[wiersz][kolumna+i])>0) return true; } return false; //jesli ustawiona figura nie bije zadnej figury, ktora juz jest na planszy } //Uswua bicia figury przy usuwaniu jej z planszy void Pionek::UsunBite(Plansza & P) // pion moze bic tylko po skosie w dol o jedno pole { if(wiersz+1 <= P.dlugosc-1 && kolumna-1 >= 0) if((++P.plansza[wiersz+1][kolumna-1])==0) //lewy dolny rog P.ile_zostalo++; if(wiersz+1 <= P.dlugosc-1 && kolumna+1 <= P.szerokosc-1) if((++P.plansza[wiersz+1][kolumna+1])==0) //prawy dolny rog P.ile_zostalo++; } void Krol::UsunBite(Plansza & P) //krol moze bic we wszystkich kierunkach o jedno pole { if(wiersz-1 >= 0 && kolumna-1 >= 0) if((++P.plansza[wiersz-1][kolumna-1])==0) //lewy gorny rog P.ile_zostalo++; if(wiersz-1 >= 0) if((++P.plansza[wiersz-1][kolumna])==0) //gora P.ile_zostalo++; if(wiersz-1 >= 0 && kolumna+1 <= P.szerokosc-1) if((++P.plansza[wiersz-1][kolumna+1])==0) //prawy gorny rog P.ile_zostalo++; if(kolumna-1 >= 0) if((++P.plansza[wiersz][kolumna-1])==0) //lewo P.ile_zostalo++; if(wiersz+1 <= P.dlugosc-1 && kolumna-1 >= 0) if((++P.plansza[wiersz+1][kolumna-1])==0) //lewy dolny rog P.ile_zostalo++; if(wiersz+1 <= P.dlugosc-1) if((++P.plansza[wiersz+1][kolumna])==0) //dol P.ile_zostalo++; if(wiersz+1 <= P.dlugosc-1 && kolumna+1 <= P.szerokosc-1) if((++P.plansza[wiersz+1][kolumna+1])==0) //prawy dolny rog P.ile_zostalo++; if(kolumna+1 <= P.szerokosc-1) if((++P.plansza[wiersz][kolumna+1])==0) //prawo P.ile_zostalo++; } void Kon::UsunBite(Plansza & P) //rozklad bic konia { if(wiersz+1 <= P.dlugosc-1 && kolumna+2 <= P.szerokosc-1) if((++P.plansza[wiersz+1][kolumna+2])==0) //dwa w prawo, jeden w dol P.ile_zostalo++; if(wiersz+2 <= P.dlugosc-1 && kolumna+1 <= P.szerokosc-1) if((++P.plansza[wiersz+2][kolumna+1])==0) //jeden w prawo, dwa w dol P.ile_zostalo++; if(wiersz+2 <= P.dlugosc-1 && kolumna-1 >= 0) if((++P.plansza[wiersz+2][kolumna-1])==0) //jeden w lewo, dwa w dol P.ile_zostalo++; if(wiersz+1 <= P.dlugosc-1 && kolumna-2 >= 0) if((++P.plansza[wiersz+1][kolumna-2])==0) //dwa w lewo, jeden w dol P.ile_zostalo++; if(wiersz-1 >= 0 && kolumna-2 >= 0) if((++P.plansza[wiersz-1][kolumna-2])==0) //dwa w lewo, jeden w gore P.ile_zostalo++; if(wiersz-2 >= 0 && kolumna-1 >= 0) if((++P.plansza[wiersz-2][kolumna-1])==0) //jeden w lewo, dwa w gore P.ile_zostalo++; if(wiersz-2 >= 0 && kolumna+1 <= P.szerokosc-1) if((++P.plansza[wiersz-2][kolumna+1])==0) //jeden w prawo, dwa w gore P.ile_zostalo++; if(wiersz-1 >= 0 && kolumna +2 <= P.szerokosc-1) if((++P.plansza[wiersz-1][kolumna+2])==0) //dwa w prawo, jeden w gore P.ile_zostalo++; } void Goniec::UsunBite(Plansza & P) { //jesli numer wiersza jest wiekszy niz zero to jedziemy po przekatnych w gore for(int i=1;i<=wiersz;i++) { if(kolumna-i >= 0) if((++P.plansza[wiersz-i][kolumna-i])==0) //po przekatnej w gore w lewo P.ile_zostalo++; if(kolumna+i <= P.szerokosc-1) if((++P.plansza[wiersz-i][kolumna+i])==0) //po przekatnej w gore w prawo P.ile_zostalo++; } //jesli numer wiersza jest mniejszy niz dlugosc-1 szachownicy to idziemy po przekatnych w dol for(int i=1;i<=P.dlugosc-1-wiersz;i++) { if(kolumna-i >= 0) if((++P.plansza[wiersz+i][kolumna-i])==0) //po przekatnej w dol w lewo P.ile_zostalo++; if(kolumna+i <= P.szerokosc-1) if((++P.plansza[wiersz+i][kolumna+i])==0) //po przekatnej w dol w prawo P.ile_zostalo++; } } void Wieza::UsunBite(Plansza & P) { for(int i=1;i<=wiersz;i++) { if((++P.plansza[wiersz-i][kolumna])==0) //po kolumnie w gore P.ile_zostalo++; } for(int i=1;i<=P.dlugosc-1-wiersz;i++) { if((++P.plansza[wiersz+i][kolumna])==0) //po kolumnie w dol P.ile_zostalo++; } for(int i=1;i<=kolumna;i++) { if((++P.plansza[wiersz][kolumna-i])==0) //po wierszu w lewo P.ile_zostalo++; } for(int i=1;i<=P.szerokosc-1-kolumna;i++) //po wierszu w prawo { if((++P.plansza[wiersz][kolumna+i])==0) P.ile_zostalo++; } } void Hetman::UsunBite(Plansza & P) { //jesli numer wiersza jest wiekszy niz zero to jedziemy po przekatnych i kolumnach w gore for(int i=1;i<=wiersz;i++) { if(kolumna-i >= 0) if((++P.plansza[wiersz-i][kolumna-i])==0) //po przekatnej w gore w lewo P.ile_zostalo++; if(kolumna+i <= P.szerokosc-1) if((++P.plansza[wiersz-i][kolumna+i])==0) //po przekatnej w gore w prawo P.ile_zostalo++; if((++P.plansza[wiersz-i][kolumna])==0) //po kolumnie w gore P.ile_zostalo++; } //jesli numer wiersza jest mniejszy niz dlugosc-1 szachownicy to idziemy po przekatnych i kolumnach w dol for(int i=1;i<=P.dlugosc-1-wiersz;i++) { if(kolumna-i >= 0) if((++P.plansza[wiersz+i][kolumna-i])==0) //po przekatnej w dol w lewo P.ile_zostalo++; if(kolumna+i <= P.szerokosc-1) if((++P.plansza[wiersz+i][kolumna+i])==0) //po przekatnej w dol w prawo P.ile_zostalo++; if((++P.plansza[wiersz+i][kolumna])==0) //po kolumnie w dol P.ile_zostalo++; } //po przekatnej niekoniecznie mamy tyle samo pol co po kolumnie for(int i=1;i<=kolumna;i++) { if((++P.plansza[wiersz][kolumna-i])==0) //po wierszu w lewo P.ile_zostalo++; } for(int i=1;i<=P.szerokosc-1-kolumna;i++) //po wierszu w prawo { if((++P.plansza[wiersz][kolumna+i])==0) P.ile_zostalo++; } }
[ "wojtekzielinski96@gmail.com" ]
wojtekzielinski96@gmail.com
20e7e3158f5b3a0ecd1ecfa9d59e29a444ca9592
ca83eae8b66fa1f0d508c2a256fe09cfcc0288da
/data/FbPageInfo.cpp
227b6d0adb0b6b6d2a211f2642094389cad9fb10
[]
no_license
ricardosalinase/qtfacebook
51646a508c9595b4dd947eb211cd7218aa795e0b
eef96e9678470dae233d17688acddedc76aeaf8f
refs/heads/master
2021-01-20T09:12:49.378176
2010-03-28T22:20:02
2010-03-28T22:20:02
39,757,583
0
0
null
null
null
null
UTF-8
C++
false
false
748
cpp
#include "FbPageInfo.h" namespace DATA { FbPageInfo::FbPageInfo() { } void FbPageInfo::setPageId(const QString &id) { m_pageId = id; } QString& FbPageInfo::getPageId() { return m_pageId; } void FbPageInfo::setName(const QString &name) { m_name = name; } QString& FbPageInfo::getName() { return m_name; } void FbPageInfo::setPic(const QString &pic) { m_pic = QUrl(pic); } QUrl& FbPageInfo::getPic() { return m_pic; } void FbPageInfo::setPicSquare(const QString &ps) { m_picSquare = QUrl(ps); } QUrl& FbPageInfo::getPicSquare() { return m_picSquare; } void FbPageInfo::setPicBig(const QString &pb) { m_picBig = QUrl(pb); } QUrl& FbPageInfo::getPicBig() { return m_picBig; } } // namespace DATA
[ "roach@mostlyharmless.net" ]
roach@mostlyharmless.net
6b1584baa1224934409074c52d5bda5a98303d09
896dc13fd4bc083be0de03899c8829dce4b4d4ea
/lab3/src/Stoper.cpp
3670ab32e34b23a7c31c8f9f1e778559e575feae
[]
no_license
218678/PAMSI
9af0843154ee777a03383da9da69b9cbc80c9d95
e72f01bd126a5552ed52086370b058250454710b
refs/heads/master
2020-04-02T01:56:36.116900
2017-06-25T17:03:24
2017-06-25T17:03:24
83,685,859
0
1
null
null
null
null
UTF-8
C++
false
false
742
cpp
#include "../inc/Stoper.hh" double Stoper::wykonaj_pomiar(ITestowalny *obiekt, int ilosc_pomiarow, int nr_algorytmu, int ilosc_elem){ clock_t start; clock_t stop; double diff_time; av_time = 0; wyp_ilosc_elem = ilosc_elem; for (int i=0; i<ilosc_pomiarow; i++){ obiekt->fill(ilosc_elem, rand()%((1+nr_algorytmu)*2)); start = clock(); obiekt->wykonaj_algorytm(nr_algorytmu); stop = clock(); diff_time = difftime(stop, start) / CLOCKS_PER_SEC; av_time = av_time + diff_time; } av_time = av_time/ilosc_pomiarow; return av_time; } void Stoper::wypisz_pomiar(std::ostream & stream){ stream << wyp_ilosc_elem << " " << av_time << "\n"; } Stoper::Stoper(){ av_time = 0; wyp_ilosc_elem = 0; } Stoper::~Stoper(){ }
[ "218678@student.pwr.edu.pl" ]
218678@student.pwr.edu.pl
de62b74225cb67b0e5e0ac32281b06a225f51b39
494dd8ca103f0db591da7f22ee3e88da72153b6b
/Project 4/pool.cpp
7b3b6b3e357bb56e96ada8a1abc1a22432cbf90b
[]
no_license
AlXplore/Programming-and-Data-Structure
e0c124e7f0541051774f01abffd96b60439366fd
5d0f79d1c845b4a3a7deae114735cc49912c909a
refs/heads/master
2020-07-08T09:28:55.212885
2019-08-21T18:13:37
2019-08-21T18:13:37
203,627,144
0
0
null
null
null
null
UTF-8
C++
false
false
2,040
cpp
#include "pool.h" #include "exceptions.h" using namespace std; Pool::Pool() { Piece p1(SHORT, BEIGE, CIRCLE, HOLLOW); Piece p2(SHORT, BEIGE, CIRCLE, SOLID); Piece p3(SHORT, BEIGE, SQUARE, HOLLOW); Piece p4(SHORT, BEIGE, SQUARE, SOLID); Piece p5(SHORT, SEPIA, CIRCLE, HOLLOW); Piece p6(SHORT, SEPIA, CIRCLE, SOLID); Piece p7(SHORT, SEPIA, SQUARE, HOLLOW); Piece p8(SHORT, SEPIA, SQUARE, SOLID); Piece p9(TALL, BEIGE, CIRCLE, HOLLOW); Piece p10(TALL, BEIGE, CIRCLE, SOLID); Piece p11(TALL, BEIGE, SQUARE, HOLLOW); Piece p12(TALL, BEIGE, SQUARE, SOLID); Piece p13(TALL, SEPIA, CIRCLE, HOLLOW); Piece p14(TALL, SEPIA, CIRCLE, SOLID); Piece p15(TALL, SEPIA, SQUARE, HOLLOW); Piece p16(TALL, SEPIA, SQUARE, SOLID); pieces[0] = p1; pieces[1] = p2; pieces[2] = p3; pieces[3] = p4; pieces[4] = p5; pieces[5] = p6; pieces[6] = p7; pieces[7] = p8; pieces[8] = p9; pieces[9] = p10; pieces[10] = p11; pieces[11] = p12; pieces[12] = p13; pieces[13] = p14; pieces[14] = p15; pieces[15] = p16; } Piece & Pool::getUnusedPiece(int index) { if (pieces[index].isUsed() == true) { UsedPieceException errPc(pieces[index]); throw errPc; } else return pieces[index]; } Piece & Pool::getUnusedPiece(Height h, Color c, Shape s, Top t) { int index = 8*int(h) + 4*int(c) + 2*int(s) + int(t); return getUnusedPiece(index); } Piece & Pool::getUnusedPiece(const std::string &in) { int index = 0; if (in[0] == 'T') index += 8; if (in[1] == 'E') index += 4; if (in[2] == 'Q') index += 2; if (in[3] == 'O') index += 1; return getUnusedPiece(index); } string Pool::toString() const { string s1 = "Available:\n"; string s0 = ""; for (int i = 0; i < 16; i ++) { if (pieces[i].isUsed() == false) s1 = s1 + pieces[i].toString()[0] + pieces[i].toString()[1] + " "; } s1 = s1 + "\n"; for (int i = 0; i < 16; i ++) { if (pieces[i].isUsed() == false) s1 = s1 + pieces[i].toString()[2] + pieces[i].toString()[3] + " "; } s1 = s1 + "\n"; if (s1 == "Available:\n\n\n") return s0; else return s1; }
[ "wyz1208@outlook.com" ]
wyz1208@outlook.com
24b961b50442b6beb65d3706a68e6a17dfae32df
cad3f5a1ab56528fe3e21c62c564c733263a2fdf
/src/execution/exec_defs.cpp
aa9a2075bed84967574da95831797203255921b1
[ "MIT" ]
permissive
stephaniewang100/terrier-steph
7bec88c5bd8d0d81b233b19edef9b89b4a96626b
3e18799b5fbe33db7a2f98a77e48b52957690a46
refs/heads/master
2022-12-19T13:22:04.398476
2020-09-25T01:20:46
2020-09-25T01:20:46
276,163,646
0
0
MIT
2020-09-04T17:49:07
2020-06-30T17:16:04
C++
UTF-8
C++
false
false
231
cpp
#include "execution/exec_defs.h" #include "common/strong_typedef_body.h" namespace terrier::execution { STRONG_TYPEDEF_BODY(query_id_t, uint32_t); STRONG_TYPEDEF_BODY(pipeline_id_t, uint32_t); } // namespace terrier::execution
[ "noreply@github.com" ]
noreply@github.com
dcb3fe1c0b060aeff2c1ec34fe431afcaf7ba9f5
32b8db47c9335f65aeb39848c928c3b64fc8a52e
/tgame-client-classes-20160829/ProtoDescCpp/CSServerNotifyMsg.pb.h
b60b1ceadb9b87fcdac4070c2703abf4d30b1427
[]
no_license
mengtest/backup-1
763dedbb09d662b0940a2cedffb4b9fd1f7fb35d
d9f34e5bc08fe88485ac82f8e9aa09b994bb0e54
refs/heads/master
2020-05-04T14:29:30.181303
2016-12-13T02:28:23
2016-12-13T02:28:23
null
0
0
null
null
null
null
UTF-8
C++
false
true
19,147
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: CSServerNotifyMsg.proto #ifndef PROTOBUF_CSServerNotifyMsg_2eproto__INCLUDED #define PROTOBUF_CSServerNotifyMsg_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 2005000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/generated_message_util.h> #include <google/protobuf/message_lite.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include "MsgBase.pb.h" // @@protoc_insertion_point(includes) namespace vmsg { // Internal implementation detail -- do not call these. void protobuf_AddDesc_CSServerNotifyMsg_2eproto(); void protobuf_AssignDesc_CSServerNotifyMsg_2eproto(); void protobuf_ShutdownFile_CSServerNotifyMsg_2eproto(); class CSServerNotifyPkg; class CSServerNotify; class CSServerNotifyRequest; class CSServerNotifyRespond; enum NOTIFY_SPEC_ID { GM_NOTIFY_ID = 0, IMPORTANT_EVENT_NOTIFY_ID = 10000 }; bool NOTIFY_SPEC_ID_IsValid(int value); const NOTIFY_SPEC_ID NOTIFY_SPEC_ID_MIN = GM_NOTIFY_ID; const NOTIFY_SPEC_ID NOTIFY_SPEC_ID_MAX = IMPORTANT_EVENT_NOTIFY_ID; const int NOTIFY_SPEC_ID_ARRAYSIZE = NOTIFY_SPEC_ID_MAX + 1; // =================================================================== class CSServerNotifyPkg : public ::google::protobuf::MessageLite { public: CSServerNotifyPkg(); virtual ~CSServerNotifyPkg(); CSServerNotifyPkg(const CSServerNotifyPkg& from); inline CSServerNotifyPkg& operator=(const CSServerNotifyPkg& from) { CopyFrom(from); return *this; } static const CSServerNotifyPkg& default_instance(); #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER // Returns the internal default instance pointer. This function can // return NULL thus should not be used by the user. This is intended // for Protobuf internal code. Please use default_instance() declared // above instead. static inline const CSServerNotifyPkg* internal_default_instance() { return default_instance_; } #endif void Swap(CSServerNotifyPkg* other); // implements Message ---------------------------------------------- CSServerNotifyPkg* New() const; void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); void CopyFrom(const CSServerNotifyPkg& from); void MergeFrom(const CSServerNotifyPkg& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::std::string GetTypeName() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:vmsg.CSServerNotifyPkg) private: mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[1]; #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER friend void protobuf_AddDesc_CSServerNotifyMsg_2eproto_impl(); #else friend void protobuf_AddDesc_CSServerNotifyMsg_2eproto(); #endif friend void protobuf_AssignDesc_CSServerNotifyMsg_2eproto(); friend void protobuf_ShutdownFile_CSServerNotifyMsg_2eproto(); void InitAsDefaultInstance(); static CSServerNotifyPkg* default_instance_; }; // ------------------------------------------------------------------- class CSServerNotify : public ::google::protobuf::MessageLite { public: CSServerNotify(); virtual ~CSServerNotify(); CSServerNotify(const CSServerNotify& from); inline CSServerNotify& operator=(const CSServerNotify& from) { CopyFrom(from); return *this; } static const CSServerNotify& default_instance(); #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER // Returns the internal default instance pointer. This function can // return NULL thus should not be used by the user. This is intended // for Protobuf internal code. Please use default_instance() declared // above instead. static inline const CSServerNotify* internal_default_instance() { return default_instance_; } #endif void Swap(CSServerNotify* other); // implements Message ---------------------------------------------- CSServerNotify* New() const; void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); void CopyFrom(const CSServerNotify& from); void MergeFrom(const CSServerNotify& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::std::string GetTypeName() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // required uint32 NotifyID = 1; inline bool has_notifyid() const; inline void clear_notifyid(); static const int kNotifyIDFieldNumber = 1; inline ::google::protobuf::uint32 notifyid() const; inline void set_notifyid(::google::protobuf::uint32 value); // repeated string NotifyStr = 2; inline int notifystr_size() const; inline void clear_notifystr(); static const int kNotifyStrFieldNumber = 2; inline const ::std::string& notifystr(int index) const; inline ::std::string* mutable_notifystr(int index); inline void set_notifystr(int index, const ::std::string& value); inline void set_notifystr(int index, const char* value); inline void set_notifystr(int index, const char* value, size_t size); inline ::std::string* add_notifystr(); inline void add_notifystr(const ::std::string& value); inline void add_notifystr(const char* value); inline void add_notifystr(const char* value, size_t size); inline const ::google::protobuf::RepeatedPtrField< ::std::string>& notifystr() const; inline ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_notifystr(); // optional .vmsg.CSServerNotifyPkg ServerNotifyPkg = 3; inline bool has_servernotifypkg() const; inline void clear_servernotifypkg(); static const int kServerNotifyPkgFieldNumber = 3; inline const ::vmsg::CSServerNotifyPkg& servernotifypkg() const; inline ::vmsg::CSServerNotifyPkg* mutable_servernotifypkg(); inline ::vmsg::CSServerNotifyPkg* release_servernotifypkg(); inline void set_allocated_servernotifypkg(::vmsg::CSServerNotifyPkg* servernotifypkg); // @@protoc_insertion_point(class_scope:vmsg.CSServerNotify) private: inline void set_has_notifyid(); inline void clear_has_notifyid(); inline void set_has_servernotifypkg(); inline void clear_has_servernotifypkg(); ::google::protobuf::RepeatedPtrField< ::std::string> notifystr_; ::vmsg::CSServerNotifyPkg* servernotifypkg_; ::google::protobuf::uint32 notifyid_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER friend void protobuf_AddDesc_CSServerNotifyMsg_2eproto_impl(); #else friend void protobuf_AddDesc_CSServerNotifyMsg_2eproto(); #endif friend void protobuf_AssignDesc_CSServerNotifyMsg_2eproto(); friend void protobuf_ShutdownFile_CSServerNotifyMsg_2eproto(); void InitAsDefaultInstance(); static CSServerNotify* default_instance_; }; // ------------------------------------------------------------------- class CSServerNotifyRequest : public ::google::protobuf::MessageLite { public: CSServerNotifyRequest(); virtual ~CSServerNotifyRequest(); CSServerNotifyRequest(const CSServerNotifyRequest& from); inline CSServerNotifyRequest& operator=(const CSServerNotifyRequest& from) { CopyFrom(from); return *this; } static const CSServerNotifyRequest& default_instance(); #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER // Returns the internal default instance pointer. This function can // return NULL thus should not be used by the user. This is intended // for Protobuf internal code. Please use default_instance() declared // above instead. static inline const CSServerNotifyRequest* internal_default_instance() { return default_instance_; } #endif void Swap(CSServerNotifyRequest* other); // implements Message ---------------------------------------------- CSServerNotifyRequest* New() const; void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); void CopyFrom(const CSServerNotifyRequest& from); void MergeFrom(const CSServerNotifyRequest& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::std::string GetTypeName() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:vmsg.CSServerNotifyRequest) private: mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[1]; #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER friend void protobuf_AddDesc_CSServerNotifyMsg_2eproto_impl(); #else friend void protobuf_AddDesc_CSServerNotifyMsg_2eproto(); #endif friend void protobuf_AssignDesc_CSServerNotifyMsg_2eproto(); friend void protobuf_ShutdownFile_CSServerNotifyMsg_2eproto(); void InitAsDefaultInstance(); static CSServerNotifyRequest* default_instance_; }; // ------------------------------------------------------------------- class CSServerNotifyRespond : public ::google::protobuf::MessageLite { public: CSServerNotifyRespond(); virtual ~CSServerNotifyRespond(); CSServerNotifyRespond(const CSServerNotifyRespond& from); inline CSServerNotifyRespond& operator=(const CSServerNotifyRespond& from) { CopyFrom(from); return *this; } static const CSServerNotifyRespond& default_instance(); #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER // Returns the internal default instance pointer. This function can // return NULL thus should not be used by the user. This is intended // for Protobuf internal code. Please use default_instance() declared // above instead. static inline const CSServerNotifyRespond* internal_default_instance() { return default_instance_; } #endif void Swap(CSServerNotifyRespond* other); // implements Message ---------------------------------------------- CSServerNotifyRespond* New() const; void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); void CopyFrom(const CSServerNotifyRespond& from); void MergeFrom(const CSServerNotifyRespond& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::std::string GetTypeName() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional .vmsg.CSServerNotify Server_Notify = 1; inline bool has_server_notify() const; inline void clear_server_notify(); static const int kServerNotifyFieldNumber = 1; inline const ::vmsg::CSServerNotify& server_notify() const; inline ::vmsg::CSServerNotify* mutable_server_notify(); inline ::vmsg::CSServerNotify* release_server_notify(); inline void set_allocated_server_notify(::vmsg::CSServerNotify* server_notify); // @@protoc_insertion_point(class_scope:vmsg.CSServerNotifyRespond) private: inline void set_has_server_notify(); inline void clear_has_server_notify(); ::vmsg::CSServerNotify* server_notify_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER friend void protobuf_AddDesc_CSServerNotifyMsg_2eproto_impl(); #else friend void protobuf_AddDesc_CSServerNotifyMsg_2eproto(); #endif friend void protobuf_AssignDesc_CSServerNotifyMsg_2eproto(); friend void protobuf_ShutdownFile_CSServerNotifyMsg_2eproto(); void InitAsDefaultInstance(); static CSServerNotifyRespond* default_instance_; }; // =================================================================== // =================================================================== // CSServerNotifyPkg // ------------------------------------------------------------------- // CSServerNotify // required uint32 NotifyID = 1; inline bool CSServerNotify::has_notifyid() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void CSServerNotify::set_has_notifyid() { _has_bits_[0] |= 0x00000001u; } inline void CSServerNotify::clear_has_notifyid() { _has_bits_[0] &= ~0x00000001u; } inline void CSServerNotify::clear_notifyid() { notifyid_ = 0u; clear_has_notifyid(); } inline ::google::protobuf::uint32 CSServerNotify::notifyid() const { return notifyid_; } inline void CSServerNotify::set_notifyid(::google::protobuf::uint32 value) { set_has_notifyid(); notifyid_ = value; } // repeated string NotifyStr = 2; inline int CSServerNotify::notifystr_size() const { return notifystr_.size(); } inline void CSServerNotify::clear_notifystr() { notifystr_.Clear(); } inline const ::std::string& CSServerNotify::notifystr(int index) const { return notifystr_.Get(index); } inline ::std::string* CSServerNotify::mutable_notifystr(int index) { return notifystr_.Mutable(index); } inline void CSServerNotify::set_notifystr(int index, const ::std::string& value) { notifystr_.Mutable(index)->assign(value); } inline void CSServerNotify::set_notifystr(int index, const char* value) { notifystr_.Mutable(index)->assign(value); } inline void CSServerNotify::set_notifystr(int index, const char* value, size_t size) { notifystr_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); } inline ::std::string* CSServerNotify::add_notifystr() { return notifystr_.Add(); } inline void CSServerNotify::add_notifystr(const ::std::string& value) { notifystr_.Add()->assign(value); } inline void CSServerNotify::add_notifystr(const char* value) { notifystr_.Add()->assign(value); } inline void CSServerNotify::add_notifystr(const char* value, size_t size) { notifystr_.Add()->assign(reinterpret_cast<const char*>(value), size); } inline const ::google::protobuf::RepeatedPtrField< ::std::string>& CSServerNotify::notifystr() const { return notifystr_; } inline ::google::protobuf::RepeatedPtrField< ::std::string>* CSServerNotify::mutable_notifystr() { return &notifystr_; } // optional .vmsg.CSServerNotifyPkg ServerNotifyPkg = 3; inline bool CSServerNotify::has_servernotifypkg() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void CSServerNotify::set_has_servernotifypkg() { _has_bits_[0] |= 0x00000004u; } inline void CSServerNotify::clear_has_servernotifypkg() { _has_bits_[0] &= ~0x00000004u; } inline void CSServerNotify::clear_servernotifypkg() { if (servernotifypkg_ != NULL) servernotifypkg_->::vmsg::CSServerNotifyPkg::Clear(); clear_has_servernotifypkg(); } inline const ::vmsg::CSServerNotifyPkg& CSServerNotify::servernotifypkg() const { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER return servernotifypkg_ != NULL ? *servernotifypkg_ : *default_instance().servernotifypkg_; #else return servernotifypkg_ != NULL ? *servernotifypkg_ : *default_instance_->servernotifypkg_; #endif } inline ::vmsg::CSServerNotifyPkg* CSServerNotify::mutable_servernotifypkg() { set_has_servernotifypkg(); if (servernotifypkg_ == NULL) servernotifypkg_ = new ::vmsg::CSServerNotifyPkg; return servernotifypkg_; } inline ::vmsg::CSServerNotifyPkg* CSServerNotify::release_servernotifypkg() { clear_has_servernotifypkg(); ::vmsg::CSServerNotifyPkg* temp = servernotifypkg_; servernotifypkg_ = NULL; return temp; } inline void CSServerNotify::set_allocated_servernotifypkg(::vmsg::CSServerNotifyPkg* servernotifypkg) { delete servernotifypkg_; servernotifypkg_ = servernotifypkg; if (servernotifypkg) { set_has_servernotifypkg(); } else { clear_has_servernotifypkg(); } } // ------------------------------------------------------------------- // CSServerNotifyRequest // ------------------------------------------------------------------- // CSServerNotifyRespond // optional .vmsg.CSServerNotify Server_Notify = 1; inline bool CSServerNotifyRespond::has_server_notify() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void CSServerNotifyRespond::set_has_server_notify() { _has_bits_[0] |= 0x00000001u; } inline void CSServerNotifyRespond::clear_has_server_notify() { _has_bits_[0] &= ~0x00000001u; } inline void CSServerNotifyRespond::clear_server_notify() { if (server_notify_ != NULL) server_notify_->::vmsg::CSServerNotify::Clear(); clear_has_server_notify(); } inline const ::vmsg::CSServerNotify& CSServerNotifyRespond::server_notify() const { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER return server_notify_ != NULL ? *server_notify_ : *default_instance().server_notify_; #else return server_notify_ != NULL ? *server_notify_ : *default_instance_->server_notify_; #endif } inline ::vmsg::CSServerNotify* CSServerNotifyRespond::mutable_server_notify() { set_has_server_notify(); if (server_notify_ == NULL) server_notify_ = new ::vmsg::CSServerNotify; return server_notify_; } inline ::vmsg::CSServerNotify* CSServerNotifyRespond::release_server_notify() { clear_has_server_notify(); ::vmsg::CSServerNotify* temp = server_notify_; server_notify_ = NULL; return temp; } inline void CSServerNotifyRespond::set_allocated_server_notify(::vmsg::CSServerNotify* server_notify) { delete server_notify_; server_notify_ = server_notify; if (server_notify) { set_has_server_notify(); } else { clear_has_server_notify(); } } // @@protoc_insertion_point(namespace_scope) } // namespace vmsg // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_CSServerNotifyMsg_2eproto__INCLUDED
[ "1027718562@qq.com" ]
1027718562@qq.com
436b131f311595d1a4ce41a6ca6e2248dd92332c
c119bc618d2fc0a389682ce1c3b0de68e0fa88ab
/ht4-5.cpp
a23ab71ba77d79d830de11a739d8b8923d38ff30
[]
no_license
Xsardas1000/Algorithms-and-Data-structures
567e66aa129121b79d0a1eb1a64551263111454d
298b5725d0e16adcc58bb129faf29847f5f7111d
refs/heads/master
2021-01-23T03:16:13.290534
2017-03-24T11:51:33
2017-03-24T11:51:33
86,062,670
0
0
null
null
null
null
UTF-8
C++
false
false
3,648
cpp
// // ht4-5.cpp // sphere // // Created by Максим on 18.04.16. // Copyright © 2016 Максим. All rights reserved. // #include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <map> #include <algorithm> /*Сотовая связь В городе имеется несколько операторов мобильной связи, каждый из которых располагает несколькими вышками. У каждой вышки свои координаты и своя зона уверенного приёма. Абонент находится в точке с заданными координатами. Требуется определить количество операторов мобильной связи в городе и определить, для скольких вышек у абонента, находящегося в данной точке, имеется устойчивая связь. В первой строке входного файла содержится целое число N(1 ≤ N ≤ 10000 — количество базовых станций. Далее следует N пар строк, в первой строке содержится имя оператора, во второй — два целых числа с координатами станции Xi и Yi ( - 10000 ≤ Xi, YI ≤ 10000), за которыми следует целочисленный радиус уверенного приёма Ri(1 ≤ Ri ≤ 10000). В последней строке — координаты абонента Xa и Ya. Названия операторов — строки, не содержащие пробелов и состоящие из букв латинского алфавита и цифр. В первой строке выходного файла нужно вывести количество операторов K, K ≤ 1000. В следующих K строках требуется вывести название оператора ( в порядке их появления во входном файле) и через пробел количество базовых станций, доступных для абонента. Input format N name1 X1 Y1 R1 ... namen Xn Yn Zn Xa Ya Output format K name1 c1 name2 c2 ... nameK cK Examples*/ using namespace:: std; class Tower { public: string name; int x, y, r; Tower() {} }; int main(int argc, const char * argv[]) { int N, xa, ya; cin >> N; map<string, int> companies; vector<Tower> towers; vector<string> names; for (int i = 0; i < N; i++) { string name; int x, y, r; cin >> name >> x >> y >> r; Tower tower; tower.name = name; tower.x = x; tower.y = y, tower.r = r; towers.push_back(tower); } cin >> xa >> ya; for (int i = 0; i < N; i++) { if ((xa - towers[i].x) * (xa - towers[i].x) + (ya - towers[i].y) * (ya - towers[i].y) <= towers[i].r * towers[i].r) { companies[towers[i].name]++; } if (find(names.begin(), names.end(), towers[i].name) == names.end()) { names.push_back(towers[i].name); } } cout << names.size() << endl; for (int i = 0; i < names.size(); i++) { cout << names[i] << " " << companies[names[i]] << endl; } /* for (auto obj :companies) { cout << obj.first << " " << obj.second << endl; }*/ return 0; }
[ "maxapple@yandex.ru" ]
maxapple@yandex.ru
86c0991ae9f1157ab0653f900433b8312fe0d42b
a75a5a272c2faea4b9f30454afe3b5d5bc10ea54
/src/services/rpc/handlers/UnlDelete.cpp
abb2bbff89cd0850f1025cbdfa59692338feccab
[]
no_license
mgicode/jingtum-core
988ab269e27584238b7ecc25bdc2d2425aa4a5ca
b189c75a9674706499ac59f9caf509f869f25f18
refs/heads/master
2021-01-24T21:42:00.732087
2018-02-28T09:45:08
2018-02-28T09:45:08
123,274,962
2
2
null
null
null
null
UTF-8
C++
false
false
2,737
cpp
//------------------------------------------------------------------------------ /* This file is part of skywelld: https://github.com/skywell/skywelld Copyright (c) 2012-2014 Skywell Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <BeastConfig.h> #include <common/misc/NetworkOPs.h> #include <common/base/StringUtilities.h> #include <common/json/json_reader.h> #include <common/core/LoadFeeTrack.h> #include <protocol/TxFlags.h> #include <protocol/Indexes.h> #include <protocol/JsonFields.h> #include <protocol/ErrorCodes.h> #include <ledger/LedgerMaster.h> #include <services/rpc/impl/KeypairForSignature.h> #include <services/rpc/impl/TransactionSign.h> #include <services/rpc/impl/Tuning.h> #include <main/Application.h> #include <services/rpc/impl/LegacyPathFind.h> #include <services/net/RPCErr.h> #include <transaction/paths/FindPaths.h> #include <services/rpc/Context.h> #include <network/peers/UniqueNodeList.h> #include <services/rpc/impl/Handler.h> //#include <protocol/JsonFields.h> //#include <protocol/ErrorCodes.h> //#include <services/net/RPCErr.h> //#include <common/misc/NetworkOPs.h> //#include <network/resource/Fees.h> //#include <services/rpc/impl/LookupLedger.h> namespace skywell { // { // node: <domain>|<public_key> // } Json::Value doUnlDelete (RPC::Context& context) { auto lock = std::unique_lock<std::recursive_mutex>(getApp().getMasterMutex()); if (!context.params.isMember (jss::node)) return rpcError (rpcINVALID_PARAMS); auto strNode = context.params[jss::node].asString (); SkywellAddress raNodePublic; if (raNodePublic.setNodePublic (strNode)) { getApp().getUNL ().nodeRemovePublic (raNodePublic); return RPC::makeObjectValue ("removing node by public key"); } else { getApp().getUNL ().nodeRemoveDomain (strNode); return RPC::makeObjectValue ("removing node by domain"); } } } // skywell
[ "beautifularea@gmail.com" ]
beautifularea@gmail.com
372803627bad5fb87dc32d8d61d77824f23628aa
288d41b0f0832685aab74f1b03b5095927ef7f03
/tuple/include/array_of_doubles_union_impl.hpp
57899d932c097b82ad2c42b993af22b1f87413e4
[ "MIT", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
chufucun/datasketches-cpp
b1d8fc855a54bd05856af63bd612eff464ac6324
d1227ef2b309e1a3763449f86779b4551f75b18a
refs/heads/master
2023-03-06T14:40:18.656759
2021-02-17T05:49:53
2021-02-17T06:03:00
313,572,718
0
0
Apache-2.0
2021-01-15T11:59:03
2020-11-17T09:43:07
C++
UTF-8
C++
false
false
1,865
hpp
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace datasketches { template<typename A> array_of_doubles_union_alloc<A>::array_of_doubles_union_alloc(uint8_t lg_cur_size, uint8_t lg_nom_size, resize_factor rf, uint64_t theta, uint64_t seed, const Policy& policy, const A& allocator): Base(lg_cur_size, lg_nom_size, rf, theta, seed, policy, allocator) {} template<typename A> auto array_of_doubles_union_alloc<A>::get_result(bool ordered) const -> CompactSketch { return compact_array_of_doubles_sketch_alloc<A>(this->state_.get_policy().get_policy().get_num_values(), Base::get_result(ordered)); } // builder template<typename A> array_of_doubles_union_alloc<A>::builder::builder(const Policy& policy, const A& allocator): tuple_base_builder<builder, Policy, A>(policy, allocator) {} template<typename A> array_of_doubles_union_alloc<A> array_of_doubles_union_alloc<A>::builder::build() const { return array_of_doubles_union_alloc<A>(this->starting_lg_size(), this->lg_k_, this->rf_, this->starting_theta(), this->seed_, this->policy_, this->allocator_); } } /* namespace datasketches */
[ "AlexanderSaydakov@users.noreply.github.com" ]
AlexanderSaydakov@users.noreply.github.com
fc9c98304076a15452e9424366c526be6222b3de
76b7e459b143c8481b044c60a68c768a0848b8f6
/GYM/ICPC/Brazil-Regional-2016/F.cpp
89aee50fac4d48ad37ff15ab4742c8fc4c7500af
[]
no_license
hsnavarro/imepp
f3b195e5ed4e453eac9b73d5a77b39f44917435f
eb90580caea91b48e7d541db92531ba3fd2b82c1
refs/heads/master
2021-11-28T07:25:05.778476
2021-09-10T02:20:32
2021-09-10T02:20:32
145,646,296
0
1
null
2021-09-10T02:20:33
2018-08-22T02:40:54
C++
UTF-8
C++
false
false
700
cpp
#include <bits/stdc++.h> using namespace std; #define st first #define nd second #define pb push_back typedef pair<int, int> pii; typedef pair<int, pii> piii; typedef long long ll; const int INF = 0x3f3f3f3f; const ll LINF = 0x3f3f3f3f3f3f3f3f; const int N = 1e3+5; int main(){ ios_base::sync_with_stdio(0), cin.tie(0); int n , c , s; while(cin >> n >> c >> s){ int f[N] , x , pos = 1; memset(f,0,sizeof(f)); f[1] = 1; for(int i = 1 ; i <= c ; i++){ cin >> x; if(x == 1){ if(pos == n) pos = 1; else pos++; } else{ if(pos == 1) pos = n; else pos--; } f[pos]++; } cout << f[s] << "\n"; } }
[ "ricksnavarro@gmail.com" ]
ricksnavarro@gmail.com
354ca80668d5c25f818c5abe58242664f00b7859
ea273a0d5a4f56a1da8b6366e8e1e3712a9efd47
/Source/Rhi/Private/Direct3D11Rhi/Direct3D11Rhi.cpp
fd51b9c721b65bc5298062ca32795b881d440c51
[ "MIT" ]
permissive
cofenberg/unrimp
c31eb36ebde09db70173a154be518925ba192d9a
3d4717d0742a5bc466321905278e0110330df070
refs/heads/master
2022-05-27T05:20:48.463362
2022-05-21T08:15:15
2022-05-21T08:15:15
7,425,818
213
22
null
null
null
null
UTF-8
C++
false
false
655,203
cpp
/*********************************************************\ * Copyright (c) 2012-2022 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ /** * @brief * Direct3D 11 RHI amalgamated/unity build implementation * * @remarks * == Dependencies == * - Direct3D 11 runtime and Direct3D 11 capable graphics driver * - Optional AMD AGS for multi-draw-indirect on AMD GPUs ("amd_ags_x64.dll" and "amd_ags_x86.dll" aren't automatically installed with the GPU driver) * - Optional NVIDIA NvAPI for multi-draw-indirect on NVIDIA GPUs ("nvapi.dll" is automatically installed with the GPU driver) * * == Preprocessor Definitions == * - Set "RHI_DIRECT3D11_EXPORTS" as preprocessor definition when building this library as shared library * - Do also have a look into the RHI header file documentation */ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <Rhi/Public/Rhi.h> // Set Windows version to Windows Vista (0x0600), we don't support Windows XP (0x0501) #ifdef WINVER #undef WINVER #endif #define WINVER 0x0600 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0600 // Exclude some stuff from "windows.h" to speed up compilation a bit #define NOGDICAPMASKS #define NOMENUS #define NOICONS #define NOKEYSTATES #define NOSYSCOMMANDS #define NORASTEROPS #define OEMRESOURCE #define NOATOM #define NOMEMMGR #define NOMETAFILE #define NOOPENFILE #define NOSCROLL #define NOSERVICE #define NOSOUND #define NOWH #define NOCOMM #define NOKANJI #define NOHELP #define NOPROFILER #define NODEFERWINDOWPOS #define NOMCX #define NOCRYPT #include <Windows.h> // Get rid of some nasty OS macros #undef max #include <VersionHelpers.h> // For "IsWindows8OrGreater()" // Disable warnings in external headers, we can't fix them PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4365) // warning C4365: 'argument': conversion from 'long' to 'unsigned int', signed/unsigned mismatch (compiling source file E:\private\unrimp\Source\Rhi\Private\Direct3D11Rhi\Direct3D11Rhi.cpp) PRAGMA_WARNING_DISABLE_MSVC(4530) // warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc PRAGMA_WARNING_DISABLE_MSVC(4623) // warning C4623: 'std::_UInt_is_zero': default constructor was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4625) // warning C4625: 'std::_Generic_error_category': copy constructor was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4626) // warning C4626: 'std::_UInt_is_zero': assignment operator was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(5026) // warning C5026: 'std::_Generic_error_category': move constructor was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(5027) // warning C5027: 'std::_UInt_is_zero': move assignment operator was implicitly defined as deleted #include <mutex> #include <vector> PRAGMA_WARNING_POP //[-------------------------------------------------------] //[ Direct3D11Rhi/MakeID.h ] //[-------------------------------------------------------] /* Author: Emil Persson, A.K.A. Humus. http://www.humus.name Version history: 1.0 - Initial release. 1.01 - Code review fixes. Code reviewed by Denis A. Gladkiy. 1.02 - Fixed an off-by-one error in DestroyRange() found by Markus Billeter License: Public Domain This file is released in the hopes that it will be useful. Use in whatever way you like, but no guarantees that it actually works or fits any particular purpose. It has been unit-tested and benchmarked though, and seems to do what it was designed to do, and seems pretty quick at it too. Notes: There are many applications where it is desired to generate unique IDs at runtime for various resources, such that they can be distinguished, sorted or otherwise processed in an efficient manner. It can in some cases replace hashes, handles and pointers. In cases where resource pointers are used as IDs, it offers a unique ID that requires far fewer bits, especially for 64bit apps. The design goal of this implementation was to return the most compact IDs as possible, limiting to a specific range if necessary. The properties of this system are as follows: - Creating a new ID returns the smallest possible unused ID. - Creating a new range of IDs returns the smallest possible continuous range of the specified size. - Created IDs remain valid until destroyed. - Destroying an ID returns it to the pool and may be returned by subsequent allocations. - The system is NOT thread-safe. Performance properties: - Creating an ID is O(1) and generally super-cheap. - Destroying an ID is also cheap, but O(log(n)), where n is the current number of distinct available ranges. - The system merges available ranges when IDs are destroyed, keeping said n generally very small in practice. - After warmup, no further memory allocations should be necessary, or be very rare. - The system uses very little memory. - It is possible to construct a pathological case where fragmentation would cause n to become large. This can be done by first allocating a very large range of IDs, then deleting every other ID, causing a new range to be allocated for every free ID, or as many ranges as there are free IDs. I believe nothing close to this situation happens in practical applications. In tests, millions of random scattered creations and deletions only resulted in a relatively short list in the worst case. This is because freed IDs are quickly reused and ranges eagerly merged. Where would this system be useful? It was originally thought up as a replacement for resource pointers as part of sort-ids in rendering. Using for instance a 64-bit sort-id packing various flags and states, putting a pointer in there takes an awful lot of bits, especially considering the actual possible resources range in the thousands at most. This got far worse of course with the switch to 64bit as pointers are now twice as large and essentially eats all bits except bottom few for alignment. Another application would be for managing a shared pool of resources. IDs could be handed out as handles and used to access the actual resource from an array. By always returning the lowest possible ID or range of IDs we get very good cache behavior since all active resources will grouped together in the bottom part of the array. Using IDs instead of pointers for handles also allows easy resizing of the allocated memory since IDs can remain the same even if the underlying storage changed. */ #ifdef RHI_DEBUG #include <cstdio> // For printf(). Remove if you don't need the PrintRanges() function (mostly for debugging anyway). #endif #include <cstdint> // uint32_t #include <limits> // std::numeric_limits<type>::max() #include <cstdlib> #include <cstring> class MakeID final { private: // Change to uint16_t here for a more compact implementation if 16bit or less IDs work for you. typedef uint16_t uint; struct Range { uint m_First; uint m_Last; }; Rhi::IAllocator& m_Allocator; Range *m_Ranges; // Sorted array of ranges of free IDs uint m_Count; // Number of ranges in list uint m_Capacity; // Total capacity of range list MakeID & operator=(const MakeID &) = delete; MakeID(const MakeID &) = delete; public: MakeID(Rhi::IAllocator& allocator, const uint max_id = std::numeric_limits<uint>::max()) : m_Allocator(allocator), m_Ranges(static_cast<Range*>(allocator.reallocate(nullptr, 0, sizeof(Range), 1))), m_Count(1), m_Capacity(1) { // Start with a single range, from 0 to max allowed ID (specified) m_Ranges[0].m_First = 0; m_Ranges[0].m_Last = max_id; } ~MakeID() { m_Allocator.reallocate(m_Ranges, 0, 0, 1); } bool CreateID(uint &id) { if (m_Ranges[0].m_First <= m_Ranges[0].m_Last) { id = m_Ranges[0].m_First; // If current range is full and there is another one, that will become the new current range if (m_Ranges[0].m_First == m_Ranges[0].m_Last && m_Count > 1) { DestroyRange(0); } else { ++m_Ranges[0].m_First; } return true; } // No available ID left return false; } bool CreateRangeID(uint &id, const uint count) { uint i = 0; do { const uint range_count = 1u + m_Ranges[i].m_Last - m_Ranges[i].m_First; if (count <= range_count) { id = m_Ranges[i].m_First; // If current range is full and there is another one, that will become the new current range if (count == range_count && i + 1 < m_Count) { DestroyRange(i); } else { m_Ranges[i].m_First += count; } return true; } ++i; } while (i < m_Count); // No range of free IDs was large enough to create the requested continuous ID sequence return false; } bool DestroyID(const uint id) { return DestroyRangeID(id, 1); } bool DestroyRangeID(const uint id, const uint count) { const uint end_id = static_cast<uint>(id + count); // Binary search of the range list uint i0 = 0u; uint i1 = m_Count - 1u; for (;;) { const uint i = (i0 + i1) / 2u; if (id < m_Ranges[i].m_First) { // Before current range, check if neighboring if (end_id >= m_Ranges[i].m_First) { if (end_id != m_Ranges[i].m_First) return false; // Overlaps a range of free IDs, thus (at least partially) invalid IDs // Neighbor id, check if neighboring previous range too if (i > i0 && id - 1 == m_Ranges[i - 1].m_Last) { // Merge with previous range m_Ranges[i - 1].m_Last = m_Ranges[i].m_Last; DestroyRange(i); } else { // Just grow range m_Ranges[i].m_First = id; } return true; } else { // Non-neighbor id if (i != i0) { // Cull upper half of list i1 = i - 1u; } else { // Found our position in the list, insert the deleted range here InsertRange(i); m_Ranges[i].m_First = id; m_Ranges[i].m_Last = end_id - 1u; return true; } } } else if (id > m_Ranges[i].m_Last) { // After current range, check if neighboring if (id - 1 == m_Ranges[i].m_Last) { // Neighbor id, check if neighboring next range too if (i < i1 && end_id == m_Ranges[i + 1].m_First) { // Merge with next range m_Ranges[i].m_Last = m_Ranges[i + 1].m_Last; DestroyRange(i + 1u); } else { // Just grow range m_Ranges[i].m_Last += count; } return true; } else { // Non-neighbor id if (i != i1) { // Cull bottom half of list i0 = i + 1u; } else { // Found our position in the list, insert the deleted range here InsertRange(i + 1u); m_Ranges[i + 1].m_First = id; m_Ranges[i + 1].m_Last = end_id - 1u; return true; } } } else { // Inside a free block, not a valid ID return false; } } } bool IsID(const uint id) const { // Binary search of the range list uint i0 = 0u; uint i1 = m_Count - 1u; for (;;) { const uint i = (i0 + i1) / 2u; if (id < m_Ranges[i].m_First) { if (i == i0) return true; // Cull upper half of list i1 = i - 1u; } else if (id > m_Ranges[i].m_Last) { if (i == i1) return true; // Cull bottom half of list i0 = i + 1u; } else { // Inside a free block, not a valid ID return false; } } } uint GetAvailableIDs() const { uint count = m_Count; uint i = 0; do { count += m_Ranges[i].m_Last - m_Ranges[i].m_First; ++i; } while (i < m_Count); return count; } uint GetLargestContinuousRange() const { uint max_count = 0; uint i = 0; do { uint count = m_Ranges[i].m_Last - m_Ranges[i].m_First + 1u; if (count > max_count) max_count = count; ++i; } while (i < m_Count); return max_count; } #ifdef RHI_DEBUG void PrintRanges() const { uint i = 0; for (;;) { if (m_Ranges[i].m_First < m_Ranges[i].m_Last) printf("%u-%u", m_Ranges[i].m_First, m_Ranges[i].m_Last); else if (m_Ranges[i].m_First == m_Ranges[i].m_Last) printf("%u", m_Ranges[i].m_First); else printf("-"); ++i; if (i >= m_Count) { printf("\n"); return; } printf(", "); } } #endif private: void InsertRange(const uint index) { if (m_Count >= m_Capacity) { m_Ranges = static_cast<Range *>(m_Allocator.reallocate(m_Ranges, sizeof(Range) * m_Capacity, (m_Capacity + m_Capacity) * sizeof(Range), 1)); m_Capacity += m_Capacity; } ::memmove(m_Ranges + index + 1, m_Ranges + index, (m_Count - index) * sizeof(Range)); ++m_Count; } void DestroyRange(const uint index) { --m_Count; ::memmove(m_Ranges + index, m_Ranges + index + 1, (m_Count - index) * sizeof(Range)); } }; //[-------------------------------------------------------] //[ Direct3D11Rhi/D3D11.h ] //[-------------------------------------------------------] /* We don't use the Direct3D headers from the DirectX SDK because there are several issues: - Licensing: It's not allowed to redistribute the Direct3D headers, meaning everyone would have to get them somehow before compiling this project - The Direct3D headers are somewhat chaotic and include tons of other headers. This slows down compilation and the more headers are included, the higher the risk of naming or redefinition conflicts. - Starting with Windows 8, Direct3D is part of the Windows SDK. When using VisualStudio 2017 and the Direct3D headers from "Microsoft DirectX SDK (June 2010)" you will get a lot of " <path>\external\directx\include\dxgitype.h(12): warning C4005: 'DXGI_STATUS_OCCLUDED' : macro redefinition c:\program files (x86)\windows kits\8.0\include\shared\winerror.h(49449) : see previous definition of 'DXGI_STATUS_OCCLUDED' " warnings. Do not include this header within headers which are usually used by users as well, do only use it inside cpp-files. It must still be possible that users of this RHI can use the Direct3D headers for features not covered by this RHI. */ //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] struct ID3D11View; struct IDXGIOutput; struct ID3D11Query; struct IDXGIDevice; struct IDXGISurface; struct IDXGIAdapter; struct ID3D11Buffer; struct IDXGIAdapter1; struct IDXGIFactory1; struct D3D11_FEATURE; struct ID3D11Counter; struct ID3D11Resource; struct IDXGISwapChain; struct IDXGISwapChain1; struct ID3D11Texture1D; struct ID3D11Texture2D; struct ID3D11Texture3D; struct ID3D11Predicate; struct ID3D11BlendState; struct D3D11_BLEND_DESC; struct D3D11_QUERY_DESC; struct ID3D11HullShader; struct ID3D11PixelShader; struct D3D11_BUFFER_DESC; struct ID3D11InputLayout; struct ID3D11CommandList; struct D3D11_COUNTER_INFO; struct D3D11_COUNTER_TYPE; struct D3D11_COUNTER_DESC; struct ID3D11ClassLinkage; struct ID3D11Asynchronous; struct ID3D11DomainShader; struct ID3D11VertexShader; struct D3D11_SAMPLER_DESC; struct ID3D11SamplerState; struct ID3D11DeviceContext; struct ID3D11ClassInstance; struct ID3D11ComputeShader; struct ID3D11GeometryShader; struct DXGI_FRAME_STATISTICS; struct ID3D11RasterizerState; struct ID3DDeviceContextState; struct D3D11_SUBRESOURCE_DATA; struct ID3D11RenderTargetView; struct ID3D11DepthStencilView; struct ID3D11DepthStencilState; struct D3D11_DEPTH_STENCIL_DESC; struct ID3D11ShaderResourceView; struct D3D11_RESOURCE_DIMENSION; struct D3D11_INPUT_ELEMENT_DESC; struct ID3D11UnorderedAccessView; struct D3D11_SO_DECLARATION_ENTRY; struct D3D11_DEPTH_STENCIL_VIEW_DESC; struct D3D11_RENDER_TARGET_VIEW_DESC; struct D3D11_SHADER_RESOURCE_VIEW_DESC; struct D3D11_UNORDERED_ACCESS_VIEW_DESC; //[-------------------------------------------------------] //[ Definitions ] //[-------------------------------------------------------] // "Microsoft DirectX SDK (June 2010)" -> "D3Dcompiler.h" #define D3DCOMPILE_DEBUG (1 << 0) #define D3DCOMPILE_SKIP_VALIDATION (1 << 1) #define D3DCOMPILE_SKIP_OPTIMIZATION (1 << 2) #define D3DCOMPILE_ENABLE_STRICTNESS (1 << 11) #define D3DCOMPILE_OPTIMIZATION_LEVEL0 (1 << 14) #define D3DCOMPILE_OPTIMIZATION_LEVEL1 0 #define D3DCOMPILE_OPTIMIZATION_LEVEL2 ((1 << 14) | (1 << 15)) #define D3DCOMPILE_OPTIMIZATION_LEVEL3 (1 << 15) #define D3DCOMPILE_WARNINGS_ARE_ERRORS (1 << 18) #define D3DCOMPILE_ALL_RESOURCES_BOUND (1 << 21) // "Microsoft DirectX SDK (June 2010)" -> "d3d9types.h" typedef DWORD D3DCOLOR; // "Microsoft DirectX SDK (June 2010)" -> "d3d9types.h" #define D3DCOLOR_ARGB(a,r,g,b) ((D3DCOLOR)((((a)&0xff)<<24) | (((r)&0xff)<<16) | (((g)&0xff)<<8) | ((b)&0xff))) #define D3DCOLOR_RGBA(r,g,b,a) D3DCOLOR_ARGB(a, r, g, b) // "Microsoft DirectX SDK (June 2010)" -> "D3X11.h" #define D3D11_SDK_VERSION (7) #define D3D11_VIEWPORT_AND_SCISSORRECT_MAX_INDEX (15) #define D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT (8) // "Microsoft DirectX SDK (June 2010)" -> "D3D10.h" #define D3D10_VIEWPORT_AND_SCISSORRECT_MAX_INDEX (15) #define D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT (8) // "Microsoft DirectX SDK (June 2010)" -> "D3X11.h" #define D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT (32) // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" #define DXGI_MWA_NO_ALT_ENTER (1 << 1) // "Microsoft DirectX SDK (June 2010)" -> "DXGIType.h" #define DXGI_USAGE_RENDER_TARGET_OUTPUT (1L << (1 + 4)) // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" #define DXGI_PRESENT_ALLOW_TEARING 0x00000200UL // "Microsoft DirectX SDK (June 2010)" -> "D3Dcommon.h" enum D3D_DRIVER_TYPE { D3D_DRIVER_TYPE_UNKNOWN = 0, D3D_DRIVER_TYPE_HARDWARE = (D3D_DRIVER_TYPE_UNKNOWN + 1), D3D_DRIVER_TYPE_REFERENCE = (D3D_DRIVER_TYPE_HARDWARE + 1), D3D_DRIVER_TYPE_NULL = (D3D_DRIVER_TYPE_REFERENCE + 1), D3D_DRIVER_TYPE_SOFTWARE = (D3D_DRIVER_TYPE_NULL + 1), D3D_DRIVER_TYPE_WARP = (D3D_DRIVER_TYPE_SOFTWARE + 1) }; // "Microsoft DirectX SDK (June 2010)" -> "D3Dcommon.h" enum D3D_FEATURE_LEVEL { D3D_FEATURE_LEVEL_9_1 = 0x9100, D3D_FEATURE_LEVEL_9_2 = 0x9200, D3D_FEATURE_LEVEL_9_3 = 0x9300, D3D_FEATURE_LEVEL_10_0 = 0xa000, D3D_FEATURE_LEVEL_10_1 = 0xa100, D3D_FEATURE_LEVEL_11_0 = 0xb000, D3D_FEATURE_LEVEL_11_1 = 0xb100 }; // "Microsoft DirectX SDK (June 2010)" -> "D3Dcommon.h" enum D3D_SRV_DIMENSION { D3D_SRV_DIMENSION_UNKNOWN = 0, D3D_SRV_DIMENSION_BUFFER = 1, D3D_SRV_DIMENSION_TEXTURE1D = 2, D3D_SRV_DIMENSION_TEXTURE1DARRAY = 3, D3D_SRV_DIMENSION_TEXTURE2D = 4, D3D_SRV_DIMENSION_TEXTURE2DARRAY = 5, D3D_SRV_DIMENSION_TEXTURE2DMS = 6, D3D_SRV_DIMENSION_TEXTURE2DMSARRAY = 7, D3D_SRV_DIMENSION_TEXTURE3D = 8, D3D_SRV_DIMENSION_TEXTURECUBE = 9, D3D_SRV_DIMENSION_TEXTURECUBEARRAY = 10, D3D_SRV_DIMENSION_BUFFEREX = 11, D3D11_SRV_DIMENSION_UNKNOWN = D3D_SRV_DIMENSION_UNKNOWN, D3D11_SRV_DIMENSION_BUFFER = D3D_SRV_DIMENSION_BUFFER, D3D11_SRV_DIMENSION_TEXTURE1D = D3D_SRV_DIMENSION_TEXTURE1D, D3D11_SRV_DIMENSION_TEXTURE1DARRAY = D3D_SRV_DIMENSION_TEXTURE1DARRAY, D3D11_SRV_DIMENSION_TEXTURE2D = D3D_SRV_DIMENSION_TEXTURE2D, D3D11_SRV_DIMENSION_TEXTURE2DARRAY = D3D_SRV_DIMENSION_TEXTURE2DARRAY, D3D11_SRV_DIMENSION_TEXTURE2DMS = D3D_SRV_DIMENSION_TEXTURE2DMS, D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY = D3D_SRV_DIMENSION_TEXTURE2DMSARRAY, D3D11_SRV_DIMENSION_TEXTURE3D = D3D_SRV_DIMENSION_TEXTURE3D, D3D11_SRV_DIMENSION_TEXTURECUBE = D3D_SRV_DIMENSION_TEXTURECUBE, D3D11_SRV_DIMENSION_TEXTURECUBEARRAY = D3D_SRV_DIMENSION_TEXTURECUBEARRAY, D3D11_SRV_DIMENSION_BUFFEREX = D3D_SRV_DIMENSION_BUFFEREX }; typedef D3D_SRV_DIMENSION D3D11_SRV_DIMENSION; // "Microsoft DirectX SDK (June 2010)" -> "D3Dcommon.h" enum D3D11_PRIMITIVE_TOPOLOGY { D3D_PRIMITIVE_TOPOLOGY_UNDEFINED = 0, D3D_PRIMITIVE_TOPOLOGY_POINTLIST = 1, D3D_PRIMITIVE_TOPOLOGY_LINELIST = 2, D3D_PRIMITIVE_TOPOLOGY_LINESTRIP = 3, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4, D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5, D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10, D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12, D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13, D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = 33, D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = 34, D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = 35, D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = 36, D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = 37, D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = 38, D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = 39, D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = 40, D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = 41, D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = 42, D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = 43, D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = 44, D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = 45, D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = 46, D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = 47, D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = 48, D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = 49, D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = 50, D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = 51, D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = 52, D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = 53, D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = 54, D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = 55, D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = 56, D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = 57, D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = 58, D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = 59, D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = 60, D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = 61, D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = 62, D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = 63, D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = 64, D3D10_PRIMITIVE_TOPOLOGY_UNDEFINED = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED, D3D10_PRIMITIVE_TOPOLOGY_POINTLIST = D3D_PRIMITIVE_TOPOLOGY_POINTLIST, D3D10_PRIMITIVE_TOPOLOGY_LINELIST = D3D_PRIMITIVE_TOPOLOGY_LINELIST, D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, D3D10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ, D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ, D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ, D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ, D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED, D3D11_PRIMITIVE_TOPOLOGY_POINTLIST = D3D_PRIMITIVE_TOPOLOGY_POINTLIST, D3D11_PRIMITIVE_TOPOLOGY_LINELIST = D3D_PRIMITIVE_TOPOLOGY_LINELIST, D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ, D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ, D3D11_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST }; // "Microsoft DirectX SDK (June 2010)" -> "D3Dcommon.h" struct D3D_SHADER_MACRO { LPCSTR Name; LPCSTR Definition; }; enum D3D_INCLUDE_TYPE { D3D_INCLUDE_LOCAL = 0, D3D_INCLUDE_SYSTEM = (D3D_INCLUDE_LOCAL + 1), D3D10_INCLUDE_LOCAL = D3D_INCLUDE_LOCAL, D3D10_INCLUDE_SYSTEM = D3D_INCLUDE_SYSTEM, D3D_INCLUDE_FORCE_DWORD = 0x7fffffff }; DECLARE_INTERFACE(ID3DInclude) { STDMETHOD(Open)(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) PURE; STDMETHOD(Close)(THIS_ LPCVOID pData) PURE; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D10shader.h" typedef D3D_SHADER_MACRO D3D10_SHADER_MACRO; typedef __interface ID3DInclude *LPD3D10INCLUDE; // "Microsoft DirectX SDK (June 2010)" -> "DXGIFormat.h" enum DXGI_FORMAT { DXGI_FORMAT_UNKNOWN = 0, DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, DXGI_FORMAT_R32G32B32A32_FLOAT = 2, DXGI_FORMAT_R32G32B32A32_UINT = 3, DXGI_FORMAT_R32G32B32A32_SINT = 4, DXGI_FORMAT_R32G32B32_TYPELESS = 5, DXGI_FORMAT_R32G32B32_FLOAT = 6, DXGI_FORMAT_R32G32B32_UINT = 7, DXGI_FORMAT_R32G32B32_SINT = 8, DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, DXGI_FORMAT_R16G16B16A16_FLOAT = 10, DXGI_FORMAT_R16G16B16A16_UNORM = 11, DXGI_FORMAT_R16G16B16A16_UINT = 12, DXGI_FORMAT_R16G16B16A16_SNORM = 13, DXGI_FORMAT_R16G16B16A16_SINT = 14, DXGI_FORMAT_R32G32_TYPELESS = 15, DXGI_FORMAT_R32G32_FLOAT = 16, DXGI_FORMAT_R32G32_UINT = 17, DXGI_FORMAT_R32G32_SINT = 18, DXGI_FORMAT_R32G8X24_TYPELESS = 19, DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, DXGI_FORMAT_R10G10B10A2_UNORM = 24, DXGI_FORMAT_R10G10B10A2_UINT = 25, DXGI_FORMAT_R11G11B10_FLOAT = 26, DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, DXGI_FORMAT_R8G8B8A8_UNORM = 28, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, DXGI_FORMAT_R8G8B8A8_UINT = 30, DXGI_FORMAT_R8G8B8A8_SNORM = 31, DXGI_FORMAT_R8G8B8A8_SINT = 32, DXGI_FORMAT_R16G16_TYPELESS = 33, DXGI_FORMAT_R16G16_FLOAT = 34, DXGI_FORMAT_R16G16_UNORM = 35, DXGI_FORMAT_R16G16_UINT = 36, DXGI_FORMAT_R16G16_SNORM = 37, DXGI_FORMAT_R16G16_SINT = 38, DXGI_FORMAT_R32_TYPELESS = 39, DXGI_FORMAT_D32_FLOAT = 40, DXGI_FORMAT_R32_FLOAT = 41, DXGI_FORMAT_R32_UINT = 42, DXGI_FORMAT_R32_SINT = 43, DXGI_FORMAT_R24G8_TYPELESS = 44, DXGI_FORMAT_D24_UNORM_S8_UINT = 45, DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, DXGI_FORMAT_R8G8_TYPELESS = 48, DXGI_FORMAT_R8G8_UNORM = 49, DXGI_FORMAT_R8G8_UINT = 50, DXGI_FORMAT_R8G8_SNORM = 51, DXGI_FORMAT_R8G8_SINT = 52, DXGI_FORMAT_R16_TYPELESS = 53, DXGI_FORMAT_R16_FLOAT = 54, DXGI_FORMAT_D16_UNORM = 55, DXGI_FORMAT_R16_UNORM = 56, DXGI_FORMAT_R16_UINT = 57, DXGI_FORMAT_R16_SNORM = 58, DXGI_FORMAT_R16_SINT = 59, DXGI_FORMAT_R8_TYPELESS = 60, DXGI_FORMAT_R8_UNORM = 61, DXGI_FORMAT_R8_UINT = 62, DXGI_FORMAT_R8_SNORM = 63, DXGI_FORMAT_R8_SINT = 64, DXGI_FORMAT_A8_UNORM = 65, DXGI_FORMAT_R1_UNORM = 66, DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, DXGI_FORMAT_R8G8_B8G8_UNORM = 68, DXGI_FORMAT_G8R8_G8B8_UNORM = 69, DXGI_FORMAT_BC1_TYPELESS = 70, DXGI_FORMAT_BC1_UNORM = 71, DXGI_FORMAT_BC1_UNORM_SRGB = 72, DXGI_FORMAT_BC2_TYPELESS = 73, DXGI_FORMAT_BC2_UNORM = 74, DXGI_FORMAT_BC2_UNORM_SRGB = 75, DXGI_FORMAT_BC3_TYPELESS = 76, DXGI_FORMAT_BC3_UNORM = 77, DXGI_FORMAT_BC3_UNORM_SRGB = 78, DXGI_FORMAT_BC4_TYPELESS = 79, DXGI_FORMAT_BC4_UNORM = 80, DXGI_FORMAT_BC4_SNORM = 81, DXGI_FORMAT_BC5_TYPELESS = 82, DXGI_FORMAT_BC5_UNORM = 83, DXGI_FORMAT_BC5_SNORM = 84, DXGI_FORMAT_B5G6R5_UNORM = 85, DXGI_FORMAT_B5G5R5A1_UNORM = 86, DXGI_FORMAT_B8G8R8A8_UNORM = 87, DXGI_FORMAT_B8G8R8X8_UNORM = 88, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, DXGI_FORMAT_B8G8R8A8_TYPELESS = 90, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91, DXGI_FORMAT_B8G8R8X8_TYPELESS = 92, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93, DXGI_FORMAT_BC6H_TYPELESS = 94, DXGI_FORMAT_BC6H_UF16 = 95, DXGI_FORMAT_BC6H_SF16 = 96, DXGI_FORMAT_BC7_TYPELESS = 97, DXGI_FORMAT_BC7_UNORM = 98, DXGI_FORMAT_BC7_UNORM_SRGB = 99, DXGI_FORMAT_FORCE_UINT = 0xffffffff }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" inline UINT D3D11CalcSubresource(UINT MipSlice, UINT ArraySlice, UINT MipLevels) { return MipSlice + ArraySlice * MipLevels; } // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_CREATE_DEVICE_FLAG { D3D11_CREATE_DEVICE_SINGLETHREADED = 0x1, D3D11_CREATE_DEVICE_DEBUG = 0x2, D3D11_CREATE_DEVICE_SWITCH_TO_REF = 0x4, D3D11_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS = 0x8, D3D11_CREATE_DEVICE_BGRA_SUPPORT = 0x20 }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_BOX { UINT left; UINT top; UINT front; UINT right; UINT bottom; UINT back; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_VIEWPORT { FLOAT TopLeftX; FLOAT TopLeftY; FLOAT Width; FLOAT Height; FLOAT MinDepth; FLOAT MaxDepth; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef RECT D3D11_RECT; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_RTV_DIMENSION { D3D11_RTV_DIMENSION_UNKNOWN = 0, D3D11_RTV_DIMENSION_BUFFER = 1, D3D11_RTV_DIMENSION_TEXTURE1D = 2, D3D11_RTV_DIMENSION_TEXTURE1DARRAY = 3, D3D11_RTV_DIMENSION_TEXTURE2D = 4, D3D11_RTV_DIMENSION_TEXTURE2DARRAY = 5, D3D11_RTV_DIMENSION_TEXTURE2DMS = 6, D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY = 7, D3D11_RTV_DIMENSION_TEXTURE3D = 8 }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_DSV_DIMENSION { D3D11_DSV_DIMENSION_UNKNOWN = 0, D3D11_DSV_DIMENSION_TEXTURE1D = 1, D3D11_DSV_DIMENSION_TEXTURE1DARRAY = 2, D3D11_DSV_DIMENSION_TEXTURE2D = 3, D3D11_DSV_DIMENSION_TEXTURE2DARRAY = 4, D3D11_DSV_DIMENSION_TEXTURE2DMS = 5, D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY = 6 }; // "Microsoft DirectX SDK (June 2010)" -> "DXGIType.h" struct DXGI_SAMPLE_DESC { UINT Count; UINT Quality; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct IDXGIObject : public IUnknown { virtual HRESULT STDMETHODCALLTYPE SetPrivateData(__in REFGUID Name, UINT DataSize, __in_bcount(DataSize) const void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(__in REFGUID Name, __in const IUnknown *pUnknown) = 0; virtual HRESULT STDMETHODCALLTYPE GetPrivateData(__in REFGUID Name, __inout UINT *pDataSize, __out_bcount(*pDataSize) void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE GetParent(__in REFIID riid, __out void **ppParent) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "DXGIType.h" struct DXGI_RATIONAL { UINT Numerator; UINT Denominator; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGIType.h" enum DXGI_MODE_SCANLINE_ORDER { DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED = 0, DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE = 1, DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST = 2, DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST = 3 }; // "Microsoft DirectX SDK (June 2010)" -> "DXGIType.h" enum DXGI_MODE_SCALING { DXGI_MODE_SCALING_UNSPECIFIED = 0, DXGI_MODE_SCALING_CENTERED = 1, DXGI_MODE_SCALING_STRETCHED = 2 }; // "Microsoft DirectX SDK (June 2010)" -> "DXGIType.h" struct DXGI_MODE_DESC { UINT Width; UINT Height; DXGI_RATIONAL RefreshRate; DXGI_FORMAT Format; DXGI_MODE_SCANLINE_ORDER ScanlineOrdering; DXGI_MODE_SCALING Scaling; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" typedef UINT DXGI_USAGE; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" enum DXGI_SWAP_EFFECT { DXGI_SWAP_EFFECT_DISCARD = 0, DXGI_SWAP_EFFECT_SEQUENTIAL = 1, DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL = 3, DXGI_SWAP_EFFECT_FLIP_DISCARD = 4 }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" typedef enum DXGI_SWAP_CHAIN_FLAG { DXGI_SWAP_CHAIN_FLAG_NONPREROTATED = 1, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH = 2, DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE = 4, DXGI_SWAP_CHAIN_FLAG_RESTRICTED_CONTENT = 8, DXGI_SWAP_CHAIN_FLAG_RESTRICT_SHARED_RESOURCE_DRIVER = 16, DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY = 32, DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT = 64, DXGI_SWAP_CHAIN_FLAG_FOREGROUND_LAYER = 128, DXGI_SWAP_CHAIN_FLAG_FULLSCREEN_VIDEO = 256, DXGI_SWAP_CHAIN_FLAG_YUV_VIDEO = 512, DXGI_SWAP_CHAIN_FLAG_HW_PROTECTED = 1024, DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING = 2048, DXGI_SWAP_CHAIN_FLAG_RESTRICTED_TO_ALL_HOLOGRAPHIC_DISPLAYS = 4096 } DXGI_SWAP_CHAIN_FLAG; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" struct DXGI_SWAP_CHAIN_DESC { DXGI_MODE_DESC BufferDesc; DXGI_SAMPLE_DESC SampleDesc; DXGI_USAGE BufferUsage; UINT BufferCount; HWND OutputWindow; BOOL Windowed; DXGI_SWAP_EFFECT SwapEffect; UINT Flags; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" MIDL_INTERFACE("7b7166ec-21c7-44ae-b21a-c9ae321ae369") IDXGIFactory : public IDXGIObject { virtual HRESULT STDMETHODCALLTYPE EnumAdapters(UINT Adapter, __out IDXGIAdapter **ppAdapter) = 0; virtual HRESULT STDMETHODCALLTYPE MakeWindowAssociation(HWND WindowHandle, UINT Flags) = 0; virtual HRESULT STDMETHODCALLTYPE GetWindowAssociation(__out HWND *pWindowHandle) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSwapChain(__in IUnknown *pDevice, __in DXGI_SWAP_CHAIN_DESC *pDesc, __out IDXGISwapChain **ppSwapChain) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter(HMODULE Module, __out IDXGIAdapter **ppAdapter) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" MIDL_INTERFACE("770aae78-f26f-4dba-a829-253c83d1b387") IDXGIFactory1 : public IDXGIFactory { virtual HRESULT STDMETHODCALLTYPE EnumAdapters1(UINT Adapter, __out IDXGIAdapter1 **ppAdapter) = 0; virtual BOOL STDMETHODCALLTYPE IsCurrent(void) = 0; }; // "Windows 10 SDK" -> "dxgi1_2.h" typedef enum DXGI_SCALING { DXGI_SCALING_STRETCH = 0, DXGI_SCALING_NONE = 1, DXGI_SCALING_ASPECT_RATIO_STRETCH = 2 } DXGI_SCALING; // "Windows 10 SDK" -> "dxgi1_2.h" typedef enum DXGI_ALPHA_MODE { DXGI_ALPHA_MODE_UNSPECIFIED = 0, DXGI_ALPHA_MODE_PREMULTIPLIED = 1, DXGI_ALPHA_MODE_STRAIGHT = 2, DXGI_ALPHA_MODE_IGNORE = 3, DXGI_ALPHA_MODE_FORCE_DWORD = 0xffffffff } DXGI_ALPHA_MODE; // "Windows 10 SDK" -> "dxgi1_2.h" typedef struct DXGI_SWAP_CHAIN_DESC1 { UINT Width; UINT Height; DXGI_FORMAT Format; BOOL Stereo; DXGI_SAMPLE_DESC SampleDesc; DXGI_USAGE BufferUsage; UINT BufferCount; DXGI_SCALING Scaling; DXGI_SWAP_EFFECT SwapEffect; DXGI_ALPHA_MODE AlphaMode; UINT Flags; } DXGI_SWAP_CHAIN_DESC1; // "Windows 10 SDK" -> "dxgi1_2.h" typedef struct DXGI_SWAP_CHAIN_FULLSCREEN_DESC { DXGI_RATIONAL RefreshRate; DXGI_MODE_SCANLINE_ORDER ScanlineOrdering; DXGI_MODE_SCALING Scaling; BOOL Windowed; } DXGI_SWAP_CHAIN_FULLSCREEN_DESC; // "Windows 10 SDK" -> "dxgi1_2.h" MIDL_INTERFACE("50c83a1c-e072-4c48-87b0-3630fa36a6d0") IDXGIFactory2 : public IDXGIFactory1 { virtual BOOL STDMETHODCALLTYPE IsWindowedStereoEnabled(void) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSwapChainForHwnd(_In_ IUnknown *pDevice, _In_ HWND hWnd, _In_ const DXGI_SWAP_CHAIN_DESC1 *pDesc, _In_opt_ const DXGI_SWAP_CHAIN_FULLSCREEN_DESC *pFullscreenDesc, _In_opt_ IDXGIOutput *pRestrictToOutput, _COM_Outptr_ IDXGISwapChain1 **ppSwapChain) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSwapChainForCoreWindow(_In_ IUnknown *pDevice, _In_ IUnknown *pWindow, _In_ const DXGI_SWAP_CHAIN_DESC1 *pDesc, _In_opt_ IDXGIOutput *pRestrictToOutput, _COM_Outptr_ IDXGISwapChain1 **ppSwapChain) = 0; virtual HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(_In_ HANDLE hResource, _Out_ LUID *pLuid) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(_In_ HWND WindowHandle, _In_ UINT wMsg, _Out_ DWORD *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterStereoStatusEvent(_In_ HANDLE hEvent, _Out_ DWORD *pdwCookie) = 0; virtual void STDMETHODCALLTYPE UnregisterStereoStatus(_In_ DWORD dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusWindow(_In_ HWND WindowHandle, _In_ UINT wMsg, _Out_ DWORD *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusEvent(_In_ HANDLE hEvent, _Out_ DWORD *pdwCookie) = 0; virtual void STDMETHODCALLTYPE UnregisterOcclusionStatus(_In_ DWORD dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSwapChainForComposition(_In_ IUnknown *pDevice, _In_ const DXGI_SWAP_CHAIN_DESC1 *pDesc, _In_opt_ IDXGIOutput *pRestrictToOutput, _COM_Outptr_ IDXGISwapChain1 **ppSwapChain) = 0; }; // "Windows 10 SDK" -> "dxgi1_3.h" MIDL_INTERFACE("25483823-cd46-4c7d-86ca-47aa95b837bd") IDXGIFactory3 : public IDXGIFactory2 { virtual UINT STDMETHODCALLTYPE GetCreationFlags(void) = 0; }; // "Windows 10 SDK" -> "dxgi1_4.h" MIDL_INTERFACE("1bc6ea02-ef36-464f-bf0c-21ca39e5168a") IDXGIFactory4 : public IDXGIFactory3 { virtual HRESULT STDMETHODCALLTYPE EnumAdapterByLuid(_In_ LUID AdapterLuid, _In_ REFIID riid, _COM_Outptr_ void **ppvAdapter) = 0; virtual HRESULT STDMETHODCALLTYPE EnumWarpAdapter(_In_ REFIID riid, _COM_Outptr_ void **ppvAdapter) = 0; }; // "Windows 10 SDK" -> "dxgi1_5.h" typedef enum DXGI_FEATURE { DXGI_FEATURE_PRESENT_ALLOW_TEARING = 0 } DXGI_FEATURE; // "Windows 10 SDK" -> "dxgi1_5.h" MIDL_INTERFACE("7632e1f5-ee65-4dca-87fd-84cd75f8838d") IDXGIFactory5 : public IDXGIFactory4 { virtual HRESULT STDMETHODCALLTYPE CheckFeatureSupport(DXGI_FEATURE Feature, _Inout_updates_bytes_(FeatureSupportDataSize) void *pFeatureSupportData, UINT FeatureSupportDataSize) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" struct DXGI_ADAPTER_DESC { WCHAR Description[128]; UINT VendorId; UINT DeviceId; UINT SubSysId; UINT Revision; SIZE_T DedicatedVideoMemory; SIZE_T DedicatedSystemMemory; SIZE_T SharedSystemMemory; LUID AdapterLuid; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct IDXGIAdapter : public IDXGIObject { virtual HRESULT STDMETHODCALLTYPE EnumOutputs(UINT Output, __out IDXGIOutput **ppOutput) = 0; virtual HRESULT STDMETHODCALLTYPE GetDesc(__out DXGI_ADAPTER_DESC *pDesc) = 0; virtual HRESULT STDMETHODCALLTYPE CheckInterfaceSupport(__in REFGUID InterfaceName, __out LARGE_INTEGER *pUMDVersion) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" struct DXGI_SURFACE_DESC { UINT Width; UINT Height; DXGI_FORMAT Format; DXGI_SAMPLE_DESC SampleDesc; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" struct DXGI_SHARED_RESOURCE { HANDLE Handle; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" enum DXGI_RESIDENCY { DXGI_RESIDENCY_FULLY_RESIDENT = 1, DXGI_RESIDENCY_RESIDENT_IN_SHARED_MEMORY = 2, DXGI_RESIDENCY_EVICTED_TO_DISK = 3 }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" MIDL_INTERFACE("54ec77fa-1377-44e6-8c32-88fd5f44c84c") IDXGIDevice : public IDXGIObject { virtual HRESULT STDMETHODCALLTYPE GetAdapter(__out IDXGIAdapter **pAdapter) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSurface(__in const DXGI_SURFACE_DESC *pDesc, UINT NumSurfaces, DXGI_USAGE Usage, __in_opt const DXGI_SHARED_RESOURCE *pSharedResource, __out IDXGISurface **ppSurface) = 0; virtual HRESULT STDMETHODCALLTYPE QueryResourceResidency(__in_ecount(NumResources) IUnknown *const *ppResources, __out_ecount(NumResources) DXGI_RESIDENCY *pResidencyStatus, UINT NumResources) = 0; virtual HRESULT STDMETHODCALLTYPE SetGPUThreadPriority(INT Priority) = 0; virtual HRESULT STDMETHODCALLTYPE GetGPUThreadPriority(__out INT *pPriority) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct IDXGIDeviceSubObject : public IDXGIObject { virtual HRESULT STDMETHODCALLTYPE GetDevice(__in REFIID riid, __out void **ppDevice) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct IDXGISwapChain : public IDXGIDeviceSubObject { virtual HRESULT STDMETHODCALLTYPE Present(UINT SyncInterval, UINT Flags) = 0; virtual HRESULT STDMETHODCALLTYPE GetBuffer(UINT Buffer, __in REFIID riid, __out void **ppSurface) = 0; virtual HRESULT STDMETHODCALLTYPE SetFullscreenState(BOOL Fullscreen, __in_opt IDXGIOutput *pTarget) = 0; virtual HRESULT STDMETHODCALLTYPE GetFullscreenState(__out BOOL *pFullscreen, __out IDXGIOutput **ppTarget) = 0; virtual HRESULT STDMETHODCALLTYPE GetDesc(__out DXGI_SWAP_CHAIN_DESC *pDesc) = 0; virtual HRESULT STDMETHODCALLTYPE ResizeBuffers(UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags) = 0; virtual HRESULT STDMETHODCALLTYPE ResizeTarget(__in const DXGI_MODE_DESC *pNewTargetParameters) = 0; virtual HRESULT STDMETHODCALLTYPE GetContainingOutput(__out IDXGIOutput **ppOutput) = 0; virtual HRESULT STDMETHODCALLTYPE GetFrameStatistics(__out DXGI_FRAME_STATISTICS *pStats) = 0; virtual HRESULT STDMETHODCALLTYPE GetLastPresentCount(__out UINT *pLastPresentCount) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_DEVICE_CONTEXT_TYPE { D3D11_DEVICE_CONTEXT_IMMEDIATE = 0, D3D11_DEVICE_CONTEXT_DEFERRED = (D3D11_DEVICE_CONTEXT_IMMEDIATE + 1) }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_CLEAR_FLAG { D3D11_CLEAR_DEPTH = 0x1L, D3D11_CLEAR_STENCIL = 0x2L }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_USAGE { D3D11_USAGE_DEFAULT = 0, D3D11_USAGE_IMMUTABLE = 1, D3D11_USAGE_DYNAMIC = 2, D3D11_USAGE_STAGING = 3 }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_MAP { D3D11_MAP_READ = 1, D3D11_MAP_WRITE = 2, D3D11_MAP_READ_WRITE = 3, D3D11_MAP_WRITE_DISCARD = 4, D3D11_MAP_WRITE_NO_OVERWRITE = 5 }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_BIND_FLAG { D3D11_BIND_VERTEX_BUFFER = 0x1L, D3D11_BIND_INDEX_BUFFER = 0x2L, D3D11_BIND_CONSTANT_BUFFER = 0x4L, D3D11_BIND_SHADER_RESOURCE = 0x8L, D3D11_BIND_STREAM_OUTPUT = 0x10L, D3D11_BIND_RENDER_TARGET = 0x20L, D3D11_BIND_DEPTH_STENCIL = 0x40L, D3D11_BIND_UNORDERED_ACCESS = 0x80L }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_CPU_ACCESS_FLAG { D3D11_CPU_ACCESS_WRITE = 0x10000L, D3D11_CPU_ACCESS_READ = 0x20000L }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_RESOURCE_MISC_FLAG { D3D11_RESOURCE_MISC_GENERATE_MIPS = 0x1L, D3D11_RESOURCE_MISC_SHARED = 0x2L, D3D11_RESOURCE_MISC_TEXTURECUBE = 0x4L, D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS = 0x10L, D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS = 0x20L, D3D11_RESOURCE_MISC_BUFFER_STRUCTURED = 0x40L, D3D11_RESOURCE_MISC_RESOURCE_CLAMP = 0x80L, D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX = 0x100L, D3D11_RESOURCE_MISC_GDI_COMPATIBLE = 0x200L, D3D11_RESOURCE_MISC_SHARED_NTHANDLE = 0x800L, D3D11_RESOURCE_MISC_RESTRICTED_CONTENT = 0x1000L, D3D11_RESOURCE_MISC_RESTRICT_SHARED_RESOURCE = 0x2000L, D3D11_RESOURCE_MISC_RESTRICT_SHARED_RESOURCE_DRIVER = 0x4000L, D3D11_RESOURCE_MISC_GUARDED = 0x8000L, D3D11_RESOURCE_MISC_TILE_POOL = 0x20000L, D3D11_RESOURCE_MISC_TILED = 0x40000L } D3D11_RESOURCE_MISC_FLAG; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_BUFFER_DESC { UINT ByteWidth; D3D11_USAGE Usage; UINT BindFlags; UINT CPUAccessFlags; UINT MiscFlags; UINT StructureByteStride; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_BUFFER_RTV { union { UINT FirstElement; UINT ElementOffset; }; union { UINT NumElements; UINT ElementWidth; }; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX1D_RTV { UINT MipSlice; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX1D_ARRAY_RTV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2D_RTV { UINT MipSlice; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2DMS_RTV { UINT UnusedField_NothingToDefine; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2D_ARRAY_RTV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2DMS_ARRAY_RTV { UINT FirstArraySlice; UINT ArraySize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX3D_RTV { UINT MipSlice; UINT FirstWSlice; UINT WSize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_TEXTURE1D_DESC { UINT Width; UINT MipLevels; UINT ArraySize; DXGI_FORMAT Format; D3D11_USAGE Usage; UINT BindFlags; UINT CPUAccessFlags; UINT MiscFlags; } D3D11_TEXTURE1D_DESC; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEXTURE2D_DESC { UINT Width; UINT Height; UINT MipLevels; UINT ArraySize; DXGI_FORMAT Format; DXGI_SAMPLE_DESC SampleDesc; D3D11_USAGE Usage; UINT BindFlags; UINT CPUAccessFlags; UINT MiscFlags; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_TEXTURE3D_DESC { UINT Width; UINT Height; UINT Depth; UINT MipLevels; DXGI_FORMAT Format; D3D11_USAGE Usage; UINT BindFlags; UINT CPUAccessFlags; UINT MiscFlags; } D3D11_TEXTURE3D_DESC; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX1D_DSV { UINT MipSlice; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX1D_ARRAY_DSV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2D_DSV { UINT MipSlice; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2D_ARRAY_DSV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2DMS_DSV { UINT UnusedField_NothingToDefine; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2DMS_ARRAY_DSV { UINT FirstArraySlice; UINT ArraySize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_SUBRESOURCE_DATA { const void *pSysMem; UINT SysMemPitch; UINT SysMemSlicePitch; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_MAPPED_SUBRESOURCE { void *pData; UINT RowPitch; UINT DepthPitch; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_BUFFER_SRV { union { UINT FirstElement; UINT ElementOffset; }; union { UINT NumElements; UINT ElementWidth; }; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_BUFFEREX_SRV_FLAG { D3D11_BUFFEREX_SRV_FLAG_RAW = 0x1 } D3D11_BUFFEREX_SRV_FLAG; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX1D_SRV { UINT MostDetailedMip; UINT MipLevels; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX1D_ARRAY_SRV { UINT MostDetailedMip; UINT MipLevels; UINT FirstArraySlice; UINT ArraySize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2D_SRV { UINT MostDetailedMip; UINT MipLevels; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2D_ARRAY_SRV { UINT MostDetailedMip; UINT MipLevels; UINT FirstArraySlice; UINT ArraySize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX3D_SRV { UINT MostDetailedMip; UINT MipLevels; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEXCUBE_SRV { UINT MostDetailedMip; UINT MipLevels; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEXCUBE_ARRAY_SRV { UINT MostDetailedMip; UINT MipLevels; UINT First2DArrayFace; UINT NumCubes; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2DMS_SRV { UINT UnusedField_NothingToDefine; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_TEX2DMS_ARRAY_SRV { UINT FirstArraySlice; UINT ArraySize; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_BUFFEREX_SRV { UINT FirstElement; UINT NumElements; UINT Flags; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_SHADER_RESOURCE_VIEW_DESC { DXGI_FORMAT Format; D3D11_SRV_DIMENSION ViewDimension; union { D3D11_BUFFER_SRV Buffer; D3D11_TEX1D_SRV Texture1D; D3D11_TEX1D_ARRAY_SRV Texture1DArray; D3D11_TEX2D_SRV Texture2D; D3D11_TEX2D_ARRAY_SRV Texture2DArray; D3D11_TEX2DMS_SRV Texture2DMS; D3D11_TEX2DMS_ARRAY_SRV Texture2DMSArray; D3D11_TEX3D_SRV Texture3D; D3D11_TEXCUBE_SRV TextureCube; D3D11_TEXCUBE_ARRAY_SRV TextureCubeArray; D3D11_BUFFEREX_SRV BufferEx; }; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_UAV_DIMENSION { D3D11_UAV_DIMENSION_UNKNOWN = 0, D3D11_UAV_DIMENSION_BUFFER = 1, D3D11_UAV_DIMENSION_TEXTURE1D = 2, D3D11_UAV_DIMENSION_TEXTURE1DARRAY = 3, D3D11_UAV_DIMENSION_TEXTURE2D = 4, D3D11_UAV_DIMENSION_TEXTURE2DARRAY = 5, D3D11_UAV_DIMENSION_TEXTURE3D = 8 } D3D11_UAV_DIMENSION; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_BUFFER_UAV_FLAG { D3D11_BUFFER_UAV_FLAG_RAW = 0x1, D3D11_BUFFER_UAV_FLAG_APPEND = 0x2, D3D11_BUFFER_UAV_FLAG_COUNTER = 0x4 } D3D11_BUFFER_UAV_FLAG; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_BUFFER_UAV { UINT FirstElement; UINT NumElements; UINT Flags; } D3D11_BUFFER_UAV; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_TEX1D_UAV { UINT MipSlice; } D3D11_TEX1D_UAV; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_TEX1D_ARRAY_UAV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; } D3D11_TEX1D_ARRAY_UAV; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_TEX2D_UAV { UINT MipSlice; } D3D11_TEX2D_UAV; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_TEX2D_ARRAY_UAV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; } D3D11_TEX2D_ARRAY_UAV; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_TEX3D_UAV { UINT MipSlice; UINT FirstWSlice; UINT WSize; } D3D11_TEX3D_UAV; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_UNORDERED_ACCESS_VIEW_DESC { DXGI_FORMAT Format; D3D11_UAV_DIMENSION ViewDimension; union { D3D11_BUFFER_UAV Buffer; D3D11_TEX1D_UAV Texture1D; D3D11_TEX1D_ARRAY_UAV Texture1DArray; D3D11_TEX2D_UAV Texture2D; D3D11_TEX2D_ARRAY_UAV Texture2DArray; D3D11_TEX3D_UAV Texture3D; }; } D3D11_UNORDERED_ACCESS_VIEW_DESC; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_DEPTH_STENCIL_VIEW_DESC { DXGI_FORMAT Format; D3D11_DSV_DIMENSION ViewDimension; UINT Flags; union { D3D11_TEX1D_DSV Texture1D; D3D11_TEX1D_ARRAY_DSV Texture1DArray; D3D11_TEX2D_DSV Texture2D; D3D11_TEX2D_ARRAY_DSV Texture2DArray; D3D11_TEX2DMS_DSV Texture2DMS; D3D11_TEX2DMS_ARRAY_DSV Texture2DMSArray; }; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_RENDER_TARGET_VIEW_DESC { DXGI_FORMAT Format; D3D11_RTV_DIMENSION ViewDimension; union { D3D11_BUFFER_RTV Buffer; D3D11_TEX1D_RTV Texture1D; D3D11_TEX1D_ARRAY_RTV Texture1DArray; D3D11_TEX2D_RTV Texture2D; D3D11_TEX2D_ARRAY_RTV Texture2DArray; D3D11_TEX2DMS_RTV Texture2DMS; D3D11_TEX2DMS_ARRAY_RTV Texture2DMSArray; D3D11_TEX3D_RTV Texture3D; }; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_INPUT_CLASSIFICATION { D3D11_INPUT_PER_VERTEX_DATA = 0, D3D11_INPUT_PER_INSTANCE_DATA = 1 }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_INPUT_ELEMENT_DESC { LPCSTR SemanticName; UINT SemanticIndex; DXGI_FORMAT Format; UINT InputSlot; UINT AlignedByteOffset; D3D11_INPUT_CLASSIFICATION InputSlotClass; UINT InstanceDataStepRate; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_FILL_MODE { D3D11_FILL_WIREFRAME = 2, D3D11_FILL_SOLID = 3 } D3D11_FILL_MODE; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_CULL_MODE { D3D11_CULL_NONE = 1, D3D11_CULL_FRONT = 2, D3D11_CULL_BACK = 3 } D3D11_CULL_MODE; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_RASTERIZER_DESC { D3D11_FILL_MODE FillMode; D3D11_CULL_MODE CullMode; BOOL FrontCounterClockwise; INT DepthBias; FLOAT DepthBiasClamp; FLOAT SlopeScaledDepthBias; BOOL DepthClipEnable; BOOL ScissorEnable; BOOL MultisampleEnable; BOOL AntialiasedLineEnable; } D3D11_RASTERIZER_DESC; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_FILTER { D3D11_FILTER_MIN_MAG_MIP_POINT = 0, D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1, D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4, D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5, D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10, D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11, D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14, D3D11_FILTER_MIN_MAG_MIP_LINEAR = 0x15, D3D11_FILTER_ANISOTROPIC = 0x55, D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80, D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81, D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84, D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85, D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90, D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91, D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94, D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95, D3D11_FILTER_COMPARISON_ANISOTROPIC = 0xd5, D3D11_FILTER_MINIMUM_MIN_MAG_MIP_POINT = 0x100, D3D11_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101, D3D11_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104, D3D11_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105, D3D11_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110, D3D11_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111, D3D11_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114, D3D11_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR = 0x115, D3D11_FILTER_MINIMUM_ANISOTROPIC = 0x155, D3D11_FILTER_MAXIMUM_MIN_MAG_MIP_POINT = 0x180, D3D11_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181, D3D11_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184, D3D11_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185, D3D11_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190, D3D11_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191, D3D11_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194, D3D11_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195, D3D11_FILTER_MAXIMUM_ANISOTROPIC = 0x1d5 } D3D11_FILTER; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_TEXTURE_ADDRESS_MODE { D3D11_TEXTURE_ADDRESS_WRAP = 1, D3D11_TEXTURE_ADDRESS_MIRROR = 2, D3D11_TEXTURE_ADDRESS_CLAMP = 3, D3D11_TEXTURE_ADDRESS_BORDER = 4, D3D11_TEXTURE_ADDRESS_MIRROR_ONCE = 5 } D3D11_TEXTURE_ADDRESS_MODE; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_COMPARISON_FUNC { D3D11_COMPARISON_NEVER = 1, D3D11_COMPARISON_LESS = 2, D3D11_COMPARISON_EQUAL = 3, D3D11_COMPARISON_LESS_EQUAL = 4, D3D11_COMPARISON_GREATER = 5, D3D11_COMPARISON_NOT_EQUAL = 6, D3D11_COMPARISON_GREATER_EQUAL = 7, D3D11_COMPARISON_ALWAYS = 8 } D3D11_COMPARISON_FUNC; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_SAMPLER_DESC { D3D11_FILTER Filter; D3D11_TEXTURE_ADDRESS_MODE AddressU; D3D11_TEXTURE_ADDRESS_MODE AddressV; D3D11_TEXTURE_ADDRESS_MODE AddressW; FLOAT MipLODBias; UINT MaxAnisotropy; D3D11_COMPARISON_FUNC ComparisonFunc; FLOAT BorderColor[4]; FLOAT MinLOD; FLOAT MaxLOD; } D3D11_SAMPLER_DESC; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_BLEND { D3D11_BLEND_ZERO = 1, D3D11_BLEND_ONE = 2, D3D11_BLEND_SRC_COLOR = 3, D3D11_BLEND_INV_SRC_COLOR = 4, D3D11_BLEND_SRC_ALPHA = 5, D3D11_BLEND_INV_SRC_ALPHA = 6, D3D11_BLEND_DEST_ALPHA = 7, D3D11_BLEND_INV_DEST_ALPHA = 8, D3D11_BLEND_DEST_COLOR = 9, D3D11_BLEND_INV_DEST_COLOR = 10, D3D11_BLEND_SRC_ALPHA_SAT = 11, D3D11_BLEND_BLEND_FACTOR = 14, D3D11_BLEND_INV_BLEND_FACTOR = 15, D3D11_BLEND_SRC1_COLOR = 16, D3D11_BLEND_INV_SRC1_COLOR = 17, D3D11_BLEND_SRC1_ALPHA = 18, D3D11_BLEND_INV_SRC1_ALPHA = 19 } D3D11_BLEND; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef enum D3D11_BLEND_OP { D3D11_BLEND_OP_ADD = 1, D3D11_BLEND_OP_SUBTRACT = 2, D3D11_BLEND_OP_REV_SUBTRACT = 3, D3D11_BLEND_OP_MIN = 4, D3D11_BLEND_OP_MAX = 5 } D3D11_BLEND_OP; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_RENDER_TARGET_BLEND_DESC { BOOL BlendEnable; D3D11_BLEND SrcBlend; D3D11_BLEND DestBlend; D3D11_BLEND_OP BlendOp; D3D11_BLEND SrcBlendAlpha; D3D11_BLEND DestBlendAlpha; D3D11_BLEND_OP BlendOpAlpha; UINT8 RenderTargetWriteMask; } D3D11_RENDER_TARGET_BLEND_DESC; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_BLEND_DESC { BOOL AlphaToCoverageEnable; BOOL IndependentBlendEnable; D3D11_RENDER_TARGET_BLEND_DESC RenderTarget[8]; } D3D11_BLEND_DESC; //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11Device : public IUnknown { virtual HRESULT STDMETHODCALLTYPE CreateBuffer(__in const D3D11_BUFFER_DESC *pDesc, __in_opt const D3D11_SUBRESOURCE_DATA *pInitialData, __out_opt ID3D11Buffer* *ppBuffer) = 0; virtual HRESULT STDMETHODCALLTYPE CreateTexture1D(__in const D3D11_TEXTURE1D_DESC *pDesc, __in_xcount_opt(pDesc->MipLevels * pDesc->ArraySize) const D3D11_SUBRESOURCE_DATA *pInitialData, __out_opt ID3D11Texture1D **ppTexture1D) = 0; virtual HRESULT STDMETHODCALLTYPE CreateTexture2D(__in const D3D11_TEXTURE2D_DESC *pDesc, __in_xcount_opt(pDesc->MipLevels * pDesc->ArraySize) const D3D11_SUBRESOURCE_DATA *pInitialData, __out_opt ID3D11Texture2D **ppTexture2D) = 0; virtual HRESULT STDMETHODCALLTYPE CreateTexture3D(__in const D3D11_TEXTURE3D_DESC *pDesc, __in_xcount_opt(pDesc->MipLevels) const D3D11_SUBRESOURCE_DATA *pInitialData, __out_opt ID3D11Texture3D **ppTexture3D) = 0; virtual HRESULT STDMETHODCALLTYPE CreateShaderResourceView(__in ID3D11Resource *pResource, __in_opt const D3D11_SHADER_RESOURCE_VIEW_DESC *pDesc, __out_opt ID3D11ShaderResourceView* *ppSRView) = 0; virtual HRESULT STDMETHODCALLTYPE CreateUnorderedAccessView(__in ID3D11Resource *pResource, __in_opt const D3D11_UNORDERED_ACCESS_VIEW_DESC *pDesc, __out_opt ID3D11UnorderedAccessView **ppUAView) = 0; virtual HRESULT STDMETHODCALLTYPE CreateRenderTargetView(__in ID3D11Resource *pResource, __in_opt const D3D11_RENDER_TARGET_VIEW_DESC *pDesc, __out_opt ID3D11RenderTargetView **ppRTView) = 0; virtual HRESULT STDMETHODCALLTYPE CreateDepthStencilView(__in ID3D11Resource *pResource, __in_opt const D3D11_DEPTH_STENCIL_VIEW_DESC *pDesc, __out_opt ID3D11DepthStencilView **ppDepthStencilView) = 0; virtual HRESULT STDMETHODCALLTYPE CreateInputLayout(__in_ecount(NumElements) const D3D11_INPUT_ELEMENT_DESC *pInputElementDescs, __in_range(0, D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) UINT NumElements, __in const void *pShaderBytecodeWithInputSignature, __in SIZE_T BytecodeLength, __out_opt ID3D11InputLayout **ppInputLayout) = 0; virtual HRESULT STDMETHODCALLTYPE CreateVertexShader(__in const void *pShaderBytecode, __in SIZE_T BytecodeLength, __in_opt ID3D11ClassLinkage *pClassLinkage, __out_opt ID3D11VertexShader **ppVertexShader) = 0; virtual HRESULT STDMETHODCALLTYPE CreateGeometryShader(__in const void *pShaderBytecode, __in SIZE_T BytecodeLength, __in_opt ID3D11ClassLinkage *pClassLinkage, __out_opt ID3D11GeometryShader **ppGeometryShader) = 0; virtual HRESULT STDMETHODCALLTYPE CreateGeometryShaderWithStreamOutput(__in const void *pShaderBytecode, __in SIZE_T BytecodeLength, __in_ecount_opt(NumEntries) const D3D11_SO_DECLARATION_ENTRY *pSODeclaration, __in_range(0, D3D11_SO_STREAM_COUNT * D3D11_SO_OUTPUT_COMPONENT_COUNT) UINT NumEntries, __in_ecount_opt(NumStrides) const UINT *pBufferStrides, __in_range(0, D3D11_SO_BUFFER_SLOT_COUNT) UINT NumStrides, __in UINT RasterizedStream, __in_opt ID3D11ClassLinkage *pClassLinkage, __out_opt ID3D11GeometryShader **ppGeometryShader) = 0; virtual HRESULT STDMETHODCALLTYPE CreatePixelShader(__in const void *pShaderBytecode, __in SIZE_T BytecodeLength, __in_opt ID3D11ClassLinkage *pClassLinkage, __out_opt ID3D11PixelShader **ppPixelShader) = 0; virtual HRESULT STDMETHODCALLTYPE CreateHullShader(__in const void *pShaderBytecode, __in SIZE_T BytecodeLength, __in_opt ID3D11ClassLinkage *pClassLinkage, __out_opt ID3D11HullShader **ppHullShader) = 0; virtual HRESULT STDMETHODCALLTYPE CreateDomainShader(__in const void *pShaderBytecode, __in SIZE_T BytecodeLength, __in_opt ID3D11ClassLinkage *pClassLinkage, __out_opt ID3D11DomainShader **ppDomainShader) = 0; virtual HRESULT STDMETHODCALLTYPE CreateComputeShader(__in const void *pShaderBytecode, __in SIZE_T BytecodeLength, __in_opt ID3D11ClassLinkage *pClassLinkage, __out_opt ID3D11ComputeShader **ppComputeShader) = 0; virtual HRESULT STDMETHODCALLTYPE CreateClassLinkage(__out ID3D11ClassLinkage **ppLinkage) = 0; virtual HRESULT STDMETHODCALLTYPE CreateBlendState(__in const D3D11_BLEND_DESC *pBlendStateDesc, __out_opt ID3D11BlendState **ppBlendState) = 0; virtual HRESULT STDMETHODCALLTYPE CreateDepthStencilState(__in const D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc, __out_opt ID3D11DepthStencilState **ppDepthStencilState) = 0; virtual HRESULT STDMETHODCALLTYPE CreateRasterizerState(__in const D3D11_RASTERIZER_DESC *pRasterizerDesc, __out_opt ID3D11RasterizerState **ppRasterizerState) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSamplerState(__in const D3D11_SAMPLER_DESC *pSamplerDesc, __out_opt ID3D11SamplerState **ppSamplerState) = 0; virtual HRESULT STDMETHODCALLTYPE CreateQuery(__in const D3D11_QUERY_DESC *pQueryDesc, __out_opt ID3D11Query **ppQuery) = 0; virtual HRESULT STDMETHODCALLTYPE CreatePredicate(__in const D3D11_QUERY_DESC *pPredicateDesc, __out_opt ID3D11Predicate **ppPredicate) = 0; virtual HRESULT STDMETHODCALLTYPE CreateCounter(__in const D3D11_COUNTER_DESC *pCounterDesc, __out_opt ID3D11Counter **ppCounter) = 0; virtual HRESULT STDMETHODCALLTYPE CreateDeferredContext(UINT ContextFlags, __out_opt ID3D11DeviceContext **ppDeferredContext) = 0; virtual HRESULT STDMETHODCALLTYPE OpenSharedResource(__in HANDLE hResource, __in REFIID ReturnedInterface, __out_opt void **ppResource) = 0; virtual HRESULT STDMETHODCALLTYPE CheckFormatSupport(__in DXGI_FORMAT Format, __out UINT *pFormatSupport) = 0; virtual HRESULT STDMETHODCALLTYPE CheckMultisampleQualityLevels(__in DXGI_FORMAT Format, __in UINT SampleCount, __out UINT *pNumQualityLevels) = 0; virtual void STDMETHODCALLTYPE CheckCounterInfo(__out D3D11_COUNTER_INFO *pCounterInfo) = 0; virtual HRESULT STDMETHODCALLTYPE CheckCounter(__in const D3D11_COUNTER_DESC *pDesc, __out D3D11_COUNTER_TYPE *pType, __out UINT *pActiveCounters, __out_ecount_opt(*pNameLength) LPSTR szName, __inout_opt UINT *pNameLength, __out_ecount_opt(*pUnitsLength) LPSTR szUnits, __inout_opt UINT *pUnitsLength, __out_ecount_opt(*pDescriptionLength) LPSTR szDescription, __inout_opt UINT *pDescriptionLength) = 0; virtual HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D11_FEATURE Feature, __out_bcount(FeatureSupportDataSize) void *pFeatureSupportData, UINT FeatureSupportDataSize) = 0; virtual HRESULT STDMETHODCALLTYPE GetPrivateData(__in REFGUID guid, __inout UINT *pDataSize, __out_bcount_opt(*pDataSize) void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE SetPrivateData(__in REFGUID guid, __in UINT DataSize, __in_bcount_opt(DataSize) const void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(__in REFGUID guid, __in_opt const IUnknown *pData) = 0; virtual D3D_FEATURE_LEVEL STDMETHODCALLTYPE GetFeatureLevel(void) = 0; virtual UINT STDMETHODCALLTYPE GetCreationFlags(void) = 0; virtual HRESULT STDMETHODCALLTYPE GetDeviceRemovedReason(void) = 0; virtual void STDMETHODCALLTYPE GetImmediateContext(__out ID3D11DeviceContext **ppImmediateContext) = 0; virtual HRESULT STDMETHODCALLTYPE SetExceptionMode(UINT RaiseFlags) = 0; virtual UINT STDMETHODCALLTYPE GetExceptionMode(void) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11DeviceChild : public IUnknown { virtual void STDMETHODCALLTYPE GetDevice(__out ID3D11Device **ppDevice) = 0; virtual HRESULT STDMETHODCALLTYPE GetPrivateData(__in REFGUID guid, __inout UINT *pDataSize, __out_bcount_opt(*pDataSize) void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE SetPrivateData(__in REFGUID guid, __in UINT DataSize, __in_bcount_opt(DataSize) const void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(__in REFGUID guid, __in_opt const IUnknown *pData) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11DeviceContext : public ID3D11DeviceChild { virtual void STDMETHODCALLTYPE VSSetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __in_ecount(NumBuffers) ID3D11Buffer* const *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE PSSetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __in_ecount(NumViews) ID3D11ShaderResourceView* const *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE PSSetShader(__in_opt ID3D11PixelShader *pPixelShader, __in_ecount_opt(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) = 0; virtual void STDMETHODCALLTYPE PSSetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __in_ecount(NumSamplers) ID3D11SamplerState *const *ppSamplers) = 0; virtual void STDMETHODCALLTYPE VSSetShader(__in_opt ID3D11VertexShader *pVertexShader, __in_ecount_opt(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) = 0; virtual void STDMETHODCALLTYPE DrawIndexed(__in UINT IndexCount, __in UINT StartIndexLocation, __in INT BaseVertexLocation) = 0; virtual void STDMETHODCALLTYPE Draw(__in UINT VertexCount, __in UINT StartVertexLocation) = 0; virtual HRESULT STDMETHODCALLTYPE Map(__in ID3D11Resource *pResource, __in UINT Subresource, __in D3D11_MAP MapType, __in UINT MapFlags, __out D3D11_MAPPED_SUBRESOURCE *pMappedResource) = 0; virtual void STDMETHODCALLTYPE Unmap(__in ID3D11Resource *pResource, __in UINT Subresource) = 0; virtual void STDMETHODCALLTYPE PSSetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __in_ecount(NumBuffers) ID3D11Buffer* const *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE IASetInputLayout(__in_opt ID3D11InputLayout *pInputLayout) = 0; virtual void STDMETHODCALLTYPE IASetVertexBuffers(__in_range(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumBuffers, __in_ecount(NumBuffers) ID3D11Buffer* const *ppVertexBuffers, __in_ecount(NumBuffers) const UINT *pStrides, __in_ecount(NumBuffers) const UINT *pOffsets) = 0; virtual void STDMETHODCALLTYPE IASetIndexBuffer(__in_opt ID3D11Buffer* pIndexBuffer, __in DXGI_FORMAT Format, __in UINT Offset) = 0; virtual void STDMETHODCALLTYPE DrawIndexedInstanced(__in UINT IndexCountPerInstance, __in UINT InstanceCount, __in UINT StartIndexLocation, __in INT BaseVertexLocation, __in UINT StartInstanceLocation) = 0; virtual void STDMETHODCALLTYPE DrawInstanced(__in UINT VertexCountPerInstance, __in UINT InstanceCount, __in UINT StartVertexLocation, __in UINT StartInstanceLocation) = 0; virtual void STDMETHODCALLTYPE GSSetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __in_ecount(NumBuffers) ID3D11Buffer* const *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE GSSetShader(__in_opt ID3D11GeometryShader *pShader, __in_ecount_opt(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) = 0; virtual void STDMETHODCALLTYPE IASetPrimitiveTopology(__in D3D11_PRIMITIVE_TOPOLOGY Topology) = 0; virtual void STDMETHODCALLTYPE VSSetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __in_ecount(NumViews) ID3D11ShaderResourceView* const *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE VSSetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __in_ecount(NumSamplers) ID3D11SamplerState *const *ppSamplers) = 0; virtual void STDMETHODCALLTYPE Begin(__in ID3D11Asynchronous *pAsync) = 0; virtual void STDMETHODCALLTYPE End(__in ID3D11Asynchronous *pAsync) = 0; virtual HRESULT STDMETHODCALLTYPE GetData(__in ID3D11Asynchronous *pAsync, __out_bcount_opt(DataSize) void *pData, __in UINT DataSize, __in UINT GetDataFlags) = 0; virtual void STDMETHODCALLTYPE SetPredication(__in_opt ID3D11Predicate *pPredicate, __in BOOL PredicateValue) = 0; virtual void STDMETHODCALLTYPE GSSetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __in_ecount(NumViews) ID3D11ShaderResourceView* const *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE GSSetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __in_ecount(NumSamplers) ID3D11SamplerState *const *ppSamplers) = 0; virtual void STDMETHODCALLTYPE OMSetRenderTargets(__in_range(0, D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT) UINT NumViews, __in_ecount_opt(NumViews) ID3D11RenderTargetView *const *ppRenderTargetViews, __in_opt ID3D11DepthStencilView *pDepthStencilView) = 0; virtual void STDMETHODCALLTYPE OMSetRenderTargetsAndUnorderedAccessViews(__in UINT NumRTVs, __in_ecount_opt(NumRTVs) ID3D11RenderTargetView *const *ppRenderTargetViews, __in_opt ID3D11DepthStencilView *pDepthStencilView, __in_range(0, D3D11_PS_CS_UAV_REGISTER_COUNT - 1) UINT UAVStartSlot, __in UINT NumUAVs, __in_ecount_opt(NumUAVs) ID3D11UnorderedAccessView *const *ppUnorderedAccessViews, __in_ecount_opt(NumUAVs) const UINT *pUAVInitialCounts) = 0; virtual void STDMETHODCALLTYPE OMSetBlendState(__in_opt ID3D11BlendState *pBlendState, __in_opt const FLOAT BlendFactor[4], __in UINT SampleMask) = 0; virtual void STDMETHODCALLTYPE OMSetDepthStencilState(__in_opt ID3D11DepthStencilState *pDepthStencilState, __in UINT StencilRef) = 0; virtual void STDMETHODCALLTYPE SOSetTargets(__in_range(0, D3D11_SO_BUFFER_SLOT_COUNT) UINT NumBuffers, __in_ecount_opt(NumBuffers) ID3D11Buffer* const *ppSOTargets, __in_ecount_opt(NumBuffers) const UINT *pOffsets) = 0; virtual void STDMETHODCALLTYPE DrawAuto(void) = 0; virtual void STDMETHODCALLTYPE DrawIndexedInstancedIndirect(__in ID3D11Buffer* pBufferForArgs, __in UINT AlignedByteOffsetForArgs) = 0; virtual void STDMETHODCALLTYPE DrawInstancedIndirect(__in ID3D11Buffer* pBufferForArgs, __in UINT AlignedByteOffsetForArgs) = 0; virtual void STDMETHODCALLTYPE Dispatch(__in UINT ThreadGroupCountX, __in UINT ThreadGroupCountY, __in UINT ThreadGroupCountZ) = 0; virtual void STDMETHODCALLTYPE DispatchIndirect(__in ID3D11Buffer* pBufferForArgs, __in UINT AlignedByteOffsetForArgs) = 0; virtual void STDMETHODCALLTYPE RSSetState(__in_opt ID3D11RasterizerState *pRasterizerState) = 0; virtual void STDMETHODCALLTYPE RSSetViewports(__in_range(0, D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumViewports, __in_ecount_opt(NumViewports) const D3D11_VIEWPORT *pViewports) = 0; virtual void STDMETHODCALLTYPE RSSetScissorRects(__in_range(0, D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumRects, __in_ecount_opt(NumRects) const D3D11_RECT *pRects) = 0; virtual void STDMETHODCALLTYPE CopySubresourceRegion(__in ID3D11Resource *pDstResource, __in UINT DstSubresource, __in UINT DstX, __in UINT DstY, __in UINT DstZ, __in ID3D11Resource *pSrcResource, __in UINT SrcSubresource, __in_opt const D3D11_BOX *pSrcBox) = 0; virtual void STDMETHODCALLTYPE CopyResource(__in ID3D11Resource *pDstResource, __in ID3D11Resource *pSrcResource) = 0; virtual void STDMETHODCALLTYPE UpdateSubresource(__in ID3D11Resource *pDstResource, __in UINT DstSubresource, __in_opt const D3D11_BOX *pDstBox, __in const void *pSrcData, __in UINT SrcRowPitch, __in UINT SrcDepthPitch) = 0; virtual void STDMETHODCALLTYPE CopyStructureCount(__in ID3D11Buffer* pDstBuffer, __in UINT DstAlignedByteOffset, __in ID3D11UnorderedAccessView *pSrcView) = 0; virtual void STDMETHODCALLTYPE ClearRenderTargetView(__in ID3D11RenderTargetView *pRenderTargetView, __in const FLOAT ColorRGBA[4]) = 0; virtual void STDMETHODCALLTYPE ClearUnorderedAccessViewUint(__in ID3D11UnorderedAccessView *pUnorderedAccessView, __in const UINT Values[4]) = 0; virtual void STDMETHODCALLTYPE ClearUnorderedAccessViewFloat(__in ID3D11UnorderedAccessView *pUnorderedAccessView, __in const FLOAT Values[4]) = 0; virtual void STDMETHODCALLTYPE ClearDepthStencilView(__in ID3D11DepthStencilView *pDepthStencilView, __in UINT ClearFlags, __in FLOAT Depth, __in UINT8 Stencil) = 0; virtual void STDMETHODCALLTYPE GenerateMips(__in ID3D11ShaderResourceView* pShaderResourceView) = 0; virtual void STDMETHODCALLTYPE SetResourceMinLOD(__in ID3D11Resource *pResource, FLOAT MinLOD) = 0; virtual FLOAT STDMETHODCALLTYPE GetResourceMinLOD(__in ID3D11Resource *pResource) = 0; virtual void STDMETHODCALLTYPE ResolveSubresource(__in ID3D11Resource *pDstResource, __in UINT DstSubresource, __in ID3D11Resource *pSrcResource, __in UINT SrcSubresource, __in DXGI_FORMAT Format) = 0; virtual void STDMETHODCALLTYPE ExecuteCommandList(__in ID3D11CommandList *pCommandList, BOOL RestoreContextState) = 0; virtual void STDMETHODCALLTYPE HSSetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __in_ecount(NumViews) ID3D11ShaderResourceView* const *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE HSSetShader(__in_opt ID3D11HullShader *pHullShader, __in_ecount_opt(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) = 0; virtual void STDMETHODCALLTYPE HSSetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __in_ecount(NumSamplers) ID3D11SamplerState *const *ppSamplers) = 0; virtual void STDMETHODCALLTYPE HSSetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __in_ecount(NumBuffers) ID3D11Buffer* const *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE DSSetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __in_ecount(NumViews) ID3D11ShaderResourceView* const *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE DSSetShader(__in_opt ID3D11DomainShader *pDomainShader, __in_ecount_opt(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) = 0; virtual void STDMETHODCALLTYPE DSSetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __in_ecount(NumSamplers) ID3D11SamplerState *const *ppSamplers) = 0; virtual void STDMETHODCALLTYPE DSSetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __in_ecount(NumBuffers) ID3D11Buffer* const *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE CSSetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __in_ecount(NumViews) ID3D11ShaderResourceView* const *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE CSSetUnorderedAccessViews(__in_range(0, D3D11_PS_CS_UAV_REGISTER_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_PS_CS_UAV_REGISTER_COUNT - StartSlot) UINT NumUAVs, __in_ecount(NumUAVs) ID3D11UnorderedAccessView *const *ppUnorderedAccessViews, __in_ecount(NumUAVs) const UINT *pUAVInitialCounts) = 0; virtual void STDMETHODCALLTYPE CSSetShader(__in_opt ID3D11ComputeShader *pComputeShader, __in_ecount_opt(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances, UINT NumClassInstances) = 0; virtual void STDMETHODCALLTYPE CSSetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __in_ecount(NumSamplers) ID3D11SamplerState *const *ppSamplers) = 0; virtual void STDMETHODCALLTYPE CSSetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __in_ecount(NumBuffers) ID3D11Buffer* const *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE VSGetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __out_ecount(NumBuffers) ID3D11Buffer* *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE PSGetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __out_ecount(NumViews) ID3D11ShaderResourceView* *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE PSGetShader(__out ID3D11PixelShader **ppPixelShader, __out_ecount_opt(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances, __inout_opt UINT *pNumClassInstances) = 0; virtual void STDMETHODCALLTYPE PSGetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __out_ecount(NumSamplers) ID3D11SamplerState **ppSamplers) = 0; virtual void STDMETHODCALLTYPE VSGetShader(__out ID3D11VertexShader **ppVertexShader, __out_ecount_opt(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances, __inout_opt UINT *pNumClassInstances) = 0; virtual void STDMETHODCALLTYPE PSGetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __out_ecount(NumBuffers) ID3D11Buffer* *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE IAGetInputLayout(__out ID3D11InputLayout **ppInputLayout) = 0; virtual void STDMETHODCALLTYPE IAGetVertexBuffers(__in_range(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumBuffers, __out_ecount_opt(NumBuffers) ID3D11Buffer* *ppVertexBuffers, __out_ecount_opt(NumBuffers) UINT *pStrides, __out_ecount_opt(NumBuffers) UINT *pOffsets) = 0; virtual void STDMETHODCALLTYPE IAGetIndexBuffer(__out_opt ID3D11Buffer* *pIndexBuffer, __out_opt DXGI_FORMAT *Format, __out_opt UINT *Offset) = 0; virtual void STDMETHODCALLTYPE GSGetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __out_ecount(NumBuffers) ID3D11Buffer* *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE GSGetShader(__out ID3D11GeometryShader **ppGeometryShader, __out_ecount_opt(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances, __inout_opt UINT *pNumClassInstances) = 0; virtual void STDMETHODCALLTYPE IAGetPrimitiveTopology(__out D3D11_PRIMITIVE_TOPOLOGY *pTopology) = 0; virtual void STDMETHODCALLTYPE VSGetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __out_ecount(NumViews) ID3D11ShaderResourceView* *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE VSGetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __out_ecount(NumSamplers) ID3D11SamplerState **ppSamplers) = 0; virtual void STDMETHODCALLTYPE GetPredication(__out_opt ID3D11Predicate **ppPredicate, __out_opt BOOL *pPredicateValue) = 0; virtual void STDMETHODCALLTYPE GSGetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __out_ecount(NumViews) ID3D11ShaderResourceView* *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE GSGetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __out_ecount(NumSamplers) ID3D11SamplerState **ppSamplers) = 0; virtual void STDMETHODCALLTYPE OMGetRenderTargets(__in_range(0, D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT) UINT NumViews, __out_ecount_opt(NumViews) ID3D11RenderTargetView **ppRenderTargetViews, __out_opt ID3D11DepthStencilView **ppDepthStencilView) = 0; virtual void STDMETHODCALLTYPE OMGetRenderTargetsAndUnorderedAccessViews(__in_range(0, D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT) UINT NumRTVs, __out_ecount_opt(NumRTVs) ID3D11RenderTargetView **ppRenderTargetViews, __out_opt ID3D11DepthStencilView **ppDepthStencilView, __in_range(0, D3D11_PS_CS_UAV_REGISTER_COUNT - 1) UINT UAVStartSlot, __in_range(0, D3D11_PS_CS_UAV_REGISTER_COUNT - UAVStartSlot) UINT NumUAVs, __out_ecount_opt(NumUAVs) ID3D11UnorderedAccessView **ppUnorderedAccessViews) = 0; virtual void STDMETHODCALLTYPE OMGetBlendState(__out_opt ID3D11BlendState **ppBlendState, __out_opt FLOAT BlendFactor[4], __out_opt UINT *pSampleMask) = 0; virtual void STDMETHODCALLTYPE OMGetDepthStencilState(__out_opt ID3D11DepthStencilState **ppDepthStencilState, __out_opt UINT *pStencilRef) = 0; virtual void STDMETHODCALLTYPE SOGetTargets(__in_range(0, D3D11_SO_BUFFER_SLOT_COUNT) UINT NumBuffers, __out_ecount(NumBuffers) ID3D11Buffer* *ppSOTargets) = 0; virtual void STDMETHODCALLTYPE RSGetState(__out ID3D11RasterizerState **ppRasterizerState) = 0; virtual void STDMETHODCALLTYPE RSGetViewports(__inout UINT *pNumViewports, __out_ecount_opt(*pNumViewports) D3D11_VIEWPORT *pViewports) = 0; virtual void STDMETHODCALLTYPE RSGetScissorRects(__inout UINT *pNumRects, __out_ecount_opt(*pNumRects) D3D11_RECT *pRects) = 0; virtual void STDMETHODCALLTYPE HSGetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __out_ecount(NumViews) ID3D11ShaderResourceView* *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE HSGetShader(__out ID3D11HullShader **ppHullShader, __out_ecount_opt(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances, __inout_opt UINT *pNumClassInstances) = 0; virtual void STDMETHODCALLTYPE HSGetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __out_ecount(NumSamplers) ID3D11SamplerState **ppSamplers) = 0; virtual void STDMETHODCALLTYPE HSGetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __out_ecount(NumBuffers) ID3D11Buffer* *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE DSGetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __out_ecount(NumViews) ID3D11ShaderResourceView* *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE DSGetShader(__out ID3D11DomainShader **ppDomainShader, __out_ecount_opt(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances, __inout_opt UINT *pNumClassInstances) = 0; virtual void STDMETHODCALLTYPE DSGetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __out_ecount(NumSamplers) ID3D11SamplerState **ppSamplers) = 0; virtual void STDMETHODCALLTYPE DSGetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __out_ecount(NumBuffers) ID3D11Buffer* *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE CSGetShaderResources(__in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews, __out_ecount(NumViews) ID3D11ShaderResourceView* *ppShaderResourceViews) = 0; virtual void STDMETHODCALLTYPE CSGetUnorderedAccessViews(__in_range(0, D3D11_PS_CS_UAV_REGISTER_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_PS_CS_UAV_REGISTER_COUNT - StartSlot) UINT NumUAVs, __out_ecount(NumUAVs) ID3D11UnorderedAccessView **ppUnorderedAccessViews) = 0; virtual void STDMETHODCALLTYPE CSGetShader(__out ID3D11ComputeShader **ppComputeShader, __out_ecount_opt(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances, __inout_opt UINT *pNumClassInstances) = 0; virtual void STDMETHODCALLTYPE CSGetSamplers(__in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers, __out_ecount(NumSamplers) ID3D11SamplerState **ppSamplers) = 0; virtual void STDMETHODCALLTYPE CSGetConstantBuffers(__in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot, __in_range(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers, __out_ecount(NumBuffers) ID3D11Buffer* *ppConstantBuffers) = 0; virtual void STDMETHODCALLTYPE ClearState(void) = 0; virtual void STDMETHODCALLTYPE Flush(void) = 0; virtual D3D11_DEVICE_CONTEXT_TYPE STDMETHODCALLTYPE GetType(void) = 0; virtual UINT STDMETHODCALLTYPE GetContextFlags(void) = 0; virtual HRESULT STDMETHODCALLTYPE FinishCommandList(BOOL RestoreDeferredContextState, __out_opt ID3D11CommandList **ppCommandList) = 0; }; PRAGMA_WARNING_POP // "Windows 10 SDK" -> "d3d11_1.h" MIDL_INTERFACE("bb2c6faa-b5fb-4082-8e6b-388b8cfa90e1") ID3D11DeviceContext1 : public ID3D11DeviceContext { virtual void STDMETHODCALLTYPE CopySubresourceRegion1(_In_ ID3D11Resource *pDstResource, _In_ UINT DstSubresource, _In_ UINT DstX, _In_ UINT DstY, _In_ UINT DstZ, _In_ ID3D11Resource *pSrcResource, _In_ UINT SrcSubresource, _In_opt_ const D3D11_BOX *pSrcBox, _In_ UINT CopyFlags) = 0; virtual void STDMETHODCALLTYPE UpdateSubresource1(_In_ ID3D11Resource *pDstResource, _In_ UINT DstSubresource, _In_opt_ const D3D11_BOX *pDstBox, _In_ const void *pSrcData, _In_ UINT SrcRowPitch, _In_ UINT SrcDepthPitch, _In_ UINT CopyFlags) = 0; virtual void STDMETHODCALLTYPE DiscardResource(_In_ ID3D11Resource *pResource) = 0; virtual void STDMETHODCALLTYPE DiscardView(_In_ ID3D11View *pResourceView) = 0; virtual void STDMETHODCALLTYPE VSSetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers, _In_reads_opt_(NumBuffers) const UINT *pFirstConstant, _In_reads_opt_(NumBuffers) const UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE HSSetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers, _In_reads_opt_(NumBuffers) const UINT *pFirstConstant, _In_reads_opt_(NumBuffers) const UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE DSSetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers, _In_reads_opt_(NumBuffers) const UINT *pFirstConstant, _In_reads_opt_(NumBuffers) const UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE GSSetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers, _In_reads_opt_(NumBuffers) const UINT *pFirstConstant, _In_reads_opt_(NumBuffers) const UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE PSSetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers, _In_reads_opt_(NumBuffers) const UINT *pFirstConstant, _In_reads_opt_(NumBuffers) const UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE CSSetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers, _In_reads_opt_(NumBuffers) const UINT *pFirstConstant, _In_reads_opt_(NumBuffers) const UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE VSGetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers, _Out_writes_opt_(NumBuffers) UINT *pFirstConstant, _Out_writes_opt_(NumBuffers) UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE HSGetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers, _Out_writes_opt_(NumBuffers) UINT *pFirstConstant, _Out_writes_opt_(NumBuffers) UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE DSGetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers, _Out_writes_opt_(NumBuffers) UINT *pFirstConstant, _Out_writes_opt_(NumBuffers) UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE GSGetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers, _Out_writes_opt_(NumBuffers) UINT *pFirstConstant, _Out_writes_opt_(NumBuffers) UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE PSGetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers, _Out_writes_opt_(NumBuffers) UINT *pFirstConstant, _Out_writes_opt_(NumBuffers) UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE CSGetConstantBuffers1(_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot, _In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers, _Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers, _Out_writes_opt_(NumBuffers) UINT *pFirstConstant, _Out_writes_opt_(NumBuffers) UINT *pNumConstants) = 0; virtual void STDMETHODCALLTYPE SwapDeviceContextState(_In_ ID3DDeviceContextState *pState, _Outptr_opt_ ID3DDeviceContextState **ppPreviousState) = 0; virtual void STDMETHODCALLTYPE ClearView(_In_ ID3D11View *pView, _In_ const FLOAT Color[ 4 ], _In_reads_opt_(NumRects) const D3D11_RECT *pRect, UINT NumRects) = 0; virtual void STDMETHODCALLTYPE DiscardView1(_In_ ID3D11View *pResourceView, _In_reads_opt_(NumRects) const D3D11_RECT *pRects, UINT NumRects) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11InputLayout : public ID3D11DeviceChild { // Nothing here }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11SamplerState : public ID3D11DeviceChild { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_SAMPLER_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11RasterizerState : public ID3D11DeviceChild { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_RASTERIZER_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11BlendState : public ID3D11DeviceChild { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_BLEND_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11DepthStencilState : public ID3D11DeviceChild { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_DEPTH_STENCIL_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11VertexShader : public ID3D11DeviceChild { // Nothing here }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11HullShader : public ID3D11DeviceChild { // Nothing here }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11DomainShader : public ID3D11DeviceChild { // Nothing here }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11GeometryShader : public ID3D11DeviceChild { // Nothing here }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11PixelShader : public ID3D11DeviceChild { // Nothing here }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11ComputeShader : public ID3D11DeviceChild { // Nothing here }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11Resource : public ID3D11DeviceChild { virtual void STDMETHODCALLTYPE GetType(__out D3D11_RESOURCE_DIMENSION *pResourceDimension) = 0; virtual void STDMETHODCALLTYPE SetEvictionPriority(__in UINT EvictionPriority) = 0; virtual UINT STDMETHODCALLTYPE GetEvictionPriority(void) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11Buffer : public ID3D11Resource { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_BUFFER_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" MIDL_INTERFACE("f8fb5c27-c6b3-4f75-a4c8-439af2ef564c") ID3D11Texture1D : public ID3D11Resource { virtual void STDMETHODCALLTYPE GetDesc(_Out_ D3D11_TEXTURE1D_DESC *pDesc) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" MIDL_INTERFACE("6f15aaf2-d208-4e89-9ab4-489535d34f9c") ID3D11Texture2D : public ID3D11Resource { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_TEXTURE2D_DESC *pDesc) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" MIDL_INTERFACE("037e866e-f56d-4357-a8af-9dabbe6e250e") ID3D11Texture3D : public ID3D11Resource { virtual void STDMETHODCALLTYPE GetDesc(_Out_ D3D11_TEXTURE3D_DESC *pDesc) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11View : public ID3D11DeviceChild { virtual void STDMETHODCALLTYPE GetResource(__out ID3D11Resource **ppResource) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11ShaderResourceView : public ID3D11View { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_SHADER_RESOURCE_VIEW_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11UnorderedAccessView : public ID3D11View { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_UNORDERED_ACCESS_VIEW_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11RenderTargetView : public ID3D11View { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_RENDER_TARGET_VIEW_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11DepthStencilView : public ID3D11View { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_DEPTH_STENCIL_VIEW_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3Dcommon.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D10Blob : public IUnknown { virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) = 0; virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11Asynchronous : public ID3D11DeviceChild { virtual UINT STDMETHODCALLTYPE GetDataSize(void) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" enum D3D11_QUERY { D3D11_QUERY_EVENT = 0, D3D11_QUERY_OCCLUSION = (D3D11_QUERY_EVENT + 1), D3D11_QUERY_TIMESTAMP = (D3D11_QUERY_OCCLUSION + 1), D3D11_QUERY_TIMESTAMP_DISJOINT = (D3D11_QUERY_TIMESTAMP + 1), D3D11_QUERY_PIPELINE_STATISTICS = (D3D11_QUERY_TIMESTAMP_DISJOINT + 1), D3D11_QUERY_OCCLUSION_PREDICATE = (D3D11_QUERY_PIPELINE_STATISTICS + 1), D3D11_QUERY_SO_STATISTICS = (D3D11_QUERY_OCCLUSION_PREDICATE + 1), D3D11_QUERY_SO_OVERFLOW_PREDICATE = (D3D11_QUERY_SO_STATISTICS + 1), D3D11_QUERY_SO_STATISTICS_STREAM0 = (D3D11_QUERY_SO_OVERFLOW_PREDICATE + 1), D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM0 = (D3D11_QUERY_SO_STATISTICS_STREAM0 + 1), D3D11_QUERY_SO_STATISTICS_STREAM1 = (D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM0 + 1), D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM1 = (D3D11_QUERY_SO_STATISTICS_STREAM1 + 1), D3D11_QUERY_SO_STATISTICS_STREAM2 = (D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM1 + 1), D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM2 = (D3D11_QUERY_SO_STATISTICS_STREAM2 + 1), D3D11_QUERY_SO_STATISTICS_STREAM3 = (D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM2 + 1), D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM3 = (D3D11_QUERY_SO_STATISTICS_STREAM3 + 1) }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" struct D3D11_QUERY_DESC { D3D11_QUERY Query; UINT MiscFlags; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5204) // warning C5204: 'IDXGIObject': class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly struct ID3D11Query : public ID3D11Asynchronous { virtual void STDMETHODCALLTYPE GetDesc(__out D3D11_QUERY_DESC *pDesc) = 0; }; PRAGMA_WARNING_POP // "Microsoft DirectX SDK (June 2010)" -> "D3D11.h" typedef struct D3D11_QUERY_DATA_PIPELINE_STATISTICS { UINT64 IAVertices; UINT64 IAPrimitives; UINT64 VSInvocations; UINT64 GSInvocations; UINT64 GSPrimitives; UINT64 CInvocations; UINT64 CPrimitives; UINT64 PSInvocations; UINT64 HSInvocations; UINT64 DSInvocations; UINT64 CSInvocations; } D3D11_QUERY_DATA_PIPELINE_STATISTICS; // "Microsoft DirectX SDK (June 2010)" -> "D3D11SDKLayers.h" typedef enum D3D11_RLDO_FLAGS { D3D11_RLDO_SUMMARY = 0x1, D3D11_RLDO_DETAIL = 0x2 } D3D11_RLDO_FLAGS; // "Microsoft DirectX SDK (June 2010)" -> "D3D11SDKLayers.h" MIDL_INTERFACE("79cf2233-7536-4948-9d36-1e4692dc5760") ID3D11Debug : public IUnknown { virtual HRESULT STDMETHODCALLTYPE SetFeatureMask(UINT Mask) = 0; virtual UINT STDMETHODCALLTYPE GetFeatureMask(void) = 0; virtual HRESULT STDMETHODCALLTYPE SetPresentPerRenderOpDelay(UINT Milliseconds) = 0; virtual UINT STDMETHODCALLTYPE GetPresentPerRenderOpDelay(void) = 0; virtual HRESULT STDMETHODCALLTYPE SetSwapChain(__in_opt IDXGISwapChain *pSwapChain) = 0; virtual HRESULT STDMETHODCALLTYPE GetSwapChain(__out IDXGISwapChain **ppSwapChain) = 0; virtual HRESULT STDMETHODCALLTYPE ValidateContext(__in ID3D11DeviceContext *pContext) = 0; virtual HRESULT STDMETHODCALLTYPE ReportLiveDeviceObjects(D3D11_RLDO_FLAGS Flags) = 0; virtual HRESULT STDMETHODCALLTYPE ValidateContextForDispatch(__in ID3D11DeviceContext *pContext) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "D3D11SDKLayers.h" typedef enum D3D11_MESSAGE_CATEGORY { D3D11_MESSAGE_CATEGORY_APPLICATION_DEFINED = 0, D3D11_MESSAGE_CATEGORY_MISCELLANEOUS = D3D11_MESSAGE_CATEGORY_APPLICATION_DEFINED + 1, D3D11_MESSAGE_CATEGORY_INITIALIZATION = D3D11_MESSAGE_CATEGORY_MISCELLANEOUS + 1, D3D11_MESSAGE_CATEGORY_CLEANUP = D3D11_MESSAGE_CATEGORY_INITIALIZATION + 1, D3D11_MESSAGE_CATEGORY_COMPILATION = D3D11_MESSAGE_CATEGORY_CLEANUP + 1, D3D11_MESSAGE_CATEGORY_STATE_CREATION = D3D11_MESSAGE_CATEGORY_COMPILATION + 1, D3D11_MESSAGE_CATEGORY_STATE_SETTING = D3D11_MESSAGE_CATEGORY_STATE_CREATION + 1, D3D11_MESSAGE_CATEGORY_STATE_GETTING = D3D11_MESSAGE_CATEGORY_STATE_SETTING + 1, D3D11_MESSAGE_CATEGORY_RESOURCE_MANIPULATION = D3D11_MESSAGE_CATEGORY_STATE_GETTING + 1, D3D11_MESSAGE_CATEGORY_EXECUTION = D3D11_MESSAGE_CATEGORY_RESOURCE_MANIPULATION + 1, D3D11_MESSAGE_CATEGORY_SHADER = D3D11_MESSAGE_CATEGORY_EXECUTION + 1 } D3D11_MESSAGE_CATEGORY; // "Microsoft DirectX SDK (June 2010)" -> "D3D11SDKLayers.h" typedef enum D3D11_MESSAGE_SEVERITY { D3D11_MESSAGE_SEVERITY_CORRUPTION = 0, D3D11_MESSAGE_SEVERITY_ERROR = D3D11_MESSAGE_SEVERITY_CORRUPTION + 1, D3D11_MESSAGE_SEVERITY_WARNING = D3D11_MESSAGE_SEVERITY_ERROR + 1, D3D11_MESSAGE_SEVERITY_INFO = D3D11_MESSAGE_SEVERITY_WARNING + 1 } D3D11_MESSAGE_SEVERITY; // "Microsoft DirectX SDK (June 2010)" -> "D3D11SDKLayers.h" -> But only the few definitions we need typedef enum D3D11_MESSAGE_ID { D3D11_MESSAGE_ID_UNKNOWN = 0, D3D11_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_HAZARD = 1, D3D11_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_HAZARD = 2, D3D11_MESSAGE_ID_DEVICE_OMSETRENDERTARGETS_HAZARD = 9, D3D11_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_HAZARD = 3, D3D11_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_HAZARD = 5, D3D11_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_HAZARD = 7, D3D11_MESSAGE_ID_DEVICE_HSSETSHADERRESOURCES_HAZARD = 2097173, D3D11_MESSAGE_ID_DEVICE_DSSETSHADERRESOURCES_HAZARD = 2097189, D3D11_MESSAGE_ID_DEVICE_CSSETSHADERRESOURCES_HAZARD = 2097316, D3D11_MESSAGE_ID_DEVICE_CSSETUNORDEREDACCESSVIEWS_HAZARD = 2097354 } D3D11_MESSAGE_ID; // "Microsoft DirectX SDK (June 2010)" -> "D3D11SDKLayers.h" typedef struct D3D11_MESSAGE { D3D11_MESSAGE_CATEGORY Category; D3D11_MESSAGE_SEVERITY Severity; D3D11_MESSAGE_ID ID; const char* pDescription; SIZE_T DescriptionByteLength; } D3D11_MESSAGE; // "Microsoft DirectX SDK (June 2010)" -> "D3D11SDKLayers.h" typedef struct D3D11_INFO_QUEUE_FILTER_DESC { UINT NumCategories; D3D11_MESSAGE_CATEGORY *pCategoryList; UINT NumSeverities; D3D11_MESSAGE_SEVERITY *pSeverityList; UINT NumIDs; D3D11_MESSAGE_ID *pIDList; } D3D11_INFO_QUEUE_FILTER_DESC; // "Microsoft DirectX SDK (June 2010)" -> "D3D11SDKLayers.h" typedef struct D3D11_INFO_QUEUE_FILTER { D3D11_INFO_QUEUE_FILTER_DESC AllowList; D3D11_INFO_QUEUE_FILTER_DESC DenyList; } D3D11_INFO_QUEUE_FILTER; // "Microsoft DirectX SDK (June 2010)" -> "D3D11SDKLayers.h" MIDL_INTERFACE("6543dbb6-1b48-42f5-ab82-e97ec74326f6") ID3D11InfoQueue : public IUnknown { virtual HRESULT STDMETHODCALLTYPE SetMessageCountLimit(_In_ UINT64 MessageCountLimit) = 0; virtual void STDMETHODCALLTYPE ClearStoredMessages(void) = 0; virtual HRESULT STDMETHODCALLTYPE GetMessage(_In_ UINT64 MessageIndex, _Out_writes_bytes_opt_(*pMessageByteLength) D3D11_MESSAGE *pMessage, _Inout_ SIZE_T *pMessageByteLength) = 0; virtual UINT64 STDMETHODCALLTYPE GetNumMessagesAllowedByStorageFilter(void) = 0; virtual UINT64 STDMETHODCALLTYPE GetNumMessagesDeniedByStorageFilter(void) = 0; virtual UINT64 STDMETHODCALLTYPE GetNumStoredMessages(void) = 0; virtual UINT64 STDMETHODCALLTYPE GetNumStoredMessagesAllowedByRetrievalFilter(void) = 0; virtual UINT64 STDMETHODCALLTYPE GetNumMessagesDiscardedByMessageCountLimit(void) = 0; virtual UINT64 STDMETHODCALLTYPE GetMessageCountLimit(void) = 0; virtual HRESULT STDMETHODCALLTYPE AddStorageFilterEntries(_In_ D3D11_INFO_QUEUE_FILTER *pFilter) = 0; virtual HRESULT STDMETHODCALLTYPE GetStorageFilter(_Out_writes_bytes_opt_(*pFilterByteLength) D3D11_INFO_QUEUE_FILTER *pFilter, _Inout_ SIZE_T *pFilterByteLength) = 0; virtual void STDMETHODCALLTYPE ClearStorageFilter(void) = 0; virtual HRESULT STDMETHODCALLTYPE PushEmptyStorageFilter(void) = 0; virtual HRESULT STDMETHODCALLTYPE PushCopyOfStorageFilter(void) = 0; virtual HRESULT STDMETHODCALLTYPE PushStorageFilter(_In_ D3D11_INFO_QUEUE_FILTER *pFilter) = 0; virtual void STDMETHODCALLTYPE PopStorageFilter(void) = 0; virtual UINT STDMETHODCALLTYPE GetStorageFilterStackSize(void) = 0; virtual HRESULT STDMETHODCALLTYPE AddRetrievalFilterEntries(_In_ D3D11_INFO_QUEUE_FILTER *pFilter) = 0; virtual HRESULT STDMETHODCALLTYPE GetRetrievalFilter(_Out_writes_bytes_opt_(*pFilterByteLength) D3D11_INFO_QUEUE_FILTER *pFilter, _Inout_ SIZE_T *pFilterByteLength) = 0; virtual void STDMETHODCALLTYPE ClearRetrievalFilter(void) = 0; virtual HRESULT STDMETHODCALLTYPE PushEmptyRetrievalFilter(void) = 0; virtual HRESULT STDMETHODCALLTYPE PushCopyOfRetrievalFilter(void) = 0; virtual HRESULT STDMETHODCALLTYPE PushRetrievalFilter(_In_ D3D11_INFO_QUEUE_FILTER *pFilter) = 0; virtual void STDMETHODCALLTYPE PopRetrievalFilter(void) = 0; virtual UINT STDMETHODCALLTYPE GetRetrievalFilterStackSize(void) = 0; virtual HRESULT STDMETHODCALLTYPE AddMessage(_In_ D3D11_MESSAGE_CATEGORY Category, _In_ D3D11_MESSAGE_SEVERITY Severity, _In_ D3D11_MESSAGE_ID ID, _In_ LPCSTR pDescription) = 0; virtual HRESULT STDMETHODCALLTYPE AddApplicationMessage(_In_ D3D11_MESSAGE_SEVERITY Severity, _In_ LPCSTR pDescription) = 0; virtual HRESULT STDMETHODCALLTYPE SetBreakOnCategory(_In_ D3D11_MESSAGE_CATEGORY Category, _In_ BOOL bEnable) = 0; virtual HRESULT STDMETHODCALLTYPE SetBreakOnSeverity(_In_ D3D11_MESSAGE_SEVERITY Severity, _In_ BOOL bEnable) = 0; virtual HRESULT STDMETHODCALLTYPE SetBreakOnID(_In_ D3D11_MESSAGE_ID ID, _In_ BOOL bEnable) = 0; virtual BOOL STDMETHODCALLTYPE GetBreakOnCategory(_In_ D3D11_MESSAGE_CATEGORY Category) = 0; virtual BOOL STDMETHODCALLTYPE GetBreakOnSeverity(_In_ D3D11_MESSAGE_SEVERITY Severity) = 0; virtual BOOL STDMETHODCALLTYPE GetBreakOnID(_In_ D3D11_MESSAGE_ID ID) = 0; virtual void STDMETHODCALLTYPE SetMuteDebugOutput(_In_ BOOL bMute) = 0; virtual BOOL STDMETHODCALLTYPE GetMuteDebugOutput(void) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "d3d11_1.h" MIDL_INTERFACE("b2daad8b-03d4-4dbf-95eb-32ab4b63d0ab") ID3DUserDefinedAnnotation : public IUnknown { virtual INT STDMETHODCALLTYPE BeginEvent(_In_ LPCWSTR Name) = 0; virtual INT STDMETHODCALLTYPE EndEvent(void) = 0; virtual void STDMETHODCALLTYPE SetMarker(_In_ LPCWSTR Name) = 0; virtual BOOL STDMETHODCALLTYPE GetStatus(void) = 0; }; //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] struct AGSContext; // AMD AGS namespace Direct3D11Rhi { class RootSignature; class Direct3D11RuntimeLinking; } //[-------------------------------------------------------] //[ Macros & definitions ] //[-------------------------------------------------------] #ifdef RHI_DEBUG /* * @brief * Check whether or not the given resource is owned by the given RHI */ #define RHI_MATCH_CHECK(rhiReference, resourceReference) \ RHI_ASSERT(mContext, &rhiReference == &(resourceReference).getRhi(), "Direct3D 11 error: The given resource is owned by another RHI instance") /** * @brief * Resource name for debugging purposes, ignored when not using "RHI_DEBUG" * * @param[in] debugName * ASCII name for debugging purposes, must be valid (there's no internal null pointer test) */ #define RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER , [[maybe_unused]] const char debugName[] = "" /* * @brief * Debug break on execution failure, replacement for "ID3D11InfoQueue::SetBreakOnSeverity()" which is creating a confusing callstack */ #define FAILED_DEBUG_BREAK(toExecute) if (FAILED(toExecute)) { DEBUG_BREAK; } #else /* * @brief * Check whether or not the given resource is owned by the given RHI */ #define RHI_MATCH_CHECK(rhiReference, resourceReference) /** * @brief * Resource name for debugging purposes, ignored when not using "RHI_DEBUG" * * @param[in] debugName * ASCII name for debugging purposes, must be valid (there's no internal null pointer test) */ #define RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER /* * @brief * Debug break on execution failure, replacement for "ID3D11InfoQueue::SetBreakOnSeverity()" which is creating a confusing callstack */ #define FAILED_DEBUG_BREAK(toExecute) toExecute; #endif //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] namespace { namespace detail { //[-------------------------------------------------------] //[ Global definitions ] //[-------------------------------------------------------] typedef LONG NTSTATUS, *PNTSTATUS; typedef NTSTATUS (WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); static constexpr const char* HLSL_NAME = "HLSL"; ///< ASCII name of this shader language, always valid (do not free the memory the returned pointer is pointing to) //[-------------------------------------------------------] //[ Global functions ] //[-------------------------------------------------------] void updateWidthHeight(uint32_t mipmapIndex, uint32_t textureWidth, uint32_t textureHeight, uint32_t& width, uint32_t& height) { Rhi::ITexture::getMipmapSize(mipmapIndex, textureWidth, textureHeight); if (width > textureWidth) { width = textureWidth; } if (height > textureHeight) { height = textureHeight; } } // From https://stackoverflow.com/a/36545162 [[nodiscard]] RTL_OSVERSIONINFOW getRealOSVersion() { const HMODULE hModule = ::GetModuleHandleW(L"ntdll.dll"); if (hModule) { PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4191) // warning C4191: 'reinterpret_cast': unsafe conversion from 'FARPROC' to '`anonymous-namespace'::detail::RtlGetVersionPtr' const RtlGetVersionPtr functionPointer = reinterpret_cast<RtlGetVersionPtr>(::GetProcAddress(hModule, "RtlGetVersion")); PRAGMA_WARNING_POP if (nullptr != functionPointer) { RTL_OSVERSIONINFOW rovi = { }; rovi.dwOSVersionInfoSize = sizeof(rovi); if (0x00000000 == functionPointer(&rovi)) { return rovi; } } } RTL_OSVERSIONINFOW rovi = { }; return rovi; } // "IsWindows10OrGreater()" isn't practically usable // - See "Windows Dev Center" -> "Version Helper functions" -> "IsWindows10OrGreater" at https://msdn.microsoft.com/en-us/library/windows/desktop/dn424972(v=vs.85).aspx // "For Windows 10, IsWindows10OrGreater returns false unless the application contains a manifest that includes a compatibility section that contains the GUID that designates Windows 10." [[nodiscard]] inline bool isWindows10OrGreater() { return (getRealOSVersion().dwMajorVersion >= 10); } //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] } // detail } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Direct3D11Rhi { //[-------------------------------------------------------] //[ Direct3D11Rhi/Direct3D11Rhi.h ] //[-------------------------------------------------------] struct CurrentGraphicsPipelineState final { Rhi::IGraphicsProgram* graphicsProgram = nullptr; ID3D11InputLayout* d3d11InputLayout = nullptr; ID3D11RasterizerState* d3d11RasterizerState = nullptr; ID3D11DepthStencilState* d3d11DepthStencilState = nullptr; ID3D11BlendState* d3d11BlendState = nullptr; }; /** * @brief * Direct3D 11 RHI class */ class Direct3D11Rhi final : public Rhi::IRhi { //[-------------------------------------------------------] //[ Friends ] //[-------------------------------------------------------] friend class GraphicsPipelineState; //[-------------------------------------------------------] //[ Public data ] //[-------------------------------------------------------] public: MakeID VertexArrayMakeId; MakeID GraphicsPipelineStateMakeId; MakeID ComputePipelineStateMakeId; //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] context * RHI context, the RHI context instance must stay valid as long as the RHI instance exists * * @note * - Do never ever use a not properly initialized RHI. Use "Rhi::IRhi::isInitialized()" to check the initialization state. */ explicit Direct3D11Rhi(const Rhi::Context& context); /** * @brief * Destructor */ virtual ~Direct3D11Rhi() override; /** * @brief * Return the Direct3D 11 device * * @return * The Direct3D 11 device, null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Device* getD3D11Device() const { return mD3D11Device; } /** * @brief * Return the immediate Direct3D 11 device context instance * * @return * The immediate Direct3D 11 device context instance, null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11DeviceContext* getD3D11DeviceContext() const { return mD3D11DeviceContext; } /** * @brief * Return the Direct3D feature level * * @return * The Direct3D feature level */ [[nodiscard]] inline D3D_FEATURE_LEVEL getD3DFeatureLevel() const { return mD3DFeatureLevel; } /** * @brief * Get the render target to render into * * @return * Render target currently bound to the output-merger state, a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline Rhi::IRenderTarget* omGetRenderTarget() const { return mRenderTarget; } void dispatchCommandBufferInternal(const Rhi::CommandBuffer& commandBuffer); //[-------------------------------------------------------] //[ Graphics ] //[-------------------------------------------------------] void setGraphicsRootSignature(Rhi::IRootSignature* rootSignature); void setGraphicsPipelineState(Rhi::IGraphicsPipelineState* graphicsPipelineState); void setGraphicsResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup); void setGraphicsVertexArray(Rhi::IVertexArray* vertexArray); // Input-assembler (IA) stage void setGraphicsViewports(uint32_t numberOfViewports, const Rhi::Viewport* viewports); // Rasterizer (RS) stage void setGraphicsScissorRectangles(uint32_t numberOfScissorRectangles, const Rhi::ScissorRectangle* scissorRectangles); // Rasterizer (RS) stage void setGraphicsRenderTarget(Rhi::IRenderTarget* renderTarget); // Output-merger (OM) stage void clearGraphics(uint32_t flags, const float color[4], float z, uint32_t stencil); void drawGraphics(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); void drawGraphicsAgs(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); void drawGraphicsNvApi(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); void drawGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); void drawIndexedGraphics(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); void drawIndexedGraphicsAgs(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); void drawIndexedGraphicsNvApi(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); void drawIndexedGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); //[-------------------------------------------------------] //[ Compute ] //[-------------------------------------------------------] void setComputeRootSignature(Rhi::IRootSignature* rootSignature); void setComputePipelineState(Rhi::IComputePipelineState* computePipelineState); void setComputeResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup); void dispatchCompute(uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ); //[-------------------------------------------------------] //[ Resource ] //[-------------------------------------------------------] void resolveMultisampleFramebuffer(Rhi::IRenderTarget& destinationRenderTarget, Rhi::IFramebuffer& sourceMultisampleFramebuffer); void copyResource(Rhi::IResource& destinationResource, Rhi::IResource& sourceResource); void generateMipmaps(Rhi::IResource& resource); void generateAsynchronousDeferredMipmaps(Rhi::ITexture& texture, ID3D11ShaderResourceView& d3d11ShaderResourceView); //[-------------------------------------------------------] //[ Query ] //[-------------------------------------------------------] void resetQueryPool(Rhi::IQueryPool& queryPool, uint32_t firstQueryIndex, uint32_t numberOfQueries); void beginQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex, uint32_t queryControlFlags); void endQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex); void writeTimestampQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex); //[-------------------------------------------------------] //[ Debug ] //[-------------------------------------------------------] #ifdef RHI_DEBUG void setDebugMarker(const char* name); void beginDebugEvent(const char* name); void endDebugEvent(); #endif //[-------------------------------------------------------] //[ Public virtual Rhi::IRhi methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getName() const override { return "Direct3D11"; } [[nodiscard]] inline virtual bool isInitialized() const override { // Is there a Direct3D 11 device? return (nullptr != mD3D11Device); } [[nodiscard]] virtual bool isDebugEnabled() override; //[-------------------------------------------------------] //[ Shader language ] //[-------------------------------------------------------] [[nodiscard]] virtual uint32_t getNumberOfShaderLanguages() const override; [[nodiscard]] virtual const char* getShaderLanguageName(uint32_t index) const override; [[nodiscard]] virtual Rhi::IShaderLanguage* getShaderLanguage(const char* shaderLanguageName = nullptr) override; //[-------------------------------------------------------] //[ Resource creation ] //[-------------------------------------------------------] [[nodiscard]] virtual Rhi::IRenderPass* createRenderPass(uint32_t numberOfColorAttachments, const Rhi::TextureFormat::Enum* colorAttachmentTextureFormats, Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat = Rhi::TextureFormat::UNKNOWN, uint8_t numberOfMultisamples = 1 RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IQueryPool* createQueryPool(Rhi::QueryType queryType, uint32_t numberOfQueries = 1 RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::ISwapChain* createSwapChain(Rhi::IRenderPass& renderPass, Rhi::WindowHandle windowHandle, bool useExternalContext = false RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IFramebuffer* createFramebuffer(Rhi::IRenderPass& renderPass, const Rhi::FramebufferAttachment* colorFramebufferAttachments, const Rhi::FramebufferAttachment* depthStencilFramebufferAttachment = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IBufferManager* createBufferManager() override; [[nodiscard]] virtual Rhi::ITextureManager* createTextureManager() override; [[nodiscard]] virtual Rhi::IRootSignature* createRootSignature(const Rhi::RootSignature& rootSignature RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IGraphicsPipelineState* createGraphicsPipelineState(const Rhi::GraphicsPipelineState& graphicsPipelineState RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IComputePipelineState* createComputePipelineState(Rhi::IRootSignature& rootSignature, Rhi::IComputeShader& computeShader RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::ISamplerState* createSamplerState(const Rhi::SamplerState& samplerState RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; //[-------------------------------------------------------] //[ Resource handling ] //[-------------------------------------------------------] [[nodiscard]] virtual bool map(Rhi::IResource& resource, uint32_t subresource, Rhi::MapType mapType, uint32_t mapFlags, Rhi::MappedSubresource& mappedSubresource) override; virtual void unmap(Rhi::IResource& resource, uint32_t subresource) override; [[nodiscard]] virtual bool getQueryPoolResults(Rhi::IQueryPool& queryPool, uint32_t numberOfDataBytes, uint8_t* data, uint32_t firstQueryIndex = 0, uint32_t numberOfQueries = 1, uint32_t strideInBytes = 0, uint32_t queryResultFlags = 0) override; //[-------------------------------------------------------] //[ Operation ] //[-------------------------------------------------------] virtual void dispatchCommandBuffer(const Rhi::CommandBuffer& commandBuffer) override; //[-------------------------------------------------------] //[ Implementation specific ] //[-------------------------------------------------------] [[nodiscard]] inline virtual void* getD3D11DevicePointer() const override { return mD3D11Device; } [[nodiscard]] inline virtual void* getD3D11ImmediateContextPointer() const override { return mD3D11DeviceContext; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(mContext, Direct3D11Rhi, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Direct3D11Rhi(const Direct3D11Rhi& source) = delete; Direct3D11Rhi& operator =(const Direct3D11Rhi& source) = delete; /** * @brief * Initialize the capabilities */ void initializeCapabilities(); /** * @brief * Set graphics program * * @param[in] graphicsProgram * Graphics program to set */ void setGraphicsProgram(Rhi::IGraphicsProgram* graphicsProgram); //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Direct3D11RuntimeLinking* mDirect3D11RuntimeLinking; ///< Direct3D 11 runtime linking instance, always valid ID3D11Device* mD3D11Device; ///< The Direct3D 11 device, null pointer on error (we don't check because this would be a total overhead, the user has to use "Rhi::IRhi::isInitialized()" and is asked to never ever use a not properly initialized RHI) ID3D11DeviceContext* mD3D11DeviceContext; ///< The Direct3D 11 device context instance, null pointer on error (we don't check because this would be a total overhead, the user has to use "Rhi::IRhi::isInitialized()" and is asked to never ever use a not properly initialized RHI) D3D_FEATURE_LEVEL mD3DFeatureLevel; ID3DUserDefinedAnnotation* mD3DUserDefinedAnnotation; ///< The Direct3D 11 user defined annotation interface, null pointer on error, Direct3D 11.1 feature Rhi::IShaderLanguage* mShaderLanguageHlsl; ///< HLSL shader language instance (we keep a reference to it), can be a null pointer ID3D11Query* mD3D11QueryFlush; ///< Direct3D 11 query used for flush, can be a null pointer Rhi::IRenderTarget* mRenderTarget; ///< Currently set render target (we keep a reference to it), can be a null pointer RootSignature* mGraphicsRootSignature; ///< Currently set graphics root signature (we keep a reference to it), can be a null pointer RootSignature* mComputeRootSignature; ///< Currently set compute root signature (we keep a reference to it), can be a null pointer // State cache to avoid making redundant Direct3D 11 calls CurrentGraphicsPipelineState mCurrentGraphicsPipelineState; D3D11_PRIMITIVE_TOPOLOGY mD3D11PrimitiveTopology; ID3D11VertexShader* mD3d11VertexShader; ID3D11HullShader* mD3d11HullShader; ID3D11DomainShader* mD3d11DomainShader; ID3D11GeometryShader* mD3d11GeometryShader; ID3D11PixelShader* mD3d11PixelShader; ID3D11ComputeShader* mD3d11ComputeShader; // Generate asynchronous mipmaps for textures std::mutex mGenerateAsynchronousMipmapsForTexturesMutex; std::vector<Rhi::ITexture*> mGenerateAsynchronousMipmapsForTextures; }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Direct3D11RuntimeLinking.h ] //[-------------------------------------------------------] //[-------------------------------------------------------] //[ Macros & definitions ] //[-------------------------------------------------------] // Redirect D3D11* function calls to funcPtr_D3D11* #ifndef FNPTR #define FNPTR(name) funcPtr_##name #endif //[-------------------------------------------------------] //[ DXGI core functions ] //[-------------------------------------------------------] #define FNDEF_DXGI(retType, funcName, args) retType (WINAPI *funcPtr_##funcName) args FNDEF_DXGI(HRESULT, CreateDXGIFactory, (REFIID riid, _COM_Outptr_ void **ppFactory)); #define CreateDXGIFactory FNPTR(CreateDXGIFactory) //[-------------------------------------------------------] //[ D3D11 core functions ] //[-------------------------------------------------------] #define FNDEF_D3D11(retType, funcName, args) retType (WINAPI *funcPtr_##funcName) args FNDEF_D3D11(HRESULT, D3D11CreateDevice, (__in_opt IDXGIAdapter*, D3D_DRIVER_TYPE, HMODULE, UINT, __in_ecount_opt( FeatureLevels ) CONST D3D_FEATURE_LEVEL*, UINT, UINT, __out_opt ID3D11Device**, __out_opt D3D_FEATURE_LEVEL*, __out_opt ID3D11DeviceContext**)); #define D3D11CreateDevice FNPTR(D3D11CreateDevice) //[-------------------------------------------------------] //[ D3DCompiler functions ] //[-------------------------------------------------------] #define FNDEF_D3DCOMPILER(retType, funcName, args) retType (WINAPI *funcPtr_##funcName) args typedef __interface ID3D10Blob *LPD3D10BLOB; // "__interface" is no keyword of the ISO C++ standard, shouldn't be a problem because this in here is Microsoft Windows only and it's also within the Direct3D headers we have to use typedef ID3D10Blob ID3DBlob; FNDEF_D3DCOMPILER(HRESULT, D3DCompile, (LPCVOID, SIZE_T, LPCSTR, CONST D3D_SHADER_MACRO*, ID3DInclude*, LPCSTR, LPCSTR, UINT, UINT, ID3DBlob**, ID3DBlob**)); FNDEF_D3DCOMPILER(HRESULT, D3DCreateBlob, (SIZE_T Size, ID3DBlob** ppBlob)); #define D3DCompile FNPTR(D3DCompile) #define D3DCreateBlob FNPTR(D3DCreateBlob) //[-------------------------------------------------------] //[ AMD AGS functions ] //[-------------------------------------------------------] } extern "C" { // -> Using AMD AGS v5.3.0 - November 22, 2018 // -> From https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK and https://raw.githubusercontent.com/GPUOpen-LibrariesAndSDKs/Barycentrics12/master/ags_lib/inc/amd_ags.h // -> We're using the static linked version of AMD AGS in order to reduce the number of individual shipped files // -> For debug builds there are no static AMD AGS libraries available #ifdef RHI_DEBUG #define DYNAMIC_AMD_AGS #endif struct AGSGPUInfo; typedef void* (__stdcall *AGS_ALLOC_CALLBACK)(size_t allocationSize); typedef void (__stdcall *AGS_FREE_CALLBACK)(void* allocationPtr); struct AGSConfiguration { AGS_ALLOC_CALLBACK allocCallback; AGS_FREE_CALLBACK freeCallback; }; struct AGSDX11DeviceCreationParams { IDXGIAdapter* pAdapter; D3D_DRIVER_TYPE DriverType; HMODULE Software; UINT Flags; const D3D_FEATURE_LEVEL* pFeatureLevels; UINT FeatureLevels; UINT SDKVersion; const DXGI_SWAP_CHAIN_DESC* pSwapChainDesc; }; enum AGSCrossfireMode { AGS_CROSSFIRE_MODE_DRIVER_AFR = 0, AGS_CROSSFIRE_MODE_EXPLICIT_AFR, AGS_CROSSFIRE_MODE_DISABLE }; struct AGSDX11ExtensionParams { const WCHAR* pAppName; const WCHAR* pEngineName; unsigned int appVersion; unsigned int engineVersion; unsigned int numBreadcrumbMarkers; unsigned int uavSlot; AGSCrossfireMode crossfireMode; }; struct AGSDX11ReturnedParams { ID3D11Device* pDevice; ID3D11DeviceContext* pImmediateContext; IDXGISwapChain* pSwapChain; D3D_FEATURE_LEVEL FeatureLevel; unsigned int extensionsSupported; unsigned int crossfireGPUCount; void* breadcrumbBuffer; }; enum AGSReturnCode { AGS_SUCCESS, AGS_FAILURE, AGS_INVALID_ARGS, AGS_OUT_OF_MEMORY, AGS_ERROR_MISSING_DLL, AGS_ERROR_LEGACY_DRIVER, AGS_EXTENSION_NOT_SUPPORTED, AGS_ADL_FAILURE, AGS_DX_FAILURE }; #ifdef DYNAMIC_AMD_AGS #define FNDEF_AMD_AGS(retType, funcName, args) retType (WINAPIV *funcPtr_##funcName) args #else #define FNDEF_AMD_AGS(retType, funcName, args) retType WINAPIV funcName args #endif FNDEF_AMD_AGS(AGSReturnCode, agsInit, (AGSContext** context, const AGSConfiguration* config, AGSGPUInfo* gpuInfo)); FNDEF_AMD_AGS(AGSReturnCode, agsDeInit, (AGSContext* context)); FNDEF_AMD_AGS(AGSReturnCode, agsDriverExtensionsDX11_CreateDevice, (AGSContext* context, AGSDX11DeviceCreationParams* creationParams, AGSDX11ExtensionParams* extensionParams, AGSDX11ReturnedParams* returnedParams)); FNDEF_AMD_AGS(AGSReturnCode, agsDriverExtensionsDX11_DestroyDevice, (AGSContext* context, ID3D11Device* device, unsigned int* deviceReferences, ID3D11DeviceContext* immediateContext, unsigned int* immediateContextReferences)); FNDEF_AMD_AGS(AGSReturnCode, agsDriverExtensionsDX11_MultiDrawInstancedIndirect, (AGSContext* context, ID3D11DeviceContext* dxContext, unsigned int drawCount, ID3D11Buffer* pBufferForArgs, unsigned int alignedByteOffsetForArgs, unsigned int byteStrideForArgs)); FNDEF_AMD_AGS(AGSReturnCode, agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect, (AGSContext* context, ID3D11DeviceContext* dxContext, unsigned int drawCount, ID3D11Buffer* pBufferForArgs, unsigned int alignedByteOffsetForArgs, unsigned int byteStrideForArgs)); #ifdef DYNAMIC_AMD_AGS #define agsInit FNPTR(agsInit) #define agsDeInit FNPTR(agsDeInit) #define agsDriverExtensionsDX11_CreateDevice FNPTR(agsDriverExtensionsDX11_CreateDevice) #define agsDriverExtensionsDX11_DestroyDevice FNPTR(agsDriverExtensionsDX11_DestroyDevice) #define agsDriverExtensionsDX11_MultiDrawInstancedIndirect FNPTR(agsDriverExtensionsDX11_MultiDrawInstancedIndirect) #define agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect FNPTR(agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect) #else #ifdef ARCHITECTURE_X64 #ifdef RHI_DIRECT3D11_EXPORTS // Dynamic library is using "Multi-threaded DLL (/MD)" #pragma comment(lib, "amd_ags_x64_2017_MD.lib") #else // Static library is using "Multi-threaded (/MT)" #pragma comment(lib, "amd_ags_x64_2017_MT.lib") #endif #else #ifdef RHI_DIRECT3D11_EXPORTS // Dynamic library is using "Multi-threaded DLL (/MD)" #pragma comment(lib, "amd_ags_x86_2017_MD.lib") #else // Static library is using "Multi-threaded (/MT)" #pragma comment(lib, "amd_ags_x86_2017_MT.lib") #endif #endif #endif Rhi::IAllocator* g_AmdAgsAllocator = nullptr; ///< Evil global variable since AMD AGS doesn't allow to pass in user data to the allocator functions [[nodiscard]] void* __stdcall AmdAgsAllocCallback(size_t allocationSize) { return g_AmdAgsAllocator->reallocate(nullptr, 0, allocationSize, 1); } void __stdcall AmdAgsFreeCallback(void* allocationPtr) { g_AmdAgsAllocator->reallocate(allocationPtr, 0, 0, 1); } } namespace Direct3D11Rhi { //[-------------------------------------------------------] //[ NvAPI functions ] //[-------------------------------------------------------] // From https://developer.nvidia.com/nvapi and http://developer.download.nvidia.com/NVAPI/PG-5116-001_v01_public.pdf #define FNDEF_NvAPI(retType, funcName, args) retType (WINAPIV *funcPtr_##funcName) args typedef int NvAPI_Status; typedef unsigned int NvU32; FNDEF_NvAPI(NvAPI_Status, NvAPI_Initialize, ()); FNDEF_NvAPI(NvAPI_Status, NvAPI_Unload, ()); FNDEF_NvAPI(NvAPI_Status, NvAPI_D3D11_MultiDrawInstancedIndirect, (__in ID3D11DeviceContext* pDevContext11, __in NvU32 drawCount, __in ID3D11Buffer* pBuffer, __in NvU32 alignedByteOffsetForArgs, __in NvU32 alignedByteStrideForArgs)); FNDEF_NvAPI(NvAPI_Status, NvAPI_D3D11_MultiDrawIndexedInstancedIndirect, (__in ID3D11DeviceContext* pDevContext11, __in NvU32 drawCount, __in ID3D11Buffer* pBuffer, __in NvU32 alignedByteOffsetForArgs, __in NvU32 alignedByteStrideForArgs)); #define NvAPI_Initialize FNPTR(NvAPI_Initialize) #define NvAPI_Unload FNPTR(NvAPI_Unload) #define NvAPI_D3D11_MultiDrawInstancedIndirect FNPTR(NvAPI_D3D11_MultiDrawInstancedIndirect) #define NvAPI_D3D11_MultiDrawIndexedInstancedIndirect FNPTR(NvAPI_D3D11_MultiDrawIndexedInstancedIndirect) /** * @brief * Direct3D 11 runtime linking */ class Direct3D11RuntimeLinking final { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance */ inline explicit Direct3D11RuntimeLinking(Direct3D11Rhi& direct3D11Rhi) : mDirect3D11Rhi(direct3D11Rhi), mDxgiSharedLibrary(nullptr), mD3D11SharedLibrary(nullptr), mD3DCompilerSharedLibrary(nullptr), #ifdef DYNAMIC_AMD_AGS mAmdAgsSharedLibrary(nullptr), #endif mAgsContext(nullptr), mNvAPISharedLibrary(nullptr), mEntryPointsRegistered(false), mInitialized(false) {} /** * @brief * Destructor */ ~Direct3D11RuntimeLinking() { // Destroy the shared library instances if (nullptr != mDxgiSharedLibrary) { ::FreeLibrary(static_cast<HMODULE>(mDxgiSharedLibrary)); } if (nullptr != mD3D11SharedLibrary) { ::FreeLibrary(static_cast<HMODULE>(mD3D11SharedLibrary)); } if (nullptr != mD3DCompilerSharedLibrary) { ::FreeLibrary(static_cast<HMODULE>(mD3DCompilerSharedLibrary)); } #ifdef DYNAMIC_AMD_AGS if (nullptr != mAmdAgsSharedLibrary) { if (nullptr != agsDeInit && AGS_SUCCESS != agsDeInit(mAgsContext)) { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Direct3D 11: Failed to unload AMG AGS") } ::FreeLibrary(static_cast<HMODULE>(mAmdAgsSharedLibrary)); } #else if (nullptr != g_AmdAgsAllocator && AGS_SUCCESS != agsDeInit(mAgsContext)) { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Direct3D 11: Failed to unload AMG AGS") } #endif if (nullptr != mNvAPISharedLibrary) { if (nullptr != NvAPI_Unload && 0 != NvAPI_Unload()) { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Direct3D 11: Failed to unload NvAPI") } ::FreeLibrary(static_cast<HMODULE>(mNvAPISharedLibrary)); } } /** * @brief * Return whether or not Direct3D 11 is available * * @return * "true" if Direct3D 11 is available, else "false" */ [[nodiscard]] bool isDirect3D11Avaiable() { // Already initialized? if (!mInitialized) { // We're now initialized mInitialized = true; // Load the shared libraries if (loadSharedLibraries()) { // Load the DXGI, D3D11 and D3DCompiler entry points mEntryPointsRegistered = (loadDxgiEntryPoints() && loadD3D11EntryPoints() && loadD3DCompilerEntryPoints()); // AMD AGS and NvAPI for e.g. multi-draw-indirect support if (mEntryPointsRegistered) { // Check whether or not the primary DXGI adapter is an AMD GPU bool amdDxgiAdapter = false; bool nvidiaDxgiAdapter = false; { // Get the primary DXGI adapter IDXGIFactory* dxgiFactory = nullptr; FAILED_DEBUG_BREAK(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&dxgiFactory)) if (nullptr == dxgiFactory) { // Error! return false; } IDXGIAdapter* dxgiAdapter = nullptr; FAILED_DEBUG_BREAK(dxgiFactory->EnumAdapters(0, &dxgiAdapter)) DXGI_ADAPTER_DESC dxgiAdapterDesc = {}; FAILED_DEBUG_BREAK(dxgiAdapter->GetDesc(&dxgiAdapterDesc)) if (0x1414 == dxgiAdapterDesc.VendorId) // 0x1414 = "Capture Adapter" when using Visual Studio graphics debugger { RHI_LOG(mDirect3D11Rhi.getContext(), COMPATIBILITY_WARNING, "Direct3D 11 capture adapter used (e.g. Visual Studio graphics debugger), AMD AGS and NvAPI support disabled") } else { amdDxgiAdapter = (0x1002 == dxgiAdapterDesc.VendorId); // 0x1002 -> See "How-To Identify the Manufacturer and Model of an AMD Graphics Card" at http://support.amd.com/en-us/kb-articles/Pages/HowtoidentifythemodelofanATIgraphicscard.aspx nvidiaDxgiAdapter = (0x10DE == dxgiAdapterDesc.VendorId); // 0x10DE -> See "Device IDs" at http://www.nvidia.com/object/device_ids.html } dxgiAdapter->Release(); dxgiFactory->Release(); } // Optional vendor specific part: AMD AGS if (amdDxgiAdapter) { g_AmdAgsAllocator = &mDirect3D11Rhi.getContext().getAllocator(); #ifdef DYNAMIC_AMD_AGS #ifdef ARCHITECTURE_X64 static constexpr const char* AMD_AGS_SHARED_LIBRARY_NAME = "amd_ags_x64.dll"; #else static constexpr const char* AMD_AGS_SHARED_LIBRARY_NAME = "amd_ags_x86.dll"; #endif mAmdAgsSharedLibrary = ::LoadLibraryExA(AMD_AGS_SHARED_LIBRARY_NAME, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); if (nullptr != mAmdAgsSharedLibrary) { if (!loadAmdAgsEntryPoints()) { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Direct3D 11: Failed to load AMD AGS function entry points") ::FreeLibrary(static_cast<HMODULE>(mAmdAgsSharedLibrary)); mAmdAgsSharedLibrary = nullptr; agsInit = nullptr; agsDeInit = nullptr; agsDriverExtensionsDX11_CreateDevice = nullptr; agsDriverExtensionsDX11_DestroyDevice = nullptr; agsDriverExtensionsDX11_MultiDrawInstancedIndirect = nullptr; agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect = nullptr; } } else { RHI_LOG(mDirect3D11Rhi.getContext(), PERFORMANCE_WARNING, "Direct3D 11: Failed to load the AMD AGS shared library \"%s\"", AMD_AGS_SHARED_LIBRARY_NAME) } #else { // Initialize AMD AGS (e.g. for multi-indirect-draw support) const AGSConfiguration agsConfiguration = { &AmdAgsAllocCallback, &AmdAgsFreeCallback }; if (AGS_SUCCESS == agsInit(&mAgsContext, &agsConfiguration, nullptr)) { RHI_LOG(mDirect3D11Rhi.getContext(), TRACE, "Direct3D 11: Successfully initialized AMD AGS") } else { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Direct3D 11: Failed to initialize AMD AGS") } } #endif } // Optional vendor specific part: NvAPI if (nvidiaDxgiAdapter) { #ifdef ARCHITECTURE_X64 static constexpr const char* NVAPI_SHARED_LIBRARY_NAME = "nvapi64.dll"; #else static constexpr const char* NVAPI_SHARED_LIBRARY_NAME = "nvapi.dll"; #endif mNvAPISharedLibrary = ::LoadLibraryExA(NVAPI_SHARED_LIBRARY_NAME, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); if (nullptr != mNvAPISharedLibrary) { if (!loadNvAPIEntryPoints()) { RHI_LOG(mDirect3D11Rhi.getContext(), PERFORMANCE_WARNING, "Direct3D 11: Failed to load NvAPI function entry points, maybe a graphics debugger like RenderDoc disabled NvAPI") ::FreeLibrary(static_cast<HMODULE>(mNvAPISharedLibrary)); mNvAPISharedLibrary = nullptr; NvAPI_Initialize = nullptr; NvAPI_Unload = nullptr; NvAPI_D3D11_MultiDrawInstancedIndirect = nullptr; NvAPI_D3D11_MultiDrawIndexedInstancedIndirect = nullptr; } } else { RHI_LOG(mDirect3D11Rhi.getContext(), PERFORMANCE_WARNING, "Direct3D 11: Failed to load the NvAPI shared library \"%s\"", NVAPI_SHARED_LIBRARY_NAME) } } } } } // Entry points successfully registered? return mEntryPointsRegistered; } /** * @brief * Return the AMD AGS instance * * @return * The AMD AGS instance, can be a null pointer, don't destroy the returned instance */ [[nodiscard]] inline AGSContext* getAgsContext() const { return mAgsContext; } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Direct3D11RuntimeLinking(const Direct3D11RuntimeLinking& source) = delete; Direct3D11RuntimeLinking& operator =(const Direct3D11RuntimeLinking& source) = delete; /** * @brief * Load the shared libraries * * @return * "true" if all went fine, else "false" */ [[nodiscard]] bool loadSharedLibraries() { // Load the shared library mDxgiSharedLibrary = ::LoadLibraryExA("dxgi.dll", nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); if (nullptr != mDxgiSharedLibrary) { mD3D11SharedLibrary = ::LoadLibraryExA("d3d11.dll", nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); if (nullptr != mD3D11SharedLibrary) { mD3DCompilerSharedLibrary = ::LoadLibraryExA("D3DCompiler_47.dll", nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); if (nullptr == mD3DCompilerSharedLibrary) { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Failed to load in the shared Direct3D 11 library \"D3DCompiler_47.dll\"") } } else { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Failed to load in the shared Direct3D 11 library \"d3d11.dll\"") } } else { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Failed to load in the shared Direct3D 11 library \"dxgi.dll\"") } // Done return (nullptr != mDxgiSharedLibrary && nullptr != mD3D11SharedLibrary && nullptr != mD3DCompilerSharedLibrary); } /** * @brief * Load the DXGI entry points * * @return * "true" if all went fine, else "false" */ [[nodiscard]] bool loadDxgiEntryPoints() { bool result = true; // Success by default // Define a helper macro #define IMPORT_FUNC(funcName) \ if (result) \ { \ void* symbol = ::GetProcAddress(static_cast<HMODULE>(mDxgiSharedLibrary), #funcName); \ if (nullptr != symbol) \ { \ *(reinterpret_cast<void**>(&(funcName))) = symbol; \ } \ else \ { \ wchar_t moduleFilename[MAX_PATH]; \ moduleFilename[0] = '\0'; \ ::GetModuleFileNameW(static_cast<HMODULE>(mDxgiSharedLibrary), moduleFilename, MAX_PATH); \ RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Failed to locate the entry point \"%s\" within the Direct3D 11 DXGI shared library \"%s\"", #funcName, moduleFilename) \ result = false; \ } \ } // Load the entry points IMPORT_FUNC(CreateDXGIFactory) // Undefine the helper macro #undef IMPORT_FUNC // Done return result; } /** * @brief * Load the D3D11 entry points * * @return * "true" if all went fine, else "false" */ [[nodiscard]] bool loadD3D11EntryPoints() { bool result = true; // Success by default // Define a helper macro #define IMPORT_FUNC(funcName) \ if (result) \ { \ void* symbol = ::GetProcAddress(static_cast<HMODULE>(mD3D11SharedLibrary), #funcName); \ if (nullptr != symbol) \ { \ *(reinterpret_cast<void**>(&(funcName))) = symbol; \ } \ else \ { \ wchar_t moduleFilename[MAX_PATH]; \ moduleFilename[0] = '\0'; \ ::GetModuleFileNameW(static_cast<HMODULE>(mD3D11SharedLibrary), moduleFilename, MAX_PATH); \ RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Failed to locate the entry point \"%s\" within the Direct3D 11 shared library \"%s\"", #funcName, moduleFilename) \ result = false; \ } \ } // Load the entry points IMPORT_FUNC(D3D11CreateDevice) // Undefine the helper macro #undef IMPORT_FUNC // Done return result; } /** * @brief * Load the D3DCompiler entry points * * @return * "true" if all went fine, else "false" */ [[nodiscard]] bool loadD3DCompilerEntryPoints() { bool result = true; // Success by default // Define a helper macro #define IMPORT_FUNC(funcName) \ if (result) \ { \ void* symbol = ::GetProcAddress(static_cast<HMODULE>(mD3DCompilerSharedLibrary), #funcName); \ if (nullptr != symbol) \ { \ *(reinterpret_cast<void**>(&(funcName))) = symbol; \ } \ else \ { \ wchar_t moduleFilename[MAX_PATH]; \ moduleFilename[0] = '\0'; \ ::GetModuleFileNameW(static_cast<HMODULE>(mD3DCompilerSharedLibrary), moduleFilename, MAX_PATH); \ RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Failed to locate the entry point \"%s\" within the Direct3D 11 shared library \"%s\"", #funcName, moduleFilename) \ result = false; \ } \ } // Load the entry points IMPORT_FUNC(D3DCompile) IMPORT_FUNC(D3DCreateBlob) // Undefine the helper macro #undef IMPORT_FUNC // Done return result; } #ifdef DYNAMIC_AMD_AGS /** * @brief * Load the AMD AGS entry points * * @return * "true" if all went fine, else "false" */ [[nodiscard]] bool loadAmdAgsEntryPoints() { bool result = true; // Success by default // Define a helper macro #define IMPORT_FUNC(funcName) \ if (result) \ { \ void* symbol = ::GetProcAddress(static_cast<HMODULE>(mAmdAgsSharedLibrary), #funcName); \ if (nullptr != symbol) \ { \ *(reinterpret_cast<void**>(&(funcName))) = symbol; \ } \ else \ { \ wchar_t moduleFilename[MAX_PATH]; \ moduleFilename[0] = '\0'; \ ::GetModuleFileNameW(static_cast<HMODULE>(mAmdAgsSharedLibrary), moduleFilename, MAX_PATH); \ RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Failed to locate the entry point \"%s\" within the AMD AGS shared library \"%s\"", #funcName, moduleFilename) \ result = false; \ } \ } // Load the entry points IMPORT_FUNC(agsInit) IMPORT_FUNC(agsDeInit) IMPORT_FUNC(agsDriverExtensionsDX11_CreateDevice) IMPORT_FUNC(agsDriverExtensionsDX11_DestroyDevice) IMPORT_FUNC(agsDriverExtensionsDX11_MultiDrawInstancedIndirect) IMPORT_FUNC(agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect) // Undefine the helper macro #undef IMPORT_FUNC // Initialize AMD AGS (e.g. for multi-indirect-draw support) if (nullptr != agsInit) { const AGSConfiguration agsConfiguration = { &AmdAgsAllocCallback, &AmdAgsFreeCallback }; if (AGS_SUCCESS == agsInit(&mAgsContext, &agsConfiguration, nullptr)) { RHI_LOG(mDirect3D11Rhi.getContext(), TRACE, "Direct3D 11: Successfully initialized AMD AGS") } else { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Direct3D 11: Failed to initialize AMD AGS") result = false; } } // Done return result; } #endif /** * @brief * Load the NvAPI entry points * * @return * "true" if all went fine, else "false" */ [[nodiscard]] bool loadNvAPIEntryPoints() { bool result = true; // Success by default // Define a helper macro #define IMPORT_FUNC(funcName) \ void* symbol = ::GetProcAddress(static_cast<HMODULE>(mNvAPISharedLibrary), #funcName); \ if (nullptr != symbol) \ { \ *(reinterpret_cast<void**>(&(funcName))) = symbol; \ } \ else \ { \ wchar_t moduleFilename[MAX_PATH]; \ moduleFilename[0] = '\0'; \ ::GetModuleFileNameW(static_cast<HMODULE>(mNvAPISharedLibrary), moduleFilename, MAX_PATH); \ RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Failed to locate the entry point \"%s\" within the NvAPI shared library \"%s\"", #funcName, moduleFilename) \ result = false; \ } FNDEF_NvAPI(void*, nvapi_QueryInterface, (unsigned int offset)); #define nvapi_QueryInterface FNPTR(nvapi_QueryInterface) #define IMPORT_NVAPI_FUNC(funcName, ID) \ *(reinterpret_cast<void**>(&(funcName))) = nvapi_QueryInterface(ID); \ if (nullptr == funcName) \ { \ result = false; \ } // Load the entry points nvapi_QueryInterface = nullptr; IMPORT_FUNC(nvapi_QueryInterface) // Query function pointers if (nullptr != nvapi_QueryInterface) { IMPORT_NVAPI_FUNC(NvAPI_Initialize, 0x150E828UL) IMPORT_NVAPI_FUNC(NvAPI_Unload, 0xD22BDD7EUL) IMPORT_NVAPI_FUNC(NvAPI_D3D11_MultiDrawInstancedIndirect, 0xD4E26BBF) IMPORT_NVAPI_FUNC(NvAPI_D3D11_MultiDrawIndexedInstancedIndirect, 0x59E890F9) } // Undefine the helper macro #undef IMPORT_NVAPI_FUNC #undef NvAPI_QueryInterface #undef IMPORT_FUNC // Initialize NvAPI (e.g. for multi-indirect-draw support) if (result) { if (nullptr != NvAPI_Initialize && 0 == NvAPI_Initialize()) { RHI_LOG(mDirect3D11Rhi.getContext(), TRACE, "Direct3D 11: Successfully initialized NvAPI") } else { RHI_LOG(mDirect3D11Rhi.getContext(), CRITICAL, "Direct3D 11: Failed to initialize NvAPI") result = false; } } // Done return result; } //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Direct3D11Rhi& mDirect3D11Rhi; ///< Owner Direct3D 11 RHI instance void* mDxgiSharedLibrary; ///< DXGI shared library, can be a null pointer void* mD3D11SharedLibrary; ///< D3D11 shared library, can be a null pointer void* mD3DCompilerSharedLibrary; ///< D3DCompiler shared library, can be a null pointer #ifdef DYNAMIC_AMD_AGS void* mAmdAgsSharedLibrary; ///< AMD AGS shared library, can be a null pointer #endif AGSContext* mAgsContext; ///< AMD AGS context, can be a null pointer void* mNvAPISharedLibrary; ///< NvAPI shared library, can be a null pointer bool mEntryPointsRegistered; ///< Entry points successfully registered? bool mInitialized; ///< Already initialized? }; //[-------------------------------------------------------] //[ Global definitions ] //[-------------------------------------------------------] // In order to assign debug names to Direct3D resources we need to use the "WKPDID_D3DDebugObjectName"-GUID. This GUID // is defined within the "D3Dcommon.h" header and it's required to add the library "dxguid.lib" in which the symbol // is defined. // -> See "ID3D11Device::SetPrivateData method"-documentation at MSDN http://msdn.microsoft.com/en-us/library/windows/desktop/ff476533%28v=vs.85%29.aspx // The "Community Additions" states: "If you get a missing symbol error: Note that WKPDID_D3DDebugObjectName // requires both that you include D3Dcommon.h, and that you link against dxguid.lib." // -> We don't want to deal with a 800 KB library "just" for such a tiny symbol for several reasons. For once it's not // allowed to redistribute "dxguid.lib" due to DirectX SDK licensing terms. Another reason for avoiding libraries // were ever possible is that every library will increase the complexity of the build system and will also make // it harder to port to other platforms - we already would need 32 bit and 64 bit versions for standard Windows // systems. We don't want that just for resolving a tiny symbol. // // "WKPDID_D3DDebugObjectName" is defined within the "D3Dcommon.h"-header as // DEFINE_GUID(WKPDID_D3DDebugObjectName,0x429b8c22,0x9188,0x4b0c,0x87,0x42,0xac,0xb0,0xbf,0x85,0xc2,0x00); // // While the "DEFINE_GUID"-macro is defined within the "Guiddef.h"-header as // #ifdef INITGUID // #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ // EXTERN_C const GUID DECLSPEC_SELECTANY name \ // = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } // #else // #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ // EXTERN_C const GUID FAR name // #endif // INITGUID // // "GUID" is a structure defined within the "Guiddef.h"-header as // typedef struct _GUID { // unsigned long Data1; // unsigned short Data2; // unsigned short Data3; // unsigned char Data4[ 8 ]; // } GUID; #define RHI_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) constexpr GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } RHI_DEFINE_GUID(WKPDID_D3DDebugObjectName, 0x429b8c22, 0x9188, 0x4b0c, 0x87, 0x42, 0xac, 0xb0, 0xbf, 0x85, 0xc2, 0x00); //[-------------------------------------------------------] //[ Global functions ] //[-------------------------------------------------------] /** * @brief * Creates, loads and compiles a shader from source code * * @param[in] context * RHI context * @param[in] shaderModel * ASCII shader model (for example "vs_4_0", "gs_4_0", "ps_4_0"), must be a valid pointer * @param[in] sourceCode * ASCII shader ASCII source code, must be a valid pointer * @param[in] entryPoint * Optional ASCII entry point, if null pointer "main" is used * @param[in] optimizationLevel * Optimization level * * @return * The loaded and compiled shader, can be a null pointer, release the instance if you no longer need it */ [[nodiscard]] ID3DBlob* loadShaderFromSourcecode(const Rhi::Context& context, const char* shaderModel, const char* sourceCode, const char* entryPoint, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel) { // Sanity checks RHI_ASSERT(context, nullptr != shaderModel, "Invalid Direct3D 11 shader model") RHI_ASSERT(context, nullptr != sourceCode, "Invalid Direct3D 11 shader source code") // Get compile flags // -> "DX12 Do's And Don'ts" ( https://developer.nvidia.com/dx12-dos-and-donts ) "Use the /all_resources_bound / D3DCOMPILE_ALL_RESOURCES_BOUND compile flag if possible" UINT compileFlags = (D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS | D3DCOMPILE_ALL_RESOURCES_BOUND); switch (optimizationLevel) { case Rhi::IShaderLanguage::OptimizationLevel::DEBUG: compileFlags |= D3DCOMPILE_DEBUG; compileFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; break; case Rhi::IShaderLanguage::OptimizationLevel::NONE: compileFlags |= D3DCOMPILE_SKIP_VALIDATION; compileFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; break; case Rhi::IShaderLanguage::OptimizationLevel::LOW: compileFlags |= D3DCOMPILE_SKIP_VALIDATION; compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL0; break; case Rhi::IShaderLanguage::OptimizationLevel::MEDIUM: compileFlags |= D3DCOMPILE_SKIP_VALIDATION; compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL1; break; case Rhi::IShaderLanguage::OptimizationLevel::HIGH: compileFlags |= D3DCOMPILE_SKIP_VALIDATION; compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL2; break; case Rhi::IShaderLanguage::OptimizationLevel::ULTRA: compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL3; break; } // Compile ID3DBlob* d3dBlob = nullptr; ID3DBlob* errorD3dBlob = nullptr; if (FAILED(D3DCompile(sourceCode, strlen(sourceCode), nullptr, nullptr, nullptr, entryPoint ? entryPoint : "main", shaderModel, compileFlags, 0, &d3dBlob, &errorD3dBlob))) { if (nullptr != errorD3dBlob) { if (context.getLog().print(Rhi::ILog::Type::CRITICAL, sourceCode, __FILE__, static_cast<uint32_t>(__LINE__), static_cast<char*>(errorD3dBlob->GetBufferPointer()))) { DEBUG_BREAK; } errorD3dBlob->Release(); } return nullptr; } if (nullptr != errorD3dBlob) { errorD3dBlob->Release(); } // Done return d3dBlob; } void handleDeviceLost(const Direct3D11Rhi& direct3D11Rhi, HRESULT result) { // If the device was removed either by a disconnection or a driver upgrade, we must recreate all device resources if (DXGI_ERROR_DEVICE_REMOVED == result || DXGI_ERROR_DEVICE_RESET == result) { if (DXGI_ERROR_DEVICE_REMOVED == result) { result = direct3D11Rhi.getD3D11Device()->GetDeviceRemovedReason(); } RHI_LOG(direct3D11Rhi.getContext(), CRITICAL, "Direct3D 11 device lost on present: Reason code 0x%08X", static_cast<unsigned int>(result)) // TODO(co) Add device lost handling if needed. Probably more complex to recreate all device resources. } } //[-------------------------------------------------------] //[ Direct3D11Rhi/Mapping.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 mapping */ class Mapping final { //[-------------------------------------------------------] //[ Public static methods ] //[-------------------------------------------------------] public: //[-------------------------------------------------------] //[ Rhi::VertexAttributeFormat and semantic ] //[-------------------------------------------------------] /** * @brief * "Rhi::VertexAttributeFormat" to Direct3D 11 format * * @param[in] vertexAttributeFormat * "Rhi::VertexAttributeFormat" to map * * @return * Direct3D 11 format */ [[nodiscard]] static DXGI_FORMAT getDirect3D11Format(Rhi::VertexAttributeFormat vertexAttributeFormat) { static constexpr DXGI_FORMAT MAPPING[] = { DXGI_FORMAT_R32_FLOAT, // Rhi::VertexAttributeFormat::FLOAT_1 DXGI_FORMAT_R32G32_FLOAT, // Rhi::VertexAttributeFormat::FLOAT_2 DXGI_FORMAT_R32G32B32_FLOAT, // Rhi::VertexAttributeFormat::FLOAT_3 DXGI_FORMAT_R32G32B32A32_FLOAT, // Rhi::VertexAttributeFormat::FLOAT_4 DXGI_FORMAT_R8G8B8A8_UNORM, // Rhi::VertexAttributeFormat::R8G8B8A8_UNORM DXGI_FORMAT_R8G8B8A8_UINT, // Rhi::VertexAttributeFormat::R8G8B8A8_UINT DXGI_FORMAT_R16G16_SINT, // Rhi::VertexAttributeFormat::SHORT_2 DXGI_FORMAT_R16G16B16A16_SINT, // Rhi::VertexAttributeFormat::SHORT_4 DXGI_FORMAT_R32_UINT // Rhi::VertexAttributeFormat::UINT_1 }; return MAPPING[static_cast<int>(vertexAttributeFormat)]; } //[-------------------------------------------------------] //[ Rhi::BufferUsage ] //[-------------------------------------------------------] /** * @brief * "Rhi::BufferUsage" to Direct3D 11 usage and CPU access flags * * @param[in] bufferUsage * "Rhi::BufferUsage" to map * @param[out] cpuAccessFlags * Receives the CPU access flags * * @return * Direct3D 11 usage */ [[nodiscard]] static D3D11_USAGE getDirect3D11UsageAndCPUAccessFlags(Rhi::BufferUsage bufferUsage, uint32_t& cpuAccessFlags) { // Direct3D 11 only supports a subset of the OpenGL usage indications // -> See "D3D11_USAGE enumeration "-documentation at http://msdn.microsoft.com/en-us/library/windows/desktop/ff476259%28v=vs.85%29.aspx switch (bufferUsage) { case Rhi::BufferUsage::STREAM_DRAW: case Rhi::BufferUsage::STREAM_COPY: case Rhi::BufferUsage::STATIC_DRAW: case Rhi::BufferUsage::STATIC_COPY: cpuAccessFlags = 0; return D3D11_USAGE_IMMUTABLE; case Rhi::BufferUsage::STREAM_READ: case Rhi::BufferUsage::STATIC_READ: cpuAccessFlags = D3D11_CPU_ACCESS_READ; return D3D11_USAGE_STAGING; case Rhi::BufferUsage::DYNAMIC_DRAW: case Rhi::BufferUsage::DYNAMIC_COPY: cpuAccessFlags = D3D11_CPU_ACCESS_WRITE; return D3D11_USAGE_DYNAMIC; default: case Rhi::BufferUsage::DYNAMIC_READ: cpuAccessFlags = 0; return D3D11_USAGE_DEFAULT; } } //[-------------------------------------------------------] //[ Rhi::IndexBufferFormat ] //[-------------------------------------------------------] /** * @brief * "Rhi::IndexBufferFormat" to Direct3D 11 format * * @param[in] indexBufferFormat * "Rhi::IndexBufferFormat" to map * * @return * Direct3D 11 format */ [[nodiscard]] static DXGI_FORMAT getDirect3D11Format(Rhi::IndexBufferFormat::Enum indexBufferFormat) { static constexpr DXGI_FORMAT MAPPING[] = { DXGI_FORMAT_R32_UINT, // Rhi::IndexBufferFormat::UNSIGNED_CHAR - One byte per element, uint8_t (may not be supported by each API) - Not supported by Direct3D 11 DXGI_FORMAT_R16_UINT, // Rhi::IndexBufferFormat::UNSIGNED_SHORT - Two bytes per element, uint16_t DXGI_FORMAT_R32_UINT // Rhi::IndexBufferFormat::UNSIGNED_INT - Four bytes per element, uint32_t (may not be supported by each API) }; return MAPPING[indexBufferFormat]; } //[-------------------------------------------------------] //[ Rhi::TextureFormat ] //[-------------------------------------------------------] /** * @brief * "Rhi::TextureFormat" to Direct3D 11 format * * @param[in] textureFormat * "Rhi::TextureFormat" to map * * @return * Direct3D 11 format * * @remarks * For textures used as depth stencil render target, Direct3D 11 format handling becomes a little bit more complex due to * the offered flexibility. For example the abstract texture format "Rhi::TextureFormat::D32_FLOAT" translates into * - Direct3D 11 resource format is "DXGI_FORMAT_R32_TYPELESS" * - Direct3D 11 shader resource view format is "DXGI_FORMAT_R32_FLOAT" * - Direct3D 11 depth stencil view format is "DXGI_FORMAT_D32_FLOAT" */ [[nodiscard]] static DXGI_FORMAT getDirect3D11Format(Rhi::TextureFormat::Enum textureFormat) { static constexpr DXGI_FORMAT MAPPING[] = { DXGI_FORMAT_R8_UNORM, // Rhi::TextureFormat::R8 - 8-bit pixel format, all bits red DXGI_FORMAT_B8G8R8X8_UNORM, // Rhi::TextureFormat::R8G8B8 - 24-bit pixel format, 8 bits for red, green and blue DXGI_FORMAT_R8G8B8A8_UNORM, // Rhi::TextureFormat::R8G8B8A8 - 32-bit pixel format, 8 bits for red, green, blue and alpha DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, // Rhi::TextureFormat::R8G8B8A8_SRGB - 32-bit pixel format, 8 bits for red, green, blue and alpha; sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_B8G8R8A8_UNORM, // Rhi::TextureFormat::B8G8R8A8 - 32-bit pixel format, 8 bits for red, green, blue and alpha DXGI_FORMAT_R11G11B10_FLOAT, // Rhi::TextureFormat::R11G11B10F - 32-bit float format using 11 bits the red and green channel, 10 bits the blue channel; red and green channels have a 6 bits mantissa and a 5 bits exponent and blue has a 5 bits mantissa and 5 bits exponent DXGI_FORMAT_R16G16B16A16_FLOAT, // Rhi::TextureFormat::R16G16B16A16F - 64-bit float format using 16 bits for the each channel (red, green, blue, alpha) DXGI_FORMAT_R32G32B32A32_FLOAT, // Rhi::TextureFormat::R32G32B32A32F - 128-bit float format using 32 bits for the each channel (red, green, blue, alpha) DXGI_FORMAT_BC1_UNORM, // Rhi::TextureFormat::BC1 - DXT1 compression (known as BC1 in DirectX 10, RGB compression: 8:1, 8 bytes per block) DXGI_FORMAT_BC1_UNORM_SRGB, // Rhi::TextureFormat::BC1_SRGB - DXT1 compression (known as BC1 in DirectX 10, RGB compression: 8:1, 8 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_BC2_UNORM, // Rhi::TextureFormat::BC2 - DXT3 compression (known as BC2 in DirectX 10, RGBA compression: 4:1, 16 bytes per block) DXGI_FORMAT_BC2_UNORM_SRGB, // Rhi::TextureFormat::BC2_SRGB - DXT3 compression (known as BC2 in DirectX 10, RGBA compression: 4:1, 16 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_BC3_UNORM, // Rhi::TextureFormat::BC3 - DXT5 compression (known as BC3 in DirectX 10, RGBA compression: 4:1, 16 bytes per block) DXGI_FORMAT_BC3_UNORM_SRGB, // Rhi::TextureFormat::BC3_SRGB - DXT5 compression (known as BC3 in DirectX 10, RGBA compression: 4:1, 16 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_BC4_UNORM, // Rhi::TextureFormat::BC4 - 1 component texture compression (also known as 3DC+/ATI1N, known as BC4 in DirectX 10, 8 bytes per block) DXGI_FORMAT_BC5_UNORM, // Rhi::TextureFormat::BC5 - 2 component texture compression (luminance & alpha compression 4:1 -> normal map compression, also known as 3DC/ATI2N, known as BC5 in DirectX 10, 16 bytes per block) DXGI_FORMAT_UNKNOWN, // Rhi::TextureFormat::ETC1 - 3 component texture compression meant for mobile devices - not supported in Direct3D 11 DXGI_FORMAT_R16_UNORM, // Rhi::TextureFormat::R16_UNORM - 16-bit unsigned-normalized-integer format that supports 16 bits for the red channel DXGI_FORMAT_R32_UINT, // Rhi::TextureFormat::R32_UINT - 32-bit unsigned integer format DXGI_FORMAT_R32_FLOAT, // Rhi::TextureFormat::R32_FLOAT - 32-bit float format DXGI_FORMAT_D32_FLOAT, // Rhi::TextureFormat::D32_FLOAT - 32-bit float depth format DXGI_FORMAT_R16G16_SNORM, // Rhi::TextureFormat::R16G16_SNORM - A two-component, 32-bit signed-normalized-integer format that supports 16 bits for the red channel and 16 bits for the green channel DXGI_FORMAT_R16G16_FLOAT, // Rhi::TextureFormat::R16G16_FLOAT - A two-component, 32-bit floating-point format that supports 16 bits for the red channel and 16 bits for the green channel DXGI_FORMAT_UNKNOWN // Rhi::TextureFormat::UNKNOWN - Unknown }; return MAPPING[textureFormat]; } static DXGI_FORMAT getDirect3D11ResourceFormat(Rhi::TextureFormat::Enum textureFormat) { // Only "Rhi::TextureFormat::D32_FLOAT" has to be handled in a different way static constexpr DXGI_FORMAT MAPPING[] = { DXGI_FORMAT_R8_UNORM, // Rhi::TextureFormat::R8 - 8-bit pixel format, all bits red DXGI_FORMAT_B8G8R8X8_UNORM, // Rhi::TextureFormat::R8G8B8 - 24-bit pixel format, 8 bits for red, green and blue DXGI_FORMAT_R8G8B8A8_UNORM, // Rhi::TextureFormat::R8G8B8A8 - 32-bit pixel format, 8 bits for red, green, blue and alpha DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, // Rhi::TextureFormat::R8G8B8A8_SRGB - 32-bit pixel format, 8 bits for red, green, blue and alpha; sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_B8G8R8A8_UNORM, // Rhi::TextureFormat::B8G8R8A8 - 32-bit pixel format, 8 bits for red, green, blue and alpha DXGI_FORMAT_R11G11B10_FLOAT, // Rhi::TextureFormat::R11G11B10F - 32-bit float format using 11 bits the red and green channel, 10 bits the blue channel; red and green channels have a 6 bits mantissa and a 5 bits exponent and blue has a 5 bits mantissa and 5 bits exponent DXGI_FORMAT_R16G16B16A16_FLOAT, // Rhi::TextureFormat::R16G16B16A16F - 64-bit float format using 16 bits for the each channel (red, green, blue, alpha) DXGI_FORMAT_R32G32B32A32_FLOAT, // Rhi::TextureFormat::R32G32B32A32F - 128-bit float format using 32 bits for the each channel (red, green, blue, alpha) DXGI_FORMAT_BC1_UNORM, // Rhi::TextureFormat::BC1 - DXT1 compression (known as BC1 in DirectX 10, RGB compression: 8:1, 8 bytes per block) DXGI_FORMAT_BC1_UNORM_SRGB, // Rhi::TextureFormat::BC1_SRGB - DXT1 compression (known as BC1 in DirectX 10, RGB compression: 8:1, 8 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_BC2_UNORM, // Rhi::TextureFormat::BC2 - DXT3 compression (known as BC2 in DirectX 10, RGBA compression: 4:1, 16 bytes per block) DXGI_FORMAT_BC2_UNORM_SRGB, // Rhi::TextureFormat::BC2_SRGB - DXT3 compression (known as BC2 in DirectX 10, RGBA compression: 4:1, 16 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_BC3_UNORM, // Rhi::TextureFormat::BC3 - DXT5 compression (known as BC3 in DirectX 10, RGBA compression: 4:1, 16 bytes per block) DXGI_FORMAT_BC3_UNORM_SRGB, // Rhi::TextureFormat::BC3_SRGB - DXT5 compression (known as BC3 in DirectX 10, RGBA compression: 4:1, 16 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_BC4_UNORM, // Rhi::TextureFormat::BC4 - 1 component texture compression (also known as 3DC+/ATI1N, known as BC4 in DirectX 10, 8 bytes per block) DXGI_FORMAT_BC5_UNORM, // Rhi::TextureFormat::BC5 - 2 component texture compression (luminance & alpha compression 4:1 -> normal map compression, also known as 3DC/ATI2N, known as BC5 in DirectX 10, 16 bytes per block) DXGI_FORMAT_UNKNOWN, // Rhi::TextureFormat::ETC1 - 3 component texture compression meant for mobile devices - not supported in Direct3D 11 DXGI_FORMAT_R16_UNORM, // Rhi::TextureFormat::R16_UNORM - 16-bit unsigned-normalized-integer format that supports 16 bits for the red channel DXGI_FORMAT_R32_UINT, // Rhi::TextureFormat::R32_UINT - 32-bit unsigned integer format DXGI_FORMAT_R32_FLOAT, // Rhi::TextureFormat::R32_FLOAT - 32-bit float format DXGI_FORMAT_R32_TYPELESS, // Rhi::TextureFormat::D32_FLOAT - 32-bit float depth format DXGI_FORMAT_R16G16_SNORM, // Rhi::TextureFormat::R16G16_SNORM - A two-component, 32-bit signed-normalized-integer format that supports 16 bits for the red channel and 16 bits for the green channel DXGI_FORMAT_R16G16_FLOAT, // Rhi::TextureFormat::R16G16_FLOAT - A two-component, 32-bit floating-point format that supports 16 bits for the red channel and 16 bits for the green channel DXGI_FORMAT_UNKNOWN // Rhi::TextureFormat::UNKNOWN - Unknown }; return MAPPING[textureFormat]; } [[nodiscard]] static DXGI_FORMAT getDirect3D11ShaderResourceViewFormat(Rhi::TextureFormat::Enum textureFormat) { // Only "Rhi::TextureFormat::D32_FLOAT" has to be handled in a different way static constexpr DXGI_FORMAT MAPPING[] = { DXGI_FORMAT_R8_UNORM, // Rhi::TextureFormat::R8 - 8-bit pixel format, all bits red DXGI_FORMAT_B8G8R8X8_UNORM, // Rhi::TextureFormat::R8G8B8 - 24-bit pixel format, 8 bits for red, green and blue DXGI_FORMAT_R8G8B8A8_UNORM, // Rhi::TextureFormat::R8G8B8A8 - 32-bit pixel format, 8 bits for red, green, blue and alpha DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, // Rhi::TextureFormat::R8G8B8A8_SRGB - 32-bit pixel format, 8 bits for red, green, blue and alpha; sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_B8G8R8A8_UNORM, // Rhi::TextureFormat::B8G8R8A8 - 32-bit pixel format, 8 bits for red, green, blue and alpha DXGI_FORMAT_R11G11B10_FLOAT, // Rhi::TextureFormat::R11G11B10F - 32-bit float format using 11 bits the red and green channel, 10 bits the blue channel; red and green channels have a 6 bits mantissa and a 5 bits exponent and blue has a 5 bits mantissa and 5 bits exponent DXGI_FORMAT_R16G16B16A16_FLOAT, // Rhi::TextureFormat::R16G16B16A16F - 64-bit float format using 16 bits for the each channel (red, green, blue, alpha) DXGI_FORMAT_R32G32B32A32_FLOAT, // Rhi::TextureFormat::R32G32B32A32F - 128-bit float format using 32 bits for the each channel (red, green, blue, alpha) DXGI_FORMAT_BC1_UNORM, // Rhi::TextureFormat::BC1 - DXT1 compression (known as BC1 in DirectX 10, RGB compression: 8:1, 8 bytes per block) DXGI_FORMAT_BC1_UNORM_SRGB, // Rhi::TextureFormat::BC1_SRGB - DXT1 compression (known as BC1 in DirectX 10, RGB compression: 8:1, 8 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_BC2_UNORM, // Rhi::TextureFormat::BC2 - DXT3 compression (known as BC2 in DirectX 10, RGBA compression: 4:1, 16 bytes per block) DXGI_FORMAT_BC2_UNORM_SRGB, // Rhi::TextureFormat::BC2_SRGB - DXT3 compression (known as BC2 in DirectX 10, RGBA compression: 4:1, 16 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_BC3_UNORM, // Rhi::TextureFormat::BC3 - DXT5 compression (known as BC3 in DirectX 10, RGBA compression: 4:1, 16 bytes per block) DXGI_FORMAT_BC3_UNORM_SRGB, // Rhi::TextureFormat::BC3_SRGB - DXT5 compression (known as BC3 in DirectX 10, RGBA compression: 4:1, 16 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear DXGI_FORMAT_BC4_UNORM, // Rhi::TextureFormat::BC4 - 1 component texture compression (also known as 3DC+/ATI1N, known as BC4 in DirectX 10, 8 bytes per block) DXGI_FORMAT_BC5_UNORM, // Rhi::TextureFormat::BC5 - 2 component texture compression (luminance & alpha compression 4:1 -> normal map compression, also known as 3DC/ATI2N, known as BC5 in DirectX 10, 16 bytes per block) DXGI_FORMAT_UNKNOWN, // Rhi::TextureFormat::ETC1 - 3 component texture compression meant for mobile devices - not supported in Direct3D 11 DXGI_FORMAT_R16_UNORM, // Rhi::TextureFormat::R16_UNORM - 16-bit unsigned-normalized-integer format that supports 16 bits for the red channel DXGI_FORMAT_R32_UINT, // Rhi::TextureFormat::R32_UINT - 32-bit unsigned integer format DXGI_FORMAT_R32_FLOAT, // Rhi::TextureFormat::R32_FLOAT - 32-bit float format DXGI_FORMAT_R32_FLOAT, // Rhi::TextureFormat::D32_FLOAT - 32-bit float depth format DXGI_FORMAT_R16G16_SNORM, // Rhi::TextureFormat::R16G16_SNORM - A two-component, 32-bit signed-normalized-integer format that supports 16 bits for the red channel and 16 bits for the green channel DXGI_FORMAT_R16G16_FLOAT, // Rhi::TextureFormat::R16G16_FLOAT - A two-component, 32-bit floating-point format that supports 16 bits for the red channel and 16 bits for the green channel DXGI_FORMAT_UNKNOWN // Rhi::TextureFormat::UNKNOWN - Unknown }; return MAPPING[textureFormat]; } }; //[-------------------------------------------------------] //[ Direct3D11Rhi/ResourceGroup.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 resource group class */ class ResourceGroup final : public Rhi::IResourceGroup { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] rhi * Owner RHI instance * @param[in] numberOfResources * Number of resources, having no resources is invalid * @param[in] resources * At least "numberOfResources" resource pointers, must be valid, the resource group will keep a reference to the resources * @param[in] samplerStates * If not a null pointer at least "numberOfResources" sampler state pointers, must be valid if there's at least one texture resource, the resource group will keep a reference to the sampler states */ ResourceGroup(Rhi::IRhi& rhi, uint32_t numberOfResources, Rhi::IResource** resources, Rhi::ISamplerState** samplerStates RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IResourceGroup(rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mNumberOfResources(numberOfResources), mResources(RHI_MALLOC_TYPED(rhi.getContext(), Rhi::IResource*, mNumberOfResources)), mSamplerStates(nullptr) { // Process all resources and add our reference to the RHI resource for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex, ++resources) { Rhi::IResource* resource = *resources; RHI_ASSERT(rhi.getContext(), nullptr != resource, "Invalid Direct3D 11 resource") mResources[resourceIndex] = resource; resource->addReference(); } if (nullptr != samplerStates) { mSamplerStates = RHI_MALLOC_TYPED(rhi.getContext(), Rhi::ISamplerState*, mNumberOfResources); for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex, ++resources) { Rhi::ISamplerState* samplerState = mSamplerStates[resourceIndex] = samplerStates[resourceIndex]; if (nullptr != samplerState) { samplerState->addReference(); } } } } /** * @brief * Destructor */ virtual ~ResourceGroup() override { // Remove our reference from the RHI resources const Rhi::Context& context = getRhi().getContext(); if (nullptr != mSamplerStates) { for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex) { Rhi::ISamplerState* samplerState = mSamplerStates[resourceIndex]; if (nullptr != samplerState) { samplerState->releaseReference(); } } RHI_FREE(context, mSamplerStates); } for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex) { mResources[resourceIndex]->releaseReference(); } RHI_FREE(context, mResources); } /** * @brief * Return the number of resources this resource group groups together * * @return * The number of resources this resource group groups together */ [[nodiscard]] inline uint32_t getNumberOfResources() const { return mNumberOfResources; } /** * @brief * Return the RHI resources * * @return * The RHI resources, don't release or destroy the returned pointer */ [[nodiscard]] inline Rhi::IResource** getResources() const { return mResources; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), ResourceGroup, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit ResourceGroup(const ResourceGroup& source) = delete; ResourceGroup& operator =(const ResourceGroup& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: uint32_t mNumberOfResources; ///< Number of resources this resource group groups together Rhi::IResource** mResources; ///< RHI resources, we keep a reference to it Rhi::ISamplerState** mSamplerStates; ///< Sampler states, we keep a reference to it }; //[-------------------------------------------------------] //[ Direct3D11Rhi/RootSignature.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 root signature ("pipeline layout" in Vulkan terminology) class */ class RootSignature final : public Rhi::IRootSignature { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] rootSignature * Root signature to use */ RootSignature(Direct3D11Rhi& direct3D11Rhi, const Rhi::RootSignature& rootSignature RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IRootSignature(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mRootSignature(rootSignature) { const Rhi::Context& context = direct3D11Rhi.getContext(); { // Copy the parameter data const uint32_t numberOfParameters = mRootSignature.numberOfParameters; if (numberOfParameters > 0) { mRootSignature.parameters = RHI_MALLOC_TYPED(context, Rhi::RootParameter, numberOfParameters); Rhi::RootParameter* destinationRootParameters = const_cast<Rhi::RootParameter*>(mRootSignature.parameters); memcpy(destinationRootParameters, rootSignature.parameters, sizeof(Rhi::RootParameter) * numberOfParameters); // Copy the descriptor table data for (uint32_t i = 0; i < numberOfParameters; ++i) { Rhi::RootParameter& destinationRootParameter = destinationRootParameters[i]; const Rhi::RootParameter& sourceRootParameter = rootSignature.parameters[i]; if (Rhi::RootParameterType::DESCRIPTOR_TABLE == destinationRootParameter.parameterType) { const uint32_t numberOfDescriptorRanges = destinationRootParameter.descriptorTable.numberOfDescriptorRanges; destinationRootParameter.descriptorTable.descriptorRanges = reinterpret_cast<uintptr_t>(RHI_MALLOC_TYPED(context, Rhi::DescriptorRange, numberOfDescriptorRanges)); memcpy(reinterpret_cast<Rhi::DescriptorRange*>(destinationRootParameter.descriptorTable.descriptorRanges), reinterpret_cast<const Rhi::DescriptorRange*>(sourceRootParameter.descriptorTable.descriptorRanges), sizeof(Rhi::DescriptorRange) * numberOfDescriptorRanges); } } } } { // Copy the static sampler data const uint32_t numberOfStaticSamplers = mRootSignature.numberOfStaticSamplers; if (numberOfStaticSamplers > 0) { mRootSignature.staticSamplers = RHI_MALLOC_TYPED(context, Rhi::StaticSampler, numberOfStaticSamplers); memcpy(const_cast<Rhi::StaticSampler*>(mRootSignature.staticSamplers), rootSignature.staticSamplers, sizeof(Rhi::StaticSampler) * numberOfStaticSamplers); } } } /** * @brief * Destructor */ virtual ~RootSignature() override { const Rhi::Context& context = getRhi().getContext(); if (nullptr != mRootSignature.parameters) { for (uint32_t i = 0; i < mRootSignature.numberOfParameters; ++i) { const Rhi::RootParameter& rootParameter = mRootSignature.parameters[i]; if (Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType) { RHI_FREE(context, reinterpret_cast<Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges)); } } RHI_FREE(context, const_cast<Rhi::RootParameter*>(mRootSignature.parameters)); } RHI_FREE(context, const_cast<Rhi::StaticSampler*>(mRootSignature.staticSamplers)); } /** * @brief * Return the root signature data * * @return * The root signature data */ [[nodiscard]] inline const Rhi::RootSignature& getRootSignature() const { return mRootSignature; } //[-------------------------------------------------------] //[ Public virtual Rhi::IRootSignature methods ] //[-------------------------------------------------------] public: [[nodiscard]] virtual Rhi::IResourceGroup* createResourceGroup([[maybe_unused]] uint32_t rootParameterIndex, uint32_t numberOfResources, Rhi::IResource** resources, Rhi::ISamplerState** samplerStates = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Rhi::IRhi& rhi = getRhi(); // Sanity checks RHI_ASSERT(rhi.getContext(), rootParameterIndex < mRootSignature.numberOfParameters, "The Direct3D 11 root parameter index is out-of-bounds") RHI_ASSERT(rhi.getContext(), numberOfResources > 0, "The number of Direct3D 11 resources must not be zero") RHI_ASSERT(rhi.getContext(), nullptr != resources, "The Direct3D 11 resource pointers must be valid") // Create resource group return RHI_NEW(rhi.getContext(), ResourceGroup)(rhi, numberOfResources, resources, samplerStates RHI_RESOURCE_DEBUG_PASS_PARAMETER); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), RootSignature, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit RootSignature(const RootSignature& source) = delete; RootSignature& operator =(const RootSignature& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::RootSignature mRootSignature; }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Buffer/VertexBuffer.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 vertex buffer object (VBO, "array buffer" in OpenGL terminology) class */ class VertexBuffer final : public Rhi::IVertexBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] numberOfBytes * Number of bytes within the vertex buffer, must be valid * @param[in] data * Vertex buffer data, can be a null pointer (empty buffer) * @param[in] bufferFlags * Buffer flags, see "Rhi::BufferFlag" * @param[in] bufferUsage * Indication of the buffer usage */ VertexBuffer(Direct3D11Rhi& direct3D11Rhi, uint32_t numberOfBytes, const void* data, uint32_t bufferFlags, Rhi::BufferUsage bufferUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IVertexBuffer(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11Buffer(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // Direct3D 11 buffer description D3D11_BUFFER_DESC d3d11BufferDesc; d3d11BufferDesc.ByteWidth = numberOfBytes; d3d11BufferDesc.Usage = Mapping::getDirect3D11UsageAndCPUAccessFlags(bufferUsage, d3d11BufferDesc.CPUAccessFlags); d3d11BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; //d3d11BufferDesc.CPUAccessFlags = <filled above>; d3d11BufferDesc.MiscFlags = 0; d3d11BufferDesc.StructureByteStride = 0; // Set bind flags // -> Using a structured vertex buffer would be handy inside shader source codes, sadly this isn't possible with Direct3D 11 and will result in the following error: // D3D11 ERROR: ID3D11Device::CreateBuffer: Buffers created with D3D11_RESOURCE_MISC_BUFFER_STRUCTURED cannot specify any of the following listed bind flags. The following BindFlags bits (0x9) are set: D3D11_BIND_VERTEX_BUFFER (1), D3D11_BIND_INDEX_BUFFER (0), D3D11_BIND_CONSTANT_BUFFER (0), D3D11_BIND_STREAM_OUTPUT (0), D3D11_BIND_RENDER_TARGET (0), or D3D11_BIND_DEPTH_STENCIL (0). [ STATE_CREATION ERROR #68: CREATEBUFFER_INVALIDMISCFLAGS] if (bufferFlags & Rhi::IndirectBufferFlag::SHADER_RESOURCE) { d3d11BufferDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; d3d11BufferDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS; } if (bufferFlags & Rhi::IndirectBufferFlag::UNORDERED_ACCESS) { d3d11BufferDesc.Usage = D3D11_USAGE_DEFAULT; d3d11BufferDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; d3d11BufferDesc.CPUAccessFlags = 0; d3d11BufferDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS; } // Data given? if (nullptr != data) { // Direct3D 11 subresource data D3D11_SUBRESOURCE_DATA d3d11SubresourceData; d3d11SubresourceData.pSysMem = data; d3d11SubresourceData.SysMemPitch = 0; d3d11SubresourceData.SysMemSlicePitch = 0; // Create the Direct3D 11 vertex buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, &d3d11SubresourceData, &mD3D11Buffer)) } else { // Create the Direct3D 11 vertex buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, nullptr, &mD3D11Buffer)) } // Create the Direct3D 11 shader resource view instance if (bufferFlags & Rhi::IndirectBufferFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = DXGI_FORMAT_R32_TYPELESS; d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX; d3d11ShaderResourceViewDesc.BufferEx.NumElements = numberOfBytes / sizeof(uint32_t); d3d11ShaderResourceViewDesc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW; // Create the Direct3D 11 shader resource view instance // -> HLSL usage example: "ByteAddressBuffer InputVertexBuffer : register(t0);" FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Buffer, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (bufferFlags & Rhi::IndirectBufferFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = DXGI_FORMAT_R32_TYPELESS; d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; d3d11UnorderedAccessViewDesc.Buffer.NumElements = numberOfBytes / sizeof(uint32_t); d3d11UnorderedAccessViewDesc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW; // Create the Direct3D 11 unordered access view instance // -> HLSL usage example: "RWByteAddressBuffer OutputVertexBuffer : register(u0);" FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Buffer, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "VBO", 6) // 6 = "VBO: " including terminating zero if (nullptr != mD3D11Buffer) { FAILED_DEBUG_BREAK(mD3D11Buffer->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~VertexBuffer() override { if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); mD3D11ShaderResourceView = nullptr; } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); mD3D11UnorderedAccessView = nullptr; } if (nullptr != mD3D11Buffer) { mD3D11Buffer->Release(); } } /** * @brief * Return the Direct3D vertex buffer instance * * @return * The Direct3D vertex buffer instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Buffer* getD3D11Buffer() const { return mD3D11Buffer; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), VertexBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit VertexBuffer(const VertexBuffer& source) = delete; VertexBuffer& operator =(const VertexBuffer& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11Buffer* mD3D11Buffer; ///< Direct3D vertex buffer instance, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Buffer/IndexBuffer.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 index buffer object (IBO, "element array buffer" in OpenGL terminology) class */ class IndexBuffer final : public Rhi::IIndexBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 rhi instance * @param[in] numberOfBytes * Number of bytes within the index buffer, must be valid * @param[in] data * Index buffer data, can be a null pointer (empty buffer) * @param[in] bufferFlags * Buffer flags, see "Rhi::BufferFlag" * @param[in] bufferUsage * Indication of the buffer usage * @param[in] indexBufferFormat * Index buffer data format */ IndexBuffer(Direct3D11Rhi& direct3D11Rhi, uint32_t numberOfBytes, const void* data, uint32_t bufferFlags, Rhi::BufferUsage bufferUsage, Rhi::IndexBufferFormat::Enum indexBufferFormat RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IIndexBuffer(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11Buffer(nullptr), mDXGIFormat(DXGI_FORMAT_UNKNOWN), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // "Rhi::IndexBufferFormat::UnsignedChar" is not supported by Direct3D 11 // -> See "Input assembler index buffer resources" ("D3D11_FORMAT_SUPPORT_IA_INDEX_BUFFER"): https://msdn.microsoft.com/en-us/library/windows/desktop/ff471325%28v=vs.85%29.aspx RHI_ASSERT(direct3D11Rhi.getContext(), Rhi::IndexBufferFormat::UNSIGNED_CHAR != indexBufferFormat, "\"Rhi::IndexBufferFormat::UNSIGNED_CHAR\" is not supported by Direct3D 11") // Set the DXGI format mDXGIFormat = Mapping::getDirect3D11Format(indexBufferFormat); // Direct3D 11 buffer description D3D11_BUFFER_DESC d3d11BufferDesc; d3d11BufferDesc.ByteWidth = numberOfBytes; d3d11BufferDesc.Usage = Mapping::getDirect3D11UsageAndCPUAccessFlags(bufferUsage, d3d11BufferDesc.CPUAccessFlags); d3d11BufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; //d3d11BufferDesc.CPUAccessFlags = <filled above>; d3d11BufferDesc.MiscFlags = 0; d3d11BufferDesc.StructureByteStride = 0; // Set bind flags if (bufferFlags & Rhi::IndirectBufferFlag::SHADER_RESOURCE) { d3d11BufferDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if (bufferFlags & Rhi::IndirectBufferFlag::UNORDERED_ACCESS) { d3d11BufferDesc.Usage = D3D11_USAGE_DEFAULT; d3d11BufferDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; d3d11BufferDesc.CPUAccessFlags = 0; } // Data given? if (nullptr != data) { // Direct3D 11 subresource data D3D11_SUBRESOURCE_DATA d3d11SubresourceData; d3d11SubresourceData.pSysMem = data; d3d11SubresourceData.SysMemPitch = 0; d3d11SubresourceData.SysMemSlicePitch = 0; // Create the Direct3D 11 index buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, &d3d11SubresourceData, &mD3D11Buffer)) } else { // Create the Direct3D 11 index buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, nullptr, &mD3D11Buffer)) } // Create the Direct3D 11 shader resource view instance if (bufferFlags & Rhi::IndirectBufferFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = mDXGIFormat; d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; d3d11ShaderResourceViewDesc.Buffer.ElementWidth = numberOfBytes / Rhi::IndexBufferFormat::getNumberOfBytesPerElement(indexBufferFormat); // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Buffer, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (bufferFlags & Rhi::IndirectBufferFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = mDXGIFormat; d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; d3d11UnorderedAccessViewDesc.Buffer.NumElements = numberOfBytes / Rhi::IndexBufferFormat::getNumberOfBytesPerElement(indexBufferFormat); // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Buffer, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "IBO", 6) // 6 = "IBO: " including terminating zero if (nullptr != mD3D11Buffer) { FAILED_DEBUG_BREAK(mD3D11Buffer->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~IndexBuffer() override { if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); mD3D11ShaderResourceView = nullptr; } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); mD3D11UnorderedAccessView = nullptr; } if (nullptr != mD3D11Buffer) { mD3D11Buffer->Release(); } } /** * @brief * Return the Direct3D index buffer instance * * @return * The Direct3D index buffer instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Buffer* getD3D11Buffer() const { return mD3D11Buffer; } /** * @brief * Return the DXGI index buffer data format * * @return * The DXGI index buffer data format */ [[nodiscard]] inline DXGI_FORMAT getDXGIFormat() const { return mDXGIFormat; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), IndexBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit IndexBuffer(const IndexBuffer& source) = delete; IndexBuffer& operator =(const IndexBuffer& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11Buffer* mD3D11Buffer; ///< Direct3D index buffer instance, can be a null pointer DXGI_FORMAT mDXGIFormat; ///< DXGI index buffer data format ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Buffer/VertexArray.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 vertex array class */ class VertexArray final : public Rhi::IVertexArray { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] vertexAttributes * Vertex attributes ("vertex declaration" in Direct3D 9 terminology, "input layout" in Direct3D 10 & 11 terminology) * @param[in] numberOfVertexBuffers * Number of vertex buffers, having zero vertex buffers is valid * @param[in] vertexBuffers * At least numberOfVertexBuffers instances of vertex array vertex buffers, can be a null pointer in case there are zero vertex buffers, the data is internally copied and you have to free your memory if you no longer need it * @param[in] indexBuffer * Optional index buffer to use, can be a null pointer, the vertex array instance keeps a reference to the index buffer * @param[in] id * The unique compact vertex array ID */ VertexArray(Direct3D11Rhi& direct3D11Rhi, const Rhi::VertexAttributes& vertexAttributes, uint32_t numberOfVertexBuffers, const Rhi::VertexArrayVertexBuffer* vertexBuffers, IndexBuffer* indexBuffer, uint16_t id RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IVertexArray(direct3D11Rhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER), mIndexBuffer(indexBuffer), mNumberOfSlots(numberOfVertexBuffers), mD3D11Buffers(nullptr), mStrides(nullptr), mOffsets(nullptr), mVertexBuffers(nullptr) { // Add a reference to the given index buffer if (nullptr != mIndexBuffer) { mIndexBuffer->addReference(); } // Add a reference to the used vertex buffers if (mNumberOfSlots > 0) { const Rhi::Context& context = direct3D11Rhi.getContext(); mD3D11Buffers = RHI_MALLOC_TYPED(context, ID3D11Buffer*, mNumberOfSlots); mStrides = RHI_MALLOC_TYPED(context, UINT, mNumberOfSlots); mOffsets = RHI_MALLOC_TYPED(context, UINT, mNumberOfSlots); memset(mOffsets, 0, sizeof(UINT) * mNumberOfSlots); // Vertex buffer offset is not supported by OpenGL, so our RHI implementation doesn't support it either, set everything to zero mVertexBuffers = RHI_MALLOC_TYPED(context, VertexBuffer*, mNumberOfSlots); { // Loop through all vertex buffers ID3D11Buffer** currentD3D11Buffer = mD3D11Buffers; VertexBuffer** currentVertexBuffer = mVertexBuffers; const Rhi::VertexArrayVertexBuffer* vertexBufferEnd = vertexBuffers + mNumberOfSlots; for (const Rhi::VertexArrayVertexBuffer* vertexBuffer = vertexBuffers; vertexBuffer < vertexBufferEnd; ++vertexBuffer, ++currentD3D11Buffer, ++currentVertexBuffer) { // TODO(co) Add security check: Is the given resource one of the currently used RHI? *currentVertexBuffer = static_cast<VertexBuffer*>(vertexBuffer->vertexBuffer); *currentD3D11Buffer = (*currentVertexBuffer)->getD3D11Buffer(); (*currentVertexBuffer)->addReference(); } } { // Gather slot related data const Rhi::VertexAttribute* attribute = vertexAttributes.attributes; const Rhi::VertexAttribute* attributesEnd = attribute + vertexAttributes.numberOfAttributes; for (; attribute < attributesEnd; ++attribute) { mStrides[attribute->inputSlot] = attribute->strideInBytes; } } } } /** * @brief * Destructor */ virtual ~VertexArray() override { // Release the index buffer reference if (nullptr != mIndexBuffer) { mIndexBuffer->releaseReference(); } // Cleanup Direct3D 11 input slot data Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); const Rhi::Context& context = direct3D11Rhi.getContext(); if (mNumberOfSlots > 0) { RHI_FREE(context, mD3D11Buffers); RHI_FREE(context, mStrides); RHI_FREE(context, mOffsets); } // Release the reference to the used vertex buffers if (nullptr != mVertexBuffers) { // Release references VertexBuffer** vertexBuffersEnd = mVertexBuffers + mNumberOfSlots; for (VertexBuffer** vertexBuffer = mVertexBuffers; vertexBuffer < vertexBuffersEnd; ++vertexBuffer) { (*vertexBuffer)->releaseReference(); } // Cleanup RHI_FREE(context, mVertexBuffers); } // Free the unique compact vertex array ID direct3D11Rhi.VertexArrayMakeId.DestroyID(getId()); } /** * @brief * Set the Direct3D 11 vertex declaration and stream source * * @param[in] d3d11DeviceContext * The Direct3D 11 device context instance */ void setDirect3DIASetInputLayoutAndStreamSource(ID3D11DeviceContext& d3d11DeviceContext) const { // Set the Direct3D 11 vertex buffers if (nullptr != mD3D11Buffers) { { // TODO(co) Work in progress: Compute shader writing into vertex buffer: "D3D11 WARNING: ID3D11DeviceContext::IASetVertexBuffers: Resource being set to Vertex Buffer slot 0 is still bound on output! Forcing to NULL. [ STATE_SETTING WARNING #1: DEVICE_IASETVERTEXBUFFERS_HAZARD]" ID3D11UnorderedAccessView* d3d11UnorderedAccessView = nullptr; d3d11DeviceContext.CSSetUnorderedAccessViews(2, 1, &d3d11UnorderedAccessView, nullptr); } // Just make a single API call d3d11DeviceContext.IASetVertexBuffers(0, mNumberOfSlots, mD3D11Buffers, mStrides, mOffsets); } else { // Direct3D 10 says: "D3D10: INFO: ID3D10Device::IASetVertexBuffers: Since NumBuffers is 0, the operation effectively does nothing. This is probably not intentional, nor is the most efficient way to achieve this operation. Avoid calling the routine at all. [ STATE_SETTING INFO #240: DEVICE_IASETVERTEXBUFFERS_BUFFERS_EMPTY ]" // -> Direct3D 11 does not give us this message, but it's probably still no good thing to do } // Set the used index buffer // -> In case of no index buffer we don't set null indices, there's not really a point in it if (nullptr != mIndexBuffer) { { // TODO(co) Work in progress: Compute shader writing into vertex buffer: "D3D11 WARNING: ID3D11DeviceContext::IASetIndexBuffer: Resource being set to Index Buffer is still bound on output! Forcing to NULL. [ STATE_SETTING WARNING #2: DEVICE_IASETINDEXBUFFER_HAZARD]" ID3D11UnorderedAccessView* d3d11UnorderedAccessView = nullptr; d3d11DeviceContext.CSSetUnorderedAccessViews(1, 1, &d3d11UnorderedAccessView, nullptr); } // Set the Direct3D 11 indices d3d11DeviceContext.IASetIndexBuffer(mIndexBuffer->getD3D11Buffer(), static_cast<DXGI_FORMAT>(mIndexBuffer->getDXGIFormat()), 0); } } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), VertexArray, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit VertexArray(const VertexArray& source) = delete; VertexArray& operator =(const VertexArray& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: IndexBuffer* mIndexBuffer; ///< Optional index buffer to use, can be a null pointer, the vertex array instance keeps a reference to the index buffer // Direct3D 11 input slots UINT mNumberOfSlots; ///< Number of used Direct3D 11 input slots ID3D11Buffer** mD3D11Buffers; ///< Direct3D 11 vertex buffers, if "mD3D11InputLayout" is no null pointer this is no null pointer as well UINT* mStrides; ///< Strides in bytes, if "mD3D11Buffers" is no null pointer this is no null pointer as well UINT* mOffsets; ///< Offsets in bytes, if "mD3D11Buffers" is no null pointer this is no null pointer as well // For proper vertex buffer reference counter behaviour VertexBuffer** mVertexBuffers; ///< Vertex buffers (we keep a reference to it) used by this vertex array, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Buffer/TextureBuffer.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 texture buffer object (TBO) class */ class TextureBuffer final : public Rhi::ITextureBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] numberOfBytes * Number of bytes within the texture buffer, must be valid * @param[in] data * Texture buffer data, can be a null pointer (empty buffer) * @param[in] bufferFlags * Buffer flags, see "Rhi::BufferFlag" * @param[in] bufferUsage * Indication of the buffer usage * @param[in] textureFormat * Texture buffer data format */ TextureBuffer(Direct3D11Rhi& direct3D11Rhi, uint32_t numberOfBytes, const void* data, uint32_t bufferFlags, Rhi::BufferUsage bufferUsage, Rhi::TextureFormat::Enum textureFormat RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITextureBuffer(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11Buffer(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), (numberOfBytes % Rhi::TextureFormat::getNumberOfBytesPerElement(textureFormat)) == 0, "The Direct3D 11 texture buffer size must be a multiple of the selected texture format bytes per texel") { // Buffer part // Direct3D 11 buffer description D3D11_BUFFER_DESC d3d11BufferDesc; d3d11BufferDesc.ByteWidth = numberOfBytes; d3d11BufferDesc.Usage = Mapping::getDirect3D11UsageAndCPUAccessFlags(bufferUsage, d3d11BufferDesc.CPUAccessFlags); d3d11BufferDesc.BindFlags = 0; //d3d11BufferDesc.CPUAccessFlags = <filled above>; d3d11BufferDesc.MiscFlags = 0; d3d11BufferDesc.StructureByteStride = 0; // Set bind flags if (bufferFlags & Rhi::BufferFlag::SHADER_RESOURCE) { d3d11BufferDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if (bufferFlags & Rhi::BufferFlag::UNORDERED_ACCESS) { d3d11BufferDesc.Usage = D3D11_USAGE_DEFAULT; d3d11BufferDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; d3d11BufferDesc.CPUAccessFlags = 0; } // Data given? if (nullptr != data) { // Direct3D 11 subresource data D3D11_SUBRESOURCE_DATA d3d11SubresourceData; d3d11SubresourceData.pSysMem = data; d3d11SubresourceData.SysMemPitch = 0; d3d11SubresourceData.SysMemSlicePitch = 0; // Create the Direct3D 11 constant buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, &d3d11SubresourceData, &mD3D11Buffer)) } else { // Create the Direct3D 11 constant buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, nullptr, &mD3D11Buffer)) } } // Create the Direct3D 11 shader resource view instance if (bufferFlags & Rhi::BufferFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = Mapping::getDirect3D11ResourceFormat(textureFormat); d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; d3d11ShaderResourceViewDesc.Buffer.ElementWidth = numberOfBytes / Rhi::TextureFormat::getNumberOfBytesPerElement(textureFormat); // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Buffer, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (bufferFlags & Rhi::BufferFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; d3d11UnorderedAccessViewDesc.Buffer.NumElements = numberOfBytes / Rhi::TextureFormat::getNumberOfBytesPerElement(textureFormat); // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Buffer, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "TBO", 6) // 6 = "TBO: " including terminating zero if (nullptr != mD3D11Buffer) { FAILED_DEBUG_BREAK(mD3D11Buffer->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~TextureBuffer() override { // Release the used resources if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); mD3D11ShaderResourceView = nullptr; } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); mD3D11UnorderedAccessView = nullptr; } if (nullptr != mD3D11Buffer) { mD3D11Buffer->Release(); mD3D11Buffer = nullptr; } } /** * @brief * Return the Direct3D texture buffer instance * * @return * The Direct3D texture buffer instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Buffer* getD3D11Buffer() const { return mD3D11Buffer; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TextureBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TextureBuffer(const TextureBuffer& source) = delete; TextureBuffer& operator =(const TextureBuffer& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11Buffer* mD3D11Buffer; ///< Direct3D texture buffer instance, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Buffer/StructuredBuffer.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 structured buffer object (SBO) class */ class StructuredBuffer final : public Rhi::IStructuredBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] numberOfBytes * Number of bytes within the structured buffer, must be valid * @param[in] data * Structured buffer data, can be a null pointer (empty buffer) * @param[in] bufferFlags * Buffer flags, see "Rhi::BufferFlag" * @param[in] bufferUsage * Indication of the buffer usage * @param[in] numberOfStructureBytes * Number of structure bytes */ StructuredBuffer(Direct3D11Rhi& direct3D11Rhi, uint32_t numberOfBytes, const void* data, uint32_t bufferFlags, Rhi::BufferUsage bufferUsage, uint32_t numberOfStructureBytes RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IStructuredBuffer(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11Buffer(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), (numberOfBytes % numberOfStructureBytes) == 0, "The Direct3D 11 structured buffer size must be a multiple of the given number of structure bytes") RHI_ASSERT(direct3D11Rhi.getContext(), (numberOfBytes % (sizeof(float) * 4)) == 0, "Performance: The Direct3D 11 structured buffer should be aligned to a 128-bit stride, see \"Understanding Structured Buffer Performance\" by Evan Hart, posted Apr 17 2015 at 11:33AM - https://developer.nvidia.com/content/understanding-structured-buffer-performance") { // Buffer part // Direct3D 11 buffer description D3D11_BUFFER_DESC d3d11BufferDesc; d3d11BufferDesc.ByteWidth = numberOfBytes; d3d11BufferDesc.Usage = Mapping::getDirect3D11UsageAndCPUAccessFlags(bufferUsage, d3d11BufferDesc.CPUAccessFlags); d3d11BufferDesc.BindFlags = 0; //d3d11BufferDesc.CPUAccessFlags = <filled above>; d3d11BufferDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED; d3d11BufferDesc.StructureByteStride = numberOfStructureBytes; // Set bind flags if (bufferFlags & Rhi::BufferFlag::SHADER_RESOURCE) { d3d11BufferDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if (bufferFlags & Rhi::BufferFlag::UNORDERED_ACCESS) { d3d11BufferDesc.Usage = D3D11_USAGE_DEFAULT; d3d11BufferDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; d3d11BufferDesc.CPUAccessFlags = 0; } // Data given? if (nullptr != data) { // Direct3D 11 subresource data D3D11_SUBRESOURCE_DATA d3d11SubresourceData; d3d11SubresourceData.pSysMem = data; d3d11SubresourceData.SysMemPitch = 0; d3d11SubresourceData.SysMemSlicePitch = 0; // Create the Direct3D 11 constant buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, &d3d11SubresourceData, &mD3D11Buffer)) } else { // Create the Direct3D 11 constant buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, nullptr, &mD3D11Buffer)) } } // Create the Direct3D 11 shader resource view instance if (bufferFlags & Rhi::BufferFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = DXGI_FORMAT_UNKNOWN; d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; d3d11ShaderResourceViewDesc.Buffer.ElementWidth = numberOfBytes / numberOfStructureBytes; // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Buffer, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (bufferFlags & Rhi::BufferFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description // -> There's no support for Direct3D 11 style "append" ("D3D11_BUFFER_UAV_FLAG_APPEND") or "counter" ("D3D11_BUFFER_UAV_FLAG_COUNTER") structured buffer by intent since neither OpenGL nor Vulkan support something similar, use atomic shader intrinsics instead D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = DXGI_FORMAT_UNKNOWN; d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; d3d11UnorderedAccessViewDesc.Buffer.NumElements = numberOfBytes / numberOfStructureBytes; // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Buffer, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "SBO", 6) // 6 = "SBO: " including terminating zero if (nullptr != mD3D11Buffer) { FAILED_DEBUG_BREAK(mD3D11Buffer->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~StructuredBuffer() override { // Release the used resources if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); mD3D11ShaderResourceView = nullptr; } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); mD3D11UnorderedAccessView = nullptr; } if (nullptr != mD3D11Buffer) { mD3D11Buffer->Release(); mD3D11Buffer = nullptr; } } /** * @brief * Return the Direct3D structured buffer instance * * @return * The Direct3D structured buffer instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Buffer* getD3D11Buffer() const { return mD3D11Buffer; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), StructuredBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit StructuredBuffer(const StructuredBuffer& source) = delete; StructuredBuffer& operator =(const StructuredBuffer& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11Buffer* mD3D11Buffer; ///< Direct3D structured buffer instance, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Buffer/IndirectBuffer.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 indirect buffer object class */ class IndirectBuffer final : public Rhi::IIndirectBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] numberOfBytes * Number of bytes within the indirect buffer, must be valid * @param[in] data * Indirect buffer data, can be a null pointer (empty buffer) * @param[in] indirectBufferFlags * Indirect buffer flags, see "Rhi::IndirectBufferFlag" * @param[in] bufferUsage * Indication of the buffer usage */ IndirectBuffer(Direct3D11Rhi& direct3D11Rhi, uint32_t numberOfBytes, const void* data, uint32_t indirectBufferFlags, Rhi::BufferUsage bufferUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IIndirectBuffer(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11Buffer(nullptr), mStagingD3D11Buffer(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) != 0 || (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_INDEXED_ARGUMENTS) != 0, "Invalid Direct3D 11 flags, indirect buffer element type specification \"DRAW_ARGUMENTS\" or \"DRAW_INDEXED_ARGUMENTS\" is missing") RHI_ASSERT(direct3D11Rhi.getContext(), !((indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) != 0 && (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_INDEXED_ARGUMENTS) != 0), "Invalid Direct3D 11 flags, indirect buffer element type specification \"DRAW_ARGUMENTS\" or \"DRAW_INDEXED_ARGUMENTS\" must be set, but not both at one and the same time") RHI_ASSERT(direct3D11Rhi.getContext(), (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) == 0 || (numberOfBytes % sizeof(Rhi::DrawArguments)) == 0, "Direct3D 11 indirect buffer element type flags specification is \"DRAW_ARGUMENTS\" but the given number of bytes don't align to this") RHI_ASSERT(direct3D11Rhi.getContext(), (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_INDEXED_ARGUMENTS) == 0 || (numberOfBytes % sizeof(Rhi::DrawIndexedArguments)) == 0, "Direct3D 11 indirect buffer element type flags specification is \"DRAW_INDEXED_ARGUMENTS\" but the given number of bytes don't align to this") { // Buffer part: Indirect buffers can't be mapped in Direct3D 11 since considered to be exclusively written by GPU // Direct3D 11 buffer description D3D11_BUFFER_DESC d3d11BufferDesc; d3d11BufferDesc.ByteWidth = numberOfBytes; d3d11BufferDesc.Usage = D3D11_USAGE_DEFAULT; d3d11BufferDesc.BindFlags = 0; d3d11BufferDesc.CPUAccessFlags = 0; d3d11BufferDesc.MiscFlags = D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS; d3d11BufferDesc.StructureByteStride = 0; // Set bind flags // -> Using a structured indirect buffer would be handy inside shader source codes, sadly this isn't possible with Direct3D 11 and will result in the following error: // "D3D11 ERROR: ID3D11Device::CreateBuffer: A resource cannot created with both D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS and D3D11_RESOURCE_MISC_BUFFER_STRUCTURED. [ STATE_CREATION ERROR #68: CREATEBUFFER_INVALIDMISCFLAGS]" // d3d11BufferDesc.MiscFlags |= D3D11_RESOURCE_MISC_BUFFER_STRUCTURED; // d3d11BufferDesc.StructureByteStride = (flags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) ? sizeof(Rhi::DrawArguments) : sizeof(Rhi::DrawIndexedArguments); if (indirectBufferFlags & Rhi::IndirectBufferFlag::SHADER_RESOURCE) { d3d11BufferDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if (indirectBufferFlags & Rhi::IndirectBufferFlag::UNORDERED_ACCESS) { d3d11BufferDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } // Data given? if (nullptr != data) { // Direct3D 11 subresource data D3D11_SUBRESOURCE_DATA d3d11SubresourceData; d3d11SubresourceData.pSysMem = data; d3d11SubresourceData.SysMemPitch = 0; d3d11SubresourceData.SysMemSlicePitch = 0; // Create the Direct3D 11 indirect buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, &d3d11SubresourceData, &mD3D11Buffer)) } else { // Create the Direct3D 11 indirect buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, nullptr, &mD3D11Buffer)) } } // Staging buffer part: Indirect buffers can't be mapped in Direct3D 11 since considered to be exclusively written by GPU, so we need an additional staging buffer to send dynamic data from CPU to GPU if (Rhi::BufferUsage::STATIC_DRAW != bufferUsage && Rhi::BufferUsage::STATIC_READ != bufferUsage && Rhi::BufferUsage::STATIC_COPY != bufferUsage) { // Direct3D 11 buffer description D3D11_BUFFER_DESC d3d11BufferDesc; d3d11BufferDesc.ByteWidth = numberOfBytes; d3d11BufferDesc.Usage = Mapping::getDirect3D11UsageAndCPUAccessFlags(bufferUsage, d3d11BufferDesc.CPUAccessFlags); d3d11BufferDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; //d3d11BufferDesc.CPUAccessFlags = <filled above>; d3d11BufferDesc.MiscFlags = 0; d3d11BufferDesc.StructureByteStride = 0; // Data given? if (nullptr != data) { // Direct3D 11 subresource data D3D11_SUBRESOURCE_DATA d3d11SubresourceData; d3d11SubresourceData.pSysMem = data; d3d11SubresourceData.SysMemPitch = 0; d3d11SubresourceData.SysMemSlicePitch = 0; // Create the Direct3D 11 indirect buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, &d3d11SubresourceData, &mStagingD3D11Buffer)) } else { // Create the Direct3D 11 indirect buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, nullptr, &mStagingD3D11Buffer)) } } // Create the Direct3D 11 shader resource view instance if (indirectBufferFlags & Rhi::IndirectBufferFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = DXGI_FORMAT_R32_UINT; d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; d3d11ShaderResourceViewDesc.Buffer.ElementWidth = numberOfBytes / sizeof(uint32_t); // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Buffer, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (indirectBufferFlags & Rhi::IndirectBufferFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = DXGI_FORMAT_R32_UINT; d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; d3d11UnorderedAccessViewDesc.Buffer.NumElements = numberOfBytes / sizeof(uint32_t); // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Buffer, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "IndirectBufferObject", 23) // 23 = "IndirectBufferObject: " including terminating zero if (nullptr != mD3D11Buffer) { FAILED_DEBUG_BREAK(mD3D11Buffer->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mStagingD3D11Buffer) { FAILED_DEBUG_BREAK(mStagingD3D11Buffer->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~IndirectBuffer() override { // Release the used resources if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); mD3D11ShaderResourceView = nullptr; } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); mD3D11UnorderedAccessView = nullptr; } if (nullptr != mD3D11Buffer) { mD3D11Buffer->Release(); mD3D11Buffer = nullptr; } if (nullptr != mStagingD3D11Buffer) { mStagingD3D11Buffer->Release(); mStagingD3D11Buffer = nullptr; } } /** * @brief * Return the Direct3D indirect buffer instance * * @return * The Direct3D indirect buffer instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Buffer* getD3D11Buffer() const { return mD3D11Buffer; } [[nodiscard]] inline ID3D11Buffer* getStagingD3D11Buffer() const { return mStagingD3D11Buffer; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), IndirectBuffer, this); } //[-------------------------------------------------------] //[ Public virtual Rhi::IIndirectBuffer methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const uint8_t* getEmulationData() const override { return nullptr; } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit IndirectBuffer(const IndirectBuffer& source) = delete; IndirectBuffer& operator =(const IndirectBuffer& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11Buffer* mD3D11Buffer; ///< Direct3D indirect buffer instance, can be a null pointer ID3D11Buffer* mStagingD3D11Buffer; ///< Staging Direct3D indirect buffer instance, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Buffer/UniformBuffer.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 uniform buffer object (UBO, "constant buffer" in Direct3D terminology) interface */ class UniformBuffer final : public Rhi::IUniformBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] numberOfBytes * Number of bytes within the uniform buffer, must be valid * @param[in] data * Uniform buffer data, can be a null pointer (empty buffer) * @param[in] bufferUsage * Indication of the buffer usage */ UniformBuffer(Direct3D11Rhi& direct3D11Rhi, uint32_t numberOfBytes, const void* data, Rhi::BufferUsage bufferUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) : Rhi::IUniformBuffer(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11Buffer(nullptr) { { // Sanity check // Check the given number of bytes, if we don't do this we might get told // "... the ByteWidth (value = <x>) must be a multiple of 16 and be less than or equal to 65536" // by Direct3D 11 const uint32_t leftOverBytes = (numberOfBytes % 16); if (0 != leftOverBytes) { // Fix the byte alignment, no assert because other RHI implementations have another alignment (DirectX 12 e.g. 256) numberOfBytes += 16 - (numberOfBytes % 16); } } // Direct3D 11 buffer description D3D11_BUFFER_DESC d3d11BufferDesc; d3d11BufferDesc.ByteWidth = numberOfBytes; d3d11BufferDesc.Usage = Mapping::getDirect3D11UsageAndCPUAccessFlags(bufferUsage, d3d11BufferDesc.CPUAccessFlags); d3d11BufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; //d3d11BufferDescd3d11BufferDesc.CPUAccessFlags = <filled above>; d3d11BufferDesc.MiscFlags = 0; d3d11BufferDesc.StructureByteStride = 0; // Data given? if (nullptr != data) { // Direct3D 11 subresource data D3D11_SUBRESOURCE_DATA d3d11SubresourceData; d3d11SubresourceData.pSysMem = data; d3d11SubresourceData.SysMemPitch = 0; d3d11SubresourceData.SysMemSlicePitch = 0; // Create the Direct3D 11 constant buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, &d3d11SubresourceData, &mD3D11Buffer)) } else { // Create the Direct3D 11 constant buffer FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBuffer(&d3d11BufferDesc, nullptr, &mD3D11Buffer)) } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11Buffer) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "UBO", 6) // 6 = "UBO: " including terminating zero FAILED_DEBUG_BREAK(mD3D11Buffer->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~UniformBuffer() override { // Release the Direct3D 11 constant buffer if (nullptr != mD3D11Buffer) { mD3D11Buffer->Release(); } } /** * @brief * Return the Direct3D 11 constant buffer instance * * @return * The Direct3D 11 constant buffer instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Buffer* getD3D11Buffer() const { return mD3D11Buffer; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), UniformBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit UniformBuffer(const UniformBuffer& source) = delete; UniformBuffer& operator =(const UniformBuffer& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11Buffer* mD3D11Buffer; ///< Direct3D 11 constant buffer instance, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Buffer/BufferManager.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 buffer manager interface */ class BufferManager final : public Rhi::IBufferManager { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance */ inline explicit BufferManager(Direct3D11Rhi& direct3D11Rhi) : IBufferManager(direct3D11Rhi) {} /** * @brief * Destructor */ inline virtual ~BufferManager() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IBufferManager methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual Rhi::IVertexBuffer* createVertexBuffer(uint32_t numberOfBytes, const void* data = nullptr, uint32_t bufferFlags = 0, Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), VertexBuffer)(direct3D11Rhi, numberOfBytes, data, bufferFlags, bufferUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IIndexBuffer* createIndexBuffer(uint32_t numberOfBytes, const void* data = nullptr, uint32_t bufferFlags = 0, Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW, Rhi::IndexBufferFormat::Enum indexBufferFormat = Rhi::IndexBufferFormat::UNSIGNED_SHORT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), IndexBuffer)(direct3D11Rhi, numberOfBytes, data, bufferFlags, bufferUsage, indexBufferFormat RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IVertexArray* createVertexArray(const Rhi::VertexAttributes& vertexAttributes, uint32_t numberOfVertexBuffers, const Rhi::VertexArrayVertexBuffer* vertexBuffers, Rhi::IIndexBuffer* indexBuffer = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity checks #ifdef RHI_DEBUG { const Rhi::VertexArrayVertexBuffer* vertexBufferEnd = vertexBuffers + numberOfVertexBuffers; for (const Rhi::VertexArrayVertexBuffer* vertexBuffer = vertexBuffers; vertexBuffer < vertexBufferEnd; ++vertexBuffer) { RHI_ASSERT(direct3D11Rhi.getContext(), &direct3D11Rhi == &vertexBuffer->vertexBuffer->getRhi(), "Direct3D 11 error: The given vertex buffer resource is owned by another RHI instance") } } #endif RHI_ASSERT(direct3D11Rhi.getContext(), nullptr == indexBuffer || &direct3D11Rhi == &indexBuffer->getRhi(), "Direct3D 11 error: The given index buffer resource is owned by another RHI instance") // Create vertex array uint16_t id = 0; if (direct3D11Rhi.VertexArrayMakeId.CreateID(id)) { return RHI_NEW(direct3D11Rhi.getContext(), VertexArray)(direct3D11Rhi, vertexAttributes, numberOfVertexBuffers, vertexBuffers, static_cast<IndexBuffer*>(indexBuffer), id RHI_RESOURCE_DEBUG_PASS_PARAMETER); } // Error: Ensure a correct reference counter behaviour const Rhi::VertexArrayVertexBuffer* vertexBufferEnd = vertexBuffers + numberOfVertexBuffers; for (const Rhi::VertexArrayVertexBuffer* vertexBuffer = vertexBuffers; vertexBuffer < vertexBufferEnd; ++vertexBuffer) { vertexBuffer->vertexBuffer->addReference(); vertexBuffer->vertexBuffer->releaseReference(); } if (nullptr != indexBuffer) { indexBuffer->addReference(); indexBuffer->releaseReference(); } return nullptr; } [[nodiscard]] inline virtual Rhi::ITextureBuffer* createTextureBuffer(uint32_t numberOfBytes, const void* data = nullptr, uint32_t bufferFlags = Rhi::BufferFlag::SHADER_RESOURCE, Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW, Rhi::TextureFormat::Enum textureFormat = Rhi::TextureFormat::R32G32B32A32F RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), TextureBuffer)(direct3D11Rhi, numberOfBytes, data, bufferFlags, bufferUsage, textureFormat RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IStructuredBuffer* createStructuredBuffer(uint32_t numberOfBytes, const void* data, uint32_t bufferFlags, Rhi::BufferUsage bufferUsage, uint32_t numberOfStructureBytes RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), StructuredBuffer)(direct3D11Rhi, numberOfBytes, data, bufferFlags, bufferUsage, numberOfStructureBytes RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IIndirectBuffer* createIndirectBuffer(uint32_t numberOfBytes, const void* data = nullptr, uint32_t indirectBufferFlags = 0, Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), IndirectBuffer)(direct3D11Rhi, numberOfBytes, data, indirectBufferFlags, bufferUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IUniformBuffer* createUniformBuffer(uint32_t numberOfBytes, const void* data = nullptr, Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Don't remove this reminder comment block: There are no buffer flags by intent since an uniform buffer can't be used for unordered access and as a consequence an uniform buffer must always used as shader resource to not be pointless // -> "Bind a buffer as a constant buffer to a shader stage; this flag may NOT be combined with any other bind flag." - https://docs.microsoft.com/en-us/windows/desktop/api/d3d11/ne-d3d11-d3d11_bind_flag // RHI_ASSERT(direct3D11Rhi.getContext(), (bufferFlags & Rhi::BufferFlag::UNORDERED_ACCESS) == 0, "Invalid Direct3D 11 buffer flags, uniform buffer can't be used for unordered access") // RHI_ASSERT(direct3D11Rhi.getContext(), (bufferFlags & Rhi::BufferFlag::SHADER_RESOURCE) != 0, "Invalid Direct3D 11 buffer flags, uniform buffer must be used as shader resource") // Create the uniform buffer return RHI_NEW(direct3D11Rhi.getContext(), UniformBuffer)(direct3D11Rhi, numberOfBytes, data, bufferUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), BufferManager, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit BufferManager(const BufferManager& source) = delete; BufferManager& operator =(const BufferManager& source) = delete; }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Texture/Texture1D.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 1D texture class */ class Texture1D final : public Rhi::ITexture1D { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] width * Texture width, must be >0 * @param[in] textureFormat * Texture format * @param[in] data * Texture data, can be a null pointer * @param[in] textureFlags * Texture flags, see "Rhi::TextureFlag::Enum" * @param[in] textureUsage * Indication of the texture usage */ Texture1D(Direct3D11Rhi& direct3D11Rhi, uint32_t width, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags, Rhi::TextureUsage textureUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITexture1D(direct3D11Rhi, width RHI_RESOURCE_DEBUG_PASS_PARAMETER), mTextureFormat(textureFormat), mD3D11Texture1D(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), 0 == (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS) || nullptr != data, "Invalid Direct3D 11 texture parameters") RHI_ASSERT(direct3D11Rhi.getContext(), (textureFlags & Rhi::TextureFlag::RENDER_TARGET) == 0 || nullptr == data, "Direct3D 11 render target textures can't be filled using provided data") // Calculate the number of mipmaps const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS); const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS)); RHI_ASSERT(direct3D11Rhi.getContext(), Rhi::TextureUsage::IMMUTABLE != textureUsage || !generateMipmaps, "Direct3D 11 immutable texture usage can't be combined with automatic mipmap generation") const uint32_t numberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? getNumberOfMipmaps(width) : 1; const bool isDepthFormat = Rhi::TextureFormat::isDepth(textureFormat); // Direct3D 11 1D texture description D3D11_TEXTURE1D_DESC d3d11Texture1DDesc; d3d11Texture1DDesc.Width = width; d3d11Texture1DDesc.MipLevels = numberOfMipmaps; d3d11Texture1DDesc.ArraySize = 1; d3d11Texture1DDesc.Format = Mapping::getDirect3D11ResourceFormat(textureFormat); d3d11Texture1DDesc.Usage = static_cast<D3D11_USAGE>(textureUsage); // These constants directly map to Direct3D constants, do not change them d3d11Texture1DDesc.BindFlags = 0; d3d11Texture1DDesc.CPUAccessFlags = (Rhi::TextureUsage::DYNAMIC == textureUsage) ? D3D11_CPU_ACCESS_WRITE : 0u; d3d11Texture1DDesc.MiscFlags = (generateMipmaps && !isDepthFormat) ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0u; // Set bind flags if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { d3d11Texture1DDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if ((textureFlags & Rhi::TextureFlag::RENDER_TARGET) || generateMipmaps) { if (isDepthFormat) { d3d11Texture1DDesc.BindFlags |= D3D11_BIND_DEPTH_STENCIL; } else { d3d11Texture1DDesc.BindFlags |= D3D11_BIND_RENDER_TARGET; } } if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { d3d11Texture1DDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } // Create the Direct3D 11 1D texture instance: Did the user provided us with any texture data? if (nullptr != data) { // We don't want dynamic allocations, so we limit the maximum number of mipmaps and hence are able to use the efficient C runtime stack static constexpr uint32_t MAXIMUM_NUMBER_OF_MIPMAPS = 15; // A 16384x16384 texture has 15 mipmaps RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMipmaps <= MAXIMUM_NUMBER_OF_MIPMAPS, "Invalid Direct3D 11 number of mipmaps") D3D11_SUBRESOURCE_DATA d3d11SubresourceData[MAXIMUM_NUMBER_OF_MIPMAPS]; // Did the user provided data containing mipmaps from 0-n down to 1x1 linearly in memory? if (dataContainsMipmaps) { // Upload all mipmaps for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { // Upload the current mipmap D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next mipmap and ensure the size is always at least 1 // -> If the data doesn't contain mipmaps, we don't need to care about this in here data = static_cast<const uint8_t*>(data) + currentD3d11SubresourceData.SysMemPitch; width = getHalfSize(width); } } else { // The user only provided us with the base texture, no mipmaps // -> When uploading data, we still need to upload the whole mipmap chain, so provide dummy data for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); } } FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture1D(&d3d11Texture1DDesc, d3d11SubresourceData, &mD3D11Texture1D)) } else { // The user did not provide us with texture data FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture1D(&d3d11Texture1DDesc, nullptr, &mD3D11Texture1D)) } // Create requested views if (nullptr != mD3D11Texture1D) { // Create the Direct3D 11 shader resource view instance if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; d3d11ShaderResourceViewDesc.Texture1D.MipLevels = numberOfMipmaps; // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Texture1D, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE1D; // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Texture1D, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } } // Let Direct3D 11 generate the mipmaps for us automatically, if necessary if (nullptr != data && generateMipmaps) { direct3D11Rhi.generateAsynchronousDeferredMipmaps(*this, *mD3D11ShaderResourceView); } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "1D texture", 13) // 13 = "1D texture: " including terminating zero if (nullptr != mD3D11Texture1D) { FAILED_DEBUG_BREAK(mD3D11Texture1D->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~Texture1D() override { if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); } if (nullptr != mD3D11Texture1D) { mD3D11Texture1D->Release(); } } /** * @brief * Return the texture format * * @return * The texture format */ [[nodiscard]] inline Rhi::TextureFormat::Enum getTextureFormat() const { return mTextureFormat; } /** * @brief * Return the Direct3D texture 1D resource instance * * @return * The Direct3D texture 1D resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Texture1D* getD3D11Texture1D() const { return mD3D11Texture1D; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Public virtual Rhi::IResource methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual void* getInternalResourceHandle() const override { return mD3D11Texture1D; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture1D, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture1D(const Texture1D& source) = delete; Texture1D& operator =(const Texture1D& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::TextureFormat::Enum mTextureFormat; ID3D11Texture1D* mD3D11Texture1D; ///< Direct3D 11 texture 1D resource, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Texture/Texture1DArray.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 1D array texture class */ class Texture1DArray final : public Rhi::ITexture1DArray { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] width * Texture width, must be >0 * @param[in] numberOfSlices * Number of slices, must be >0 * @param[in] textureFormat * Texture format * @param[in] data * Texture data, can be a null pointer * @param[in] textureFlags * Texture flags, see "Rhi::TextureFlag::Enum" * @param[in] textureUsage * Indication of the texture usage */ Texture1DArray(Direct3D11Rhi& direct3D11Rhi, uint32_t width, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags, Rhi::TextureUsage textureUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITexture1DArray(direct3D11Rhi, width, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER), mTextureFormat(textureFormat), mD3D11Texture1D(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), (textureFlags & Rhi::TextureFlag::RENDER_TARGET) == 0 || nullptr == data, "Direct3D 11 render target textures can't be filled using provided data") // Calculate the number of mipmaps const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS); const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS)); RHI_ASSERT(direct3D11Rhi.getContext(), Rhi::TextureUsage::IMMUTABLE != textureUsage || !generateMipmaps, "Direct3D 11 immutable texture usage can't be combined with automatic mipmap generation") const uint32_t numberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? getNumberOfMipmaps(width) : 1; const bool isDepthFormat = Rhi::TextureFormat::isDepth(textureFormat); // Direct3D 11 1D array texture description D3D11_TEXTURE1D_DESC d3d11Texture1DDesc; d3d11Texture1DDesc.Width = width; d3d11Texture1DDesc.MipLevels = numberOfMipmaps; d3d11Texture1DDesc.ArraySize = numberOfSlices; d3d11Texture1DDesc.Format = Mapping::getDirect3D11ResourceFormat(textureFormat); d3d11Texture1DDesc.Usage = static_cast<D3D11_USAGE>(textureUsage); // These constants directly map to Direct3D constants, do not change them d3d11Texture1DDesc.BindFlags = 0; d3d11Texture1DDesc.CPUAccessFlags = (Rhi::TextureUsage::DYNAMIC == textureUsage) ? D3D11_CPU_ACCESS_WRITE : 0u; d3d11Texture1DDesc.MiscFlags = (generateMipmaps && !isDepthFormat) ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0u; // Set bind flags if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { d3d11Texture1DDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if ((textureFlags & Rhi::TextureFlag::RENDER_TARGET) || generateMipmaps) { if (isDepthFormat) { d3d11Texture1DDesc.BindFlags |= D3D11_BIND_DEPTH_STENCIL; } else { d3d11Texture1DDesc.BindFlags |= D3D11_BIND_RENDER_TARGET; } } if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { d3d11Texture1DDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } // Create the Direct3D 11 1D texture instance: Did the user provided us with any texture data? if (nullptr != data) { // We don't want dynamic allocations, so we limit the maximum number of mipmaps and hence are able to use the efficient C runtime stack static constexpr uint32_t MAXIMUM_NUMBER_OF_MIPMAPS = 15; // A 16384x16384 texture has 15 mipmaps static constexpr uint32_t MAXIMUM_NUMBER_OF_SLICES = 10; const Rhi::Context& context = direct3D11Rhi.getContext(); RHI_ASSERT(context, numberOfMipmaps <= MAXIMUM_NUMBER_OF_MIPMAPS, "Invalid Direct3D 11 number of mipmaps") D3D11_SUBRESOURCE_DATA d3d11SubresourceDataStack[MAXIMUM_NUMBER_OF_SLICES * MAXIMUM_NUMBER_OF_MIPMAPS]; D3D11_SUBRESOURCE_DATA* d3d11SubresourceData = (numberOfSlices <= MAXIMUM_NUMBER_OF_SLICES) ? d3d11SubresourceDataStack : RHI_MALLOC_TYPED(context, D3D11_SUBRESOURCE_DATA, numberOfSlices); // Did the user provided data containing mipmaps from 0-n down to 1x1 linearly in memory? if (dataContainsMipmaps) { // Data layout // - Direct3D 11 wants: DDS files are organized in slice-major order, like this: // Slice0: Mip0, Mip1, Mip2, etc. // Slice1: Mip0, Mip1, Mip2, etc. // etc. // - The RHI provides: CRN and KTX files are organized in mip-major order, like this: // Mip0: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5 // Mip1: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5 // etc. // Upload all mipmaps for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, 1); for (uint32_t arraySlice = 0; arraySlice < numberOfSlices; ++arraySlice) { // Upload the current slice D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[arraySlice * numberOfMipmaps + mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = numberOfBytesPerRow; currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next slice // -> If the data doesn't contain mipmaps, we don't need to care about this in here data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice; } // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); } } else { // The user only provided us with the base texture, no mipmaps // -> When uploading data, we still need to upload the whole mipmap chain, so provide dummy data for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { const void* currentData = data; const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, 1); for (uint32_t arraySlice = 0; arraySlice < numberOfSlices; ++arraySlice) { D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[arraySlice * numberOfMipmaps + mipmap]; currentD3d11SubresourceData.pSysMem = currentData; currentD3d11SubresourceData.SysMemPitch = numberOfBytesPerRow; currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next slice currentData = static_cast<const uint8_t*>(currentData) + numberOfBytesPerSlice; } } } FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture1D(&d3d11Texture1DDesc, d3d11SubresourceData, &mD3D11Texture1D)) if (numberOfSlices > MAXIMUM_NUMBER_OF_SLICES) { RHI_FREE(context, d3d11SubresourceData); } } else { // The user did not provide us with texture data FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture1D(&d3d11Texture1DDesc, nullptr, &mD3D11Texture1D)) } // Create requested views if (nullptr != mD3D11Texture1D) { // Create the Direct3D 11 shader resource view instance if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; d3d11ShaderResourceViewDesc.Texture1DArray.MipLevels = numberOfMipmaps; d3d11ShaderResourceViewDesc.Texture1DArray.ArraySize = numberOfSlices; // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Texture1D, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE1DARRAY; d3d11UnorderedAccessViewDesc.Texture1DArray.ArraySize = numberOfSlices; // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Texture1D, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } } // Let Direct3D 11 generate the mipmaps for us automatically, if necessary if (nullptr != data && generateMipmaps) { direct3D11Rhi.generateAsynchronousDeferredMipmaps(*this, *mD3D11ShaderResourceView); } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "1D texture array", 19) // 19 = "1D texture array: " including terminating zero if (nullptr != mD3D11Texture1D) { FAILED_DEBUG_BREAK(mD3D11Texture1D->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~Texture1DArray() override { if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); } if (nullptr != mD3D11Texture1D) { mD3D11Texture1D->Release(); } } /** * @brief * Return the texture format * * @return * The texture format */ [[nodiscard]] inline Rhi::TextureFormat::Enum getTextureFormat() const { return mTextureFormat; } /** * @brief * Return the Direct3D texture 1D resource instance * * @return * The Direct3D texture 1D resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Texture1D* getD3D11Texture1D() const { return mD3D11Texture1D; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture1DArray, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture1DArray(const Texture1DArray& source) = delete; Texture1DArray& operator =(const Texture1DArray& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::TextureFormat::Enum mTextureFormat; ID3D11Texture1D* mD3D11Texture1D; ///< Direct3D 11 texture 1D resource, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Texture/Texture2D.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 2D texture class */ class Texture2D final : public Rhi::ITexture2D { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] width * Texture width, must be >0 * @param[in] height * Texture height, must be >0 * @param[in] textureFormat * Texture format * @param[in] data * Texture data, can be a null pointer * @param[in] textureFlags * Texture flags, see "Rhi::TextureFlag::Enum" * @param[in] textureUsage * Indication of the texture usage * @param[in] numberOfMultisamples * The number of multisamples per pixel (valid values: 1, 2, 4, 6, 8) */ Texture2D(Direct3D11Rhi& direct3D11Rhi, uint32_t width, uint32_t height, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags, Rhi::TextureUsage textureUsage, uint8_t numberOfMultisamples RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITexture2D(direct3D11Rhi, width, height RHI_RESOURCE_DEBUG_PASS_PARAMETER), mTextureFormat(textureFormat), mNumberOfMultisamples(numberOfMultisamples), mD3D11Texture2D(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMultisamples == 1 || numberOfMultisamples == 2 || numberOfMultisamples == 4 || numberOfMultisamples == 8, "Invalid Direct3D 11 texture parameters") RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMultisamples == 1 || nullptr == data, "Invalid Direct3D 11 texture parameters") RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMultisamples == 1 || 0 == (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS), "Invalid Direct3D 11 texture parameters") RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMultisamples == 1 || 0 == (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS), "Invalid Direct3D 11 texture parameters") RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMultisamples == 1 || 0 != (textureFlags & Rhi::TextureFlag::RENDER_TARGET), "Invalid Direct3D 11 texture parameters") RHI_ASSERT(direct3D11Rhi.getContext(), 0 == (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS) || nullptr != data, "Invalid Direct3D 11 texture parameters") RHI_ASSERT(direct3D11Rhi.getContext(), (textureFlags & Rhi::TextureFlag::RENDER_TARGET) == 0 || nullptr == data, "Direct3D 11 render target textures can't be filled using provided data") // Calculate the number of mipmaps const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS); const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS)); RHI_ASSERT(direct3D11Rhi.getContext(), Rhi::TextureUsage::IMMUTABLE != textureUsage || !generateMipmaps, "Direct3D 11 immutable texture usage can't be combined with automatic mipmap generation") const uint32_t numberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? getNumberOfMipmaps(width, height) : 1; const bool isDepthFormat = Rhi::TextureFormat::isDepth(textureFormat); // Direct3D 11 2D texture description D3D11_TEXTURE2D_DESC d3d11Texture2DDesc; d3d11Texture2DDesc.Width = width; d3d11Texture2DDesc.Height = height; d3d11Texture2DDesc.MipLevels = numberOfMipmaps; d3d11Texture2DDesc.ArraySize = 1; d3d11Texture2DDesc.Format = Mapping::getDirect3D11ResourceFormat(textureFormat); d3d11Texture2DDesc.SampleDesc.Count = numberOfMultisamples; d3d11Texture2DDesc.SampleDesc.Quality = 0; d3d11Texture2DDesc.Usage = static_cast<D3D11_USAGE>(textureUsage); // These constants directly map to Direct3D constants, do not change them d3d11Texture2DDesc.BindFlags = 0; d3d11Texture2DDesc.CPUAccessFlags = (Rhi::TextureUsage::DYNAMIC == textureUsage) ? D3D11_CPU_ACCESS_WRITE : 0u; d3d11Texture2DDesc.MiscFlags = (generateMipmaps && !isDepthFormat) ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0u; // Set bind flags if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if ((textureFlags & Rhi::TextureFlag::RENDER_TARGET) || generateMipmaps) { if (isDepthFormat) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_DEPTH_STENCIL; } else { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_RENDER_TARGET; } } if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } // Create the Direct3D 11 2D texture instance: Did the user provided us with any texture data? if (nullptr != data) { // We don't want dynamic allocations, so we limit the maximum number of mipmaps and hence are able to use the efficient C runtime stack static constexpr uint32_t MAXIMUM_NUMBER_OF_MIPMAPS = 15; // A 16384x16384 texture has 15 mipmaps RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMipmaps <= MAXIMUM_NUMBER_OF_MIPMAPS, "Invalid Direct3D 11 number of mipmaps") D3D11_SUBRESOURCE_DATA d3d11SubresourceData[MAXIMUM_NUMBER_OF_MIPMAPS]; // Did the user provided data containing mipmaps from 0-n down to 1x1 linearly in memory? if (dataContainsMipmaps) { // Upload all mipmaps for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { // Upload the current mipmap D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next mipmap and ensure the size is always at least 1x1 // -> If the data doesn't contain mipmaps, we don't need to care about this in here data = static_cast<const uint8_t*>(data) + Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height); width = getHalfSize(width); height = getHalfSize(height); } } else { // The user only provided us with the base texture, no mipmaps // -> When uploading data, we still need to upload the whole mipmap chain, so provide dummy data for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); } } FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture2D(&d3d11Texture2DDesc, d3d11SubresourceData, &mD3D11Texture2D)) } else { // The user did not provide us with texture data FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture2D(&d3d11Texture2DDesc, nullptr, &mD3D11Texture2D)) } // Create requested views if (nullptr != mD3D11Texture2D) { // Create the Direct3D 11 shader resource view instance if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11ShaderResourceViewDesc.ViewDimension = (numberOfMultisamples > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D; d3d11ShaderResourceViewDesc.Texture2D.MipLevels = numberOfMipmaps; // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Texture2D, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Texture2D, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } } // Let Direct3D 11 generate the mipmaps for us automatically, if necessary if (nullptr != data && generateMipmaps) { direct3D11Rhi.generateAsynchronousDeferredMipmaps(*this, *mD3D11ShaderResourceView); } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "2D texture", 13) // 13 = "2D texture: " including terminating zero if (nullptr != mD3D11Texture2D) { FAILED_DEBUG_BREAK(mD3D11Texture2D->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~Texture2D() override { if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); } if (nullptr != mD3D11Texture2D) { mD3D11Texture2D->Release(); } } /** * @brief * Return the texture format * * @return * The texture format */ [[nodiscard]] inline Rhi::TextureFormat::Enum getTextureFormat() const { return mTextureFormat; } /** * @brief * Return the number of multisamples * * @return * The number of multisamples per pixel (valid values: 1, 2, 4, 8) */ [[nodiscard]] inline uint8_t getNumberOfMultisamples() const { return mNumberOfMultisamples; } /** * @brief * Return the Direct3D texture 2D resource instance * * @return * The Direct3D texture 2D resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Texture2D* getD3D11Texture2D() const { return mD3D11Texture2D; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } /** * @brief * Set minimum maximum mipmap index * * @param[in] minimumMipmapIndex * Minimum mipmap index, the most detailed mipmap, also known as base mipmap, 0 by default * @param[in] maximumMipmapIndex * Maximum mipmap index, the least detailed mipmap, <number of mipmaps> by default */ void setMinimumMaximumMipmapIndex(uint32_t minimumMipmapIndex, uint32_t maximumMipmapIndex) { // Re-create the Direct3D 11 shader resource view instance if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); } if (nullptr != mD3D11Texture2D) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(mTextureFormat); d3d11ShaderResourceViewDesc.ViewDimension = (mNumberOfMultisamples > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D; d3d11ShaderResourceViewDesc.Texture2D.MipLevels = maximumMipmapIndex - minimumMipmapIndex + 1; d3d11ShaderResourceViewDesc.Texture2D.MostDetailedMip = minimumMipmapIndex; // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(static_cast<Direct3D11Rhi&>(getRhi()).getD3D11Device()->CreateShaderResourceView(mD3D11Texture2D, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } } //[-------------------------------------------------------] //[ Public virtual Rhi::IResource methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual void* getInternalResourceHandle() const override { return mD3D11Texture2D; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture2D, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture2D(const Texture2D& source) = delete; Texture2D& operator =(const Texture2D& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::TextureFormat::Enum mTextureFormat; uint8_t mNumberOfMultisamples; ID3D11Texture2D* mD3D11Texture2D; ///< Direct3D 11 texture 2D resource, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Texture/Texture2DArray.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 2D array texture class */ class Texture2DArray final : public Rhi::ITexture2DArray { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] width * Texture width, must be >0 * @param[in] height * Texture height, must be >0 * @param[in] numberOfSlices * Number of slices, must be >0 * @param[in] textureFormat * Texture format * @param[in] data * Texture data, can be a null pointer * @param[in] textureFlags * Texture flags, see "Rhi::TextureFlag::Enum" * @param[in] textureUsage * Indication of the texture usage */ Texture2DArray(Direct3D11Rhi& direct3D11Rhi, uint32_t width, uint32_t height, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags, Rhi::TextureUsage textureUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITexture2DArray(direct3D11Rhi, width, height, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER), mTextureFormat(textureFormat), mNumberOfMultisamples(1), // TODO(co) Currently no MSAA support for 2D array textures mD3D11Texture2D(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), (textureFlags & Rhi::TextureFlag::RENDER_TARGET) == 0 || nullptr == data, "Direct3D 11 render target textures can't be filled using provided data") // Calculate the number of mipmaps const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS); const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS)); RHI_ASSERT(direct3D11Rhi.getContext(), Rhi::TextureUsage::IMMUTABLE != textureUsage || !generateMipmaps, "Direct3D 11 immutable texture usage can't be combined with automatic mipmap generation") const uint32_t numberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? getNumberOfMipmaps(width, height) : 1; const bool isDepthFormat = Rhi::TextureFormat::isDepth(textureFormat); // Direct3D 11 2D array texture description D3D11_TEXTURE2D_DESC d3d11Texture2DDesc; d3d11Texture2DDesc.Width = width; d3d11Texture2DDesc.Height = height; d3d11Texture2DDesc.MipLevels = numberOfMipmaps; d3d11Texture2DDesc.ArraySize = numberOfSlices; d3d11Texture2DDesc.Format = Mapping::getDirect3D11ResourceFormat(textureFormat); d3d11Texture2DDesc.SampleDesc.Count = 1; d3d11Texture2DDesc.SampleDesc.Quality = 0; d3d11Texture2DDesc.Usage = static_cast<D3D11_USAGE>(textureUsage); // These constants directly map to Direct3D constants, do not change them d3d11Texture2DDesc.BindFlags = 0; d3d11Texture2DDesc.CPUAccessFlags = (Rhi::TextureUsage::DYNAMIC == textureUsage) ? D3D11_CPU_ACCESS_WRITE : 0u; d3d11Texture2DDesc.MiscFlags = (generateMipmaps && !isDepthFormat) ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0u; // Set bind flags if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if ((textureFlags & Rhi::TextureFlag::RENDER_TARGET) || generateMipmaps) { if (isDepthFormat) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_DEPTH_STENCIL; } else { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_RENDER_TARGET; } } if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } // Create the Direct3D 11 2D texture instance: Did the user provided us with any texture data? if (nullptr != data) { // We don't want dynamic allocations, so we limit the maximum number of mipmaps and hence are able to use the efficient C runtime stack static constexpr uint32_t MAXIMUM_NUMBER_OF_MIPMAPS = 15; // A 16384x16384 texture has 15 mipmaps static constexpr uint32_t MAXIMUM_NUMBER_OF_SLICES = 10; const Rhi::Context& context = direct3D11Rhi.getContext(); RHI_ASSERT(context, numberOfMipmaps <= MAXIMUM_NUMBER_OF_MIPMAPS, "Invalid Direct3D 11 number of mipmaps") D3D11_SUBRESOURCE_DATA d3d11SubresourceDataStack[MAXIMUM_NUMBER_OF_SLICES * MAXIMUM_NUMBER_OF_MIPMAPS]; D3D11_SUBRESOURCE_DATA* d3d11SubresourceData = (numberOfSlices <= MAXIMUM_NUMBER_OF_SLICES) ? d3d11SubresourceDataStack : RHI_MALLOC_TYPED(context, D3D11_SUBRESOURCE_DATA, numberOfSlices); // Did the user provided data containing mipmaps from 0-n down to 1x1 linearly in memory? if (dataContainsMipmaps) { // Data layout // - Direct3D 11 wants: DDS files are organized in slice-major order, like this: // Slice0: Mip0, Mip1, Mip2, etc. // Slice1: Mip0, Mip1, Mip2, etc. // etc. // - The RHI provides: CRN and KTX files are organized in mip-major order, like this: // Mip0: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5 // Mip1: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5 // etc. // Upload all mipmaps for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height); for (uint32_t arraySlice = 0; arraySlice < numberOfSlices; ++arraySlice) { // Upload the current slice D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[arraySlice * numberOfMipmaps + mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = numberOfBytesPerRow; currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next slice // -> If the data doesn't contain mipmaps, we don't need to care about this in here data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice; } // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); height = getHalfSize(height); } } else { // The user only provided us with the base texture, no mipmaps // -> When uploading data, we still need to upload the whole mipmap chain, so provide dummy data for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { const void* currentData = data; const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height); for (uint32_t arraySlice = 0; arraySlice < numberOfSlices; ++arraySlice) { D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[arraySlice * numberOfMipmaps + mipmap]; currentD3d11SubresourceData.pSysMem = currentData; currentD3d11SubresourceData.SysMemPitch = numberOfBytesPerRow; currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next slice currentData = static_cast<const uint8_t*>(currentData) + numberOfBytesPerSlice; } // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); height = getHalfSize(height); } } FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture2D(&d3d11Texture2DDesc, d3d11SubresourceData, &mD3D11Texture2D)) if (numberOfSlices > MAXIMUM_NUMBER_OF_SLICES) { RHI_FREE(context, d3d11SubresourceData); } } else { // The user did not provide us with texture data FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture2D(&d3d11Texture2DDesc, nullptr, &mD3D11Texture2D)) } // Create requested views if (nullptr != mD3D11Texture2D) { // Create the Direct3D 11 shader resource view instance if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; d3d11ShaderResourceViewDesc.Texture2DArray.MipLevels = numberOfMipmaps; d3d11ShaderResourceViewDesc.Texture2DArray.ArraySize = numberOfSlices; // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Texture2D, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY; d3d11UnorderedAccessViewDesc.Texture2DArray.ArraySize = numberOfSlices; // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Texture2D, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } } // Let Direct3D 11 generate the mipmaps for us automatically, if necessary if (nullptr != data && generateMipmaps) { direct3D11Rhi.generateAsynchronousDeferredMipmaps(*this, *mD3D11ShaderResourceView); } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "2D texture array", 19) // 19 = "2D texture array: " including terminating zero if (nullptr != mD3D11Texture2D) { FAILED_DEBUG_BREAK(mD3D11Texture2D->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~Texture2DArray() override { if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); } if (nullptr != mD3D11Texture2D) { mD3D11Texture2D->Release(); } } /** * @brief * Return the texture format * * @return * The texture format */ [[nodiscard]] inline Rhi::TextureFormat::Enum getTextureFormat() const { return mTextureFormat; } /** * @brief * Return the number of multisamples * * @return * The number of multisamples per pixel (valid values: 1, 2, 4, 8) */ [[nodiscard]] inline uint8_t getNumberOfMultisamples() const { return mNumberOfMultisamples; } /** * @brief * Return the Direct3D texture 2D resource instance * * @return * The Direct3D texture 2D resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Texture2D* getD3D11Texture2D() const { return mD3D11Texture2D; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture2DArray, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture2DArray(const Texture2DArray& source) = delete; Texture2DArray& operator =(const Texture2DArray& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::TextureFormat::Enum mTextureFormat; uint8_t mNumberOfMultisamples; ID3D11Texture2D* mD3D11Texture2D; ///< Direct3D 11 texture 2D resource, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Texture/Texture3D.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 3D texture class */ class Texture3D final : public Rhi::ITexture3D { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] width * Texture width, must be >0 * @param[in] height * Texture height, must be >0 * @param[in] depth * Texture depth, must be >0 * @param[in] textureFormat * Texture format * @param[in] data * Texture data, can be a null pointer * @param[in] textureFlags * Texture flags, see "Rhi::TextureFlag::Enum" * @param[in] textureUsage * Indication of the texture usage */ Texture3D(Direct3D11Rhi& direct3D11Rhi, uint32_t width, uint32_t height, uint32_t depth, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags, Rhi::TextureUsage textureUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITexture3D(direct3D11Rhi, width, height, depth RHI_RESOURCE_DEBUG_PASS_PARAMETER), mTextureFormat(textureFormat), mD3D11Texture3D(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), 0 == (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS) || nullptr != data, "Invalid Direct3D 11 texture parameters") RHI_ASSERT(direct3D11Rhi.getContext(), (textureFlags & Rhi::TextureFlag::RENDER_TARGET) == 0 || nullptr == data, "Direct3D 11 render target textures can't be filled using provided data") // Calculate the number of mipmaps const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS); const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS)); RHI_ASSERT(direct3D11Rhi.getContext(), Rhi::TextureUsage::IMMUTABLE != textureUsage || !generateMipmaps, "Direct3D 11 immutable texture usage can't be combined with automatic mipmap generation") const uint32_t numberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? getNumberOfMipmaps(width, height, depth) : 1; const bool isDepthFormat = Rhi::TextureFormat::isDepth(textureFormat); // Direct3D 11 3D texture description D3D11_TEXTURE3D_DESC d3d11Texture3DDesc; d3d11Texture3DDesc.Width = width; d3d11Texture3DDesc.Height = height; d3d11Texture3DDesc.Depth = depth; d3d11Texture3DDesc.MipLevels = numberOfMipmaps; d3d11Texture3DDesc.Format = Mapping::getDirect3D11ResourceFormat(textureFormat); d3d11Texture3DDesc.Usage = static_cast<D3D11_USAGE>(textureUsage); // These constants directly map to Direct3D constants, do not change them d3d11Texture3DDesc.BindFlags = 0; d3d11Texture3DDesc.CPUAccessFlags = (Rhi::TextureUsage::DYNAMIC == textureUsage) ? D3D11_CPU_ACCESS_WRITE : 0u; d3d11Texture3DDesc.MiscFlags = (generateMipmaps && !isDepthFormat) ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0u; // Set bind flags if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { d3d11Texture3DDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if ((textureFlags & Rhi::TextureFlag::RENDER_TARGET) || generateMipmaps) { if (isDepthFormat) { d3d11Texture3DDesc.BindFlags |= D3D11_BIND_DEPTH_STENCIL; } else { d3d11Texture3DDesc.BindFlags |= D3D11_BIND_RENDER_TARGET; } } if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { d3d11Texture3DDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } // Create the Direct3D 11 3D texture instance: Did the user provided us with any texture data? if (nullptr != data) { // We don't want dynamic allocations, so we limit the maximum number of mipmaps and hence are able to use the efficient C runtime stack static constexpr uint32_t MAXIMUM_NUMBER_OF_MIPMAPS = 15; // A 16384x16384 texture has 15 mipmaps RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMipmaps <= MAXIMUM_NUMBER_OF_MIPMAPS, "Invalid Direct3D 11 number of mipmaps") D3D11_SUBRESOURCE_DATA d3d11SubresourceData[MAXIMUM_NUMBER_OF_MIPMAPS]; // Did the user provided data containing mipmaps from 0-n down to 1x1 linearly in memory? if (dataContainsMipmaps) { // Data layout: The RHI provides: CRN and KTX files are organized in mip-major order, like this: // Mip0: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5 // Mip1: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5 // etc. // Upload all mipmaps for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { // Upload the current mipmap D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); currentD3d11SubresourceData.SysMemSlicePitch = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height); // Move on to the next mipmap and ensure the size is always at least 1x1x1 // -> If the data doesn't contain mipmaps, we don't need to care about this in here data = static_cast<const uint8_t*>(data) + currentD3d11SubresourceData.SysMemSlicePitch * depth; width = getHalfSize(width); height = getHalfSize(height); depth = getHalfSize(depth); } } else { // The user only provided us with the base texture, no mipmaps // -> When uploading data, we still need to upload the whole mipmap chain, so provide dummy data for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); currentD3d11SubresourceData.SysMemSlicePitch = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height); // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); height = getHalfSize(height); } } FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture3D(&d3d11Texture3DDesc, d3d11SubresourceData, &mD3D11Texture3D)) } else { // The user did not provide us with texture data FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture3D(&d3d11Texture3DDesc, nullptr, &mD3D11Texture3D)) } // Create requested views if (nullptr != mD3D11Texture3D) { // Create the Direct3D 11 shader resource view instance if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; d3d11ShaderResourceViewDesc.Texture3D.MipLevels = numberOfMipmaps; // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11Texture3D, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE3D; d3d11UnorderedAccessViewDesc.Texture3D.WSize = depth; // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11Texture3D, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } } // Let Direct3D 11 generate the mipmaps for us automatically, if necessary if (nullptr != data && generateMipmaps) { direct3D11Rhi.generateAsynchronousDeferredMipmaps(*this, *mD3D11ShaderResourceView); } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "3D texture", 13) // 13 = "3D texture: " including terminating zero if (nullptr != mD3D11Texture3D) { FAILED_DEBUG_BREAK(mD3D11Texture3D->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~Texture3D() override { if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); } if (nullptr != mD3D11Texture3D) { mD3D11Texture3D->Release(); } } /** * @brief * Return the texture format * * @return * The texture format */ [[nodiscard]] inline Rhi::TextureFormat::Enum getTextureFormat() const { return mTextureFormat; } /** * @brief * Return the Direct3D texture 3D resource instance * * @return * The Direct3D texture 3D resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Texture3D* getD3D11Texture3D() const { return mD3D11Texture3D; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Public virtual Rhi::IResource methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual void* getInternalResourceHandle() const override { return mD3D11Texture3D; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture3D, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture3D(const Texture3D& source) = delete; Texture3D& operator =(const Texture3D& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::TextureFormat::Enum mTextureFormat; ID3D11Texture3D* mD3D11Texture3D; ///< Direct3D 11 texture 3D resource, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Texture/TextureCube.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 cube texture class */ class TextureCube final : public Rhi::ITextureCube { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] width * Texture width, must be >0 * @param[in] textureFormat * Texture format * @param[in] data * Texture data, can be a null pointer * @param[in] textureFlags * Texture flags, see "Rhi::TextureFlag::Enum" * @param[in] textureUsage * Indication of the texture usage */ TextureCube(Direct3D11Rhi& direct3D11Rhi, uint32_t width, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags, Rhi::TextureUsage textureUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITextureCube(direct3D11Rhi, width RHI_RESOURCE_DEBUG_PASS_PARAMETER), mTextureFormat(textureFormat), mD3D11TextureCube(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { static constexpr uint32_t NUMBER_OF_SLICES = 6; // In Direct3D 11, a cube map is a 2D array texture with six slices // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), (textureFlags & Rhi::TextureFlag::RENDER_TARGET) == 0 || nullptr == data, "Direct3D 11 render target textures can't be filled using provided data") // Calculate the number of mipmaps const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS); const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS)); RHI_ASSERT(direct3D11Rhi.getContext(), Rhi::TextureUsage::IMMUTABLE != textureUsage || !generateMipmaps, "Direct3D 11 immutable texture usage can't be combined with automatic mipmap generation") const uint32_t numberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? getNumberOfMipmaps(width) : 1; // Direct3D 11 2D array texture description D3D11_TEXTURE2D_DESC d3d11Texture2DDesc; d3d11Texture2DDesc.Width = width; d3d11Texture2DDesc.Height = width; d3d11Texture2DDesc.MipLevels = numberOfMipmaps; d3d11Texture2DDesc.ArraySize = NUMBER_OF_SLICES; d3d11Texture2DDesc.Format = Mapping::getDirect3D11ResourceFormat(textureFormat); d3d11Texture2DDesc.SampleDesc.Count = 1; d3d11Texture2DDesc.SampleDesc.Quality = 0; d3d11Texture2DDesc.Usage = static_cast<D3D11_USAGE>(textureUsage); // These constants directly map to Direct3D constants, do not change them d3d11Texture2DDesc.BindFlags = 0; d3d11Texture2DDesc.CPUAccessFlags = (Rhi::TextureUsage::DYNAMIC == textureUsage) ? D3D11_CPU_ACCESS_WRITE : 0u; d3d11Texture2DDesc.MiscFlags = (generateMipmaps ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0u) | D3D11_RESOURCE_MISC_TEXTURECUBE; // Set bind flags if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if ((textureFlags & Rhi::TextureFlag::RENDER_TARGET) || generateMipmaps) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_RENDER_TARGET; } if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } // Create the Direct3D 11 2D texture instance: Did the user provided us with any texture data? if (nullptr != data) { // We don't want dynamic allocations, so we limit the maximum number of mipmaps and hence are able to use the efficient C runtime stack static constexpr uint32_t MAXIMUM_NUMBER_OF_MIPMAPS = 15; // A 16384x16384 texture has 15 mipmaps RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMipmaps <= MAXIMUM_NUMBER_OF_MIPMAPS, "Invalid Direct3D 11 number of mipmaps") D3D11_SUBRESOURCE_DATA d3d11SubresourceData[NUMBER_OF_SLICES * MAXIMUM_NUMBER_OF_MIPMAPS]; // Did the user provided data containing mipmaps from 0-n down to 1x1 linearly in memory? if (dataContainsMipmaps) { // Data layout // - Direct3D 11 wants: DDS files are organized in face-major order, like this: // Face0: Mip0, Mip1, Mip2, etc. // Face1: Mip0, Mip1, Mip2, etc. // etc. // - The RHI provides: CRN and KTX files are organized in mip-major order, like this: // Mip0: Face0, Face1, Face2, Face3, Face4, Face5 // Mip1: Face0, Face1, Face2, Face3, Face4, Face5 // etc. // Upload all mipmaps for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, width); for (uint32_t arraySlice = 0; arraySlice < NUMBER_OF_SLICES; ++arraySlice) { // Upload the current mipmap D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[arraySlice * numberOfMipmaps + mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = numberOfBytesPerRow; currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the cube map face // -> If the data doesn't contain mipmaps, we don't need to care about this in here data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice; } // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); } } else { // The user only provided us with the base texture, no mipmaps // -> When uploading data, we still need to upload the whole mipmap chain, so provide dummy data for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { const void* currentData = data; const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, width); for (uint32_t arraySlice = 0; arraySlice < NUMBER_OF_SLICES; ++arraySlice) { D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[arraySlice]; currentD3d11SubresourceData.pSysMem = currentData; currentD3d11SubresourceData.SysMemPitch = numberOfBytesPerRow; currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next slice currentData = static_cast<const uint8_t*>(currentData) + numberOfBytesPerSlice; } // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); } } FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture2D(&d3d11Texture2DDesc, d3d11SubresourceData, &mD3D11TextureCube)) } else { // The user did not provide us with texture data FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture2D(&d3d11Texture2DDesc, nullptr, &mD3D11TextureCube)) } // Create requested views if (nullptr != mD3D11TextureCube) { // Create the Direct3D 11 shader resource view instance if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; d3d11ShaderResourceViewDesc.TextureCube.MipLevels = numberOfMipmaps; // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11TextureCube, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY; d3d11UnorderedAccessViewDesc.Texture2DArray.ArraySize = NUMBER_OF_SLICES; // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11TextureCube, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } } // Let Direct3D 11 generate the mipmaps for us automatically, if necessary if (nullptr != data && generateMipmaps) { direct3D11Rhi.generateAsynchronousDeferredMipmaps(*this, *mD3D11ShaderResourceView); } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Cube texture", 15) // 15 = "Cube texture: " including terminating zero if (nullptr != mD3D11TextureCube) { FAILED_DEBUG_BREAK(mD3D11TextureCube->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~TextureCube() override { if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); } if (nullptr != mD3D11TextureCube) { mD3D11TextureCube->Release(); } } /** * @brief * Return the texture format * * @return * The texture format */ [[nodiscard]] inline Rhi::TextureFormat::Enum getTextureFormat() const { return mTextureFormat; } /** * @brief * Return the Direct3D texture cube resource instance * * @return * The Direct3D texture cube resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Texture2D* getD3D11TextureCube() const { return mD3D11TextureCube; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Public virtual Rhi::IResource methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual void* getInternalResourceHandle() const override { return mD3D11TextureCube; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TextureCube, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TextureCube(const TextureCube& source) = delete; TextureCube& operator =(const TextureCube& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::TextureFormat::Enum mTextureFormat; ID3D11Texture2D* mD3D11TextureCube; ///< Direct3D 11 texture cube resource, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Texture/TextureCubeArray.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 cube texture array class */ class TextureCubeArray final : public Rhi::ITextureCubeArray { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] width * Texture width, must be >0 * @param[in] numberOfSlices * Number of slices, must be >0 * @param[in] textureFormat * Texture format * @param[in] data * Texture data, can be a null pointer * @param[in] textureFlags * Texture flags, see "Rhi::TextureFlag::Enum" * @param[in] textureUsage * Indication of the texture usage */ TextureCubeArray(Direct3D11Rhi& direct3D11Rhi, uint32_t width, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags, Rhi::TextureUsage textureUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITextureCubeArray(direct3D11Rhi, width, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER), mTextureFormat(textureFormat), mD3D11TextureCube(nullptr), mD3D11ShaderResourceView(nullptr), mD3D11UnorderedAccessView(nullptr) { static constexpr uint32_t NUMBER_OF_SLICES = 6; // In Direct3D 11, a cube map is a 2D array texture with six slices const uint32_t arraySize = NUMBER_OF_SLICES * numberOfSlices; // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), (textureFlags & Rhi::TextureFlag::RENDER_TARGET) == 0 || nullptr == data, "Direct3D 11 render target textures can't be filled using provided data") // Calculate the number of mipmaps const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS); const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS)); RHI_ASSERT(direct3D11Rhi.getContext(), Rhi::TextureUsage::IMMUTABLE != textureUsage || !generateMipmaps, "Direct3D 11 immutable texture usage can't be combined with automatic mipmap generation") const uint32_t numberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? getNumberOfMipmaps(width) : 1; // Direct3D 11 2D array texture description D3D11_TEXTURE2D_DESC d3d11Texture2DDesc; d3d11Texture2DDesc.Width = width; d3d11Texture2DDesc.Height = width; d3d11Texture2DDesc.MipLevels = numberOfMipmaps; d3d11Texture2DDesc.ArraySize = arraySize; d3d11Texture2DDesc.Format = Mapping::getDirect3D11ResourceFormat(textureFormat); d3d11Texture2DDesc.SampleDesc.Count = 1; d3d11Texture2DDesc.SampleDesc.Quality = 0; d3d11Texture2DDesc.Usage = static_cast<D3D11_USAGE>(textureUsage); // These constants directly map to Direct3D constants, do not change them d3d11Texture2DDesc.BindFlags = 0; d3d11Texture2DDesc.CPUAccessFlags = (Rhi::TextureUsage::DYNAMIC == textureUsage) ? D3D11_CPU_ACCESS_WRITE : 0u; d3d11Texture2DDesc.MiscFlags = (generateMipmaps ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0u) | D3D11_RESOURCE_MISC_TEXTURECUBE; // Set bind flags if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if ((textureFlags & Rhi::TextureFlag::RENDER_TARGET) || generateMipmaps) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_RENDER_TARGET; } if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { d3d11Texture2DDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } // Create the Direct3D 11 2D texture instance: Did the user provided us with any texture data? if (nullptr != data) { // We don't want dynamic allocations, so we limit the maximum number of mipmaps and hence are able to use the efficient C runtime stack static constexpr uint32_t MAXIMUM_NUMBER_OF_MIPMAPS = 15; // A 16384x16384 texture has 15 mipmaps RHI_ASSERT(direct3D11Rhi.getContext(), numberOfMipmaps <= MAXIMUM_NUMBER_OF_MIPMAPS, "Invalid Direct3D 11 number of mipmaps") D3D11_SUBRESOURCE_DATA* d3d11SubresourceData = RHI_MALLOC_TYPED(direct3D11Rhi.getContext(), D3D11_SUBRESOURCE_DATA, arraySize * MAXIMUM_NUMBER_OF_MIPMAPS); // Did the user provided data containing mipmaps from 0-n down to 1x1 linearly in memory? if (dataContainsMipmaps) { // Data layout // - Direct3D 11 wants: DDS files are organized in face-major order, like this: // Face0: Mip0, Mip1, Mip2, etc. // Face1: Mip0, Mip1, Mip2, etc. // etc. // - The RHI provides: CRN and KTX files are organized in mip-major order, like this: // Mip0: Face0, Face1, Face2, Face3, Face4, Face5 // Mip1: Face0, Face1, Face2, Face3, Face4, Face5 // etc. // Upload all mipmaps for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, width); for (uint32_t arraySlice = 0; arraySlice < arraySize; ++arraySlice) { // Upload the current mipmap D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[arraySlice * numberOfMipmaps + mipmap]; currentD3d11SubresourceData.pSysMem = data; currentD3d11SubresourceData.SysMemPitch = numberOfBytesPerRow; currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the cube map face // -> If the data doesn't contain mipmaps, we don't need to care about this in here data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice; } // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); } } else { // The user only provided us with the base texture, no mipmaps // -> When uploading data, we still need to upload the whole mipmap chain, so provide dummy data for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap) { const void* currentData = data; const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width); const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, width); for (uint32_t arraySlice = 0; arraySlice < arraySize; ++arraySlice) { D3D11_SUBRESOURCE_DATA& currentD3d11SubresourceData = d3d11SubresourceData[arraySlice]; currentD3d11SubresourceData.pSysMem = currentData; currentD3d11SubresourceData.SysMemPitch = numberOfBytesPerRow; currentD3d11SubresourceData.SysMemSlicePitch = 0; // Only relevant for 3D textures // Move on to the next slice currentData = static_cast<const uint8_t*>(currentData) + numberOfBytesPerSlice; } // Move on to the next mipmap and ensure the size is always at least 1x1 width = getHalfSize(width); } } FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture2D(&d3d11Texture2DDesc, d3d11SubresourceData, &mD3D11TextureCube)) RHI_FREE(direct3D11Rhi.getContext(), d3d11SubresourceData); } else { // The user did not provide us with texture data FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateTexture2D(&d3d11Texture2DDesc, nullptr, &mD3D11TextureCube)) } // Create requested views if (nullptr != mD3D11TextureCube) { // Create the Direct3D 11 shader resource view instance if (textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) { // Direct3D 11 shader resource view description D3D11_SHADER_RESOURCE_VIEW_DESC d3d11ShaderResourceViewDesc = {}; d3d11ShaderResourceViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY; d3d11ShaderResourceViewDesc.TextureCubeArray.MipLevels = numberOfMipmaps; d3d11ShaderResourceViewDesc.TextureCubeArray.NumCubes = numberOfSlices; // Create the Direct3D 11 shader resource view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateShaderResourceView(mD3D11TextureCube, &d3d11ShaderResourceViewDesc, &mD3D11ShaderResourceView)) } // Create the Direct3D 11 unordered access view instance if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS) { // Direct3D 11 unordered access view description D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11UnorderedAccessViewDesc = {}; d3d11UnorderedAccessViewDesc.Format = Mapping::getDirect3D11ShaderResourceViewFormat(textureFormat); d3d11UnorderedAccessViewDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY; d3d11UnorderedAccessViewDesc.Texture2DArray.ArraySize = arraySize; // Create the Direct3D 11 unordered access view instance FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateUnorderedAccessView(mD3D11TextureCube, &d3d11UnorderedAccessViewDesc, &mD3D11UnorderedAccessView)) } } // Let Direct3D 11 generate the mipmaps for us automatically, if necessary if (nullptr != data && generateMipmaps) { direct3D11Rhi.generateAsynchronousDeferredMipmaps(*this, *mD3D11ShaderResourceView); } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Cube texture array", 21) // 21 = "Cube texture array: " including terminating zero if (nullptr != mD3D11TextureCube) { FAILED_DEBUG_BREAK(mD3D11TextureCube->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11ShaderResourceView) { FAILED_DEBUG_BREAK(mD3D11ShaderResourceView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11UnorderedAccessView) { FAILED_DEBUG_BREAK(mD3D11UnorderedAccessView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~TextureCubeArray() override { if (nullptr != mD3D11ShaderResourceView) { mD3D11ShaderResourceView->Release(); } if (nullptr != mD3D11UnorderedAccessView) { mD3D11UnorderedAccessView->Release(); } if (nullptr != mD3D11TextureCube) { mD3D11TextureCube->Release(); } } /** * @brief * Return the texture format * * @return * The texture format */ [[nodiscard]] inline Rhi::TextureFormat::Enum getTextureFormat() const { return mTextureFormat; } /** * @brief * Return the Direct3D texture cube resource instance * * @return * The Direct3D texture cube resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11Texture2D* getD3D11TextureCube() const { return mD3D11TextureCube; } /** * @brief * Return the Direct3D shader resource view instance * * @return * The Direct3D shader resource view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11ShaderResourceView* getD3D11ShaderResourceView() const { return mD3D11ShaderResourceView; } /** * @brief * Return the Direct3D unordered access view instance * * @return * The Direct3D unordered access view instance, can be a null pointer, do not release the returned instance unless you added an own reference to it * * @note * - It's not recommended to manipulate the returned Direct3D 11 resource * view by e.g. assigning another Direct3D 11 resource to it */ [[nodiscard]] inline ID3D11UnorderedAccessView* getD3D11UnorderedAccessView() const { return mD3D11UnorderedAccessView; } //[-------------------------------------------------------] //[ Public virtual Rhi::IResource methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual void* getInternalResourceHandle() const override { return mD3D11TextureCube; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TextureCubeArray, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TextureCubeArray(const TextureCubeArray& source) = delete; TextureCubeArray& operator =(const TextureCubeArray& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::TextureFormat::Enum mTextureFormat; ID3D11Texture2D* mD3D11TextureCube; ///< Direct3D 11 texture cube resource, can be a null pointer ID3D11ShaderResourceView* mD3D11ShaderResourceView; ///< Direct3D 11 shader resource view, can be a null pointer ID3D11UnorderedAccessView* mD3D11UnorderedAccessView; ///< Direct3D 11 unordered access view, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Texture/TextureManager.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 texture manager interface */ class TextureManager final : public Rhi::ITextureManager { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance */ inline explicit TextureManager(Direct3D11Rhi& direct3D11Rhi) : ITextureManager(direct3D11Rhi) {} /** * @brief * Destructor */ inline virtual ~TextureManager() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::ITextureManager methods ] //[-------------------------------------------------------] public: [[nodiscard]] virtual Rhi::ITexture1D* createTexture1D(uint32_t width, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), width > 0, "Direct3D 11 create texture 1D was called with invalid parameters") // Create 1D texture resource return RHI_NEW(direct3D11Rhi.getContext(), Texture1D)(direct3D11Rhi, width, textureFormat, data, textureFlags, textureUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITexture1DArray* createTexture1DArray(uint32_t width, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), width > 0 && numberOfSlices > 0, "Direct3D 11 create texture 1D array was called with invalid parameters") // Create 1D texture array resource return RHI_NEW(direct3D11Rhi.getContext(), Texture1DArray)(direct3D11Rhi, width, numberOfSlices, textureFormat, data, textureFlags, textureUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITexture2D* createTexture2D(uint32_t width, uint32_t height, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT, uint8_t numberOfMultisamples = 1, [[maybe_unused]] const Rhi::OptimizedTextureClearValue* optimizedTextureClearValue = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), width > 0 && height > 0, "Direct3D 11 create texture 2D was called with invalid parameters") // Create 2D texture resource return RHI_NEW(direct3D11Rhi.getContext(), Texture2D)(direct3D11Rhi, width, height, textureFormat, data, textureFlags, textureUsage, numberOfMultisamples RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITexture2DArray* createTexture2DArray(uint32_t width, uint32_t height, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), width > 0 && height > 0 && numberOfSlices > 0, "Direct3D 11 create texture 2D array was called with invalid parameters") // Create 2D texture array resource return RHI_NEW(direct3D11Rhi.getContext(), Texture2DArray)(direct3D11Rhi, width, height, numberOfSlices, textureFormat, data, textureFlags, textureUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITexture3D* createTexture3D(uint32_t width, uint32_t height, uint32_t depth, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), width > 0 && height > 0 && depth > 0, "Direct3D 11 create texture 3D was called with invalid parameters") // Create 3D texture resource return RHI_NEW(direct3D11Rhi.getContext(), Texture3D)(direct3D11Rhi, width, height, depth, textureFormat, data, textureFlags, textureUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITextureCube* createTextureCube(uint32_t width, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), width > 0, "Direct3D 11 create texture cube was called with invalid parameters") // Create cube texture resource return RHI_NEW(direct3D11Rhi.getContext(), TextureCube)(direct3D11Rhi, width, textureFormat, data, textureFlags, textureUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITextureCubeArray* createTextureCubeArray(uint32_t width, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), width > 0 && numberOfSlices > 0, "Direct3D 11 create texture cube array was called with invalid parameters") // Create cube texture resource return RHI_NEW(direct3D11Rhi.getContext(), TextureCubeArray)(direct3D11Rhi, width, numberOfSlices, textureFormat, data, textureFlags, textureUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TextureManager, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TextureManager(const TextureManager& source) = delete; TextureManager& operator =(const TextureManager& source) = delete; }; //[-------------------------------------------------------] //[ Direct3D11Rhi/State/SamplerState.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 sampler state class */ class SamplerState final : public Rhi::ISamplerState { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] samplerState * Sampler state to use */ SamplerState(Direct3D11Rhi& direct3D11Rhi, const Rhi::SamplerState& samplerState RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ISamplerState(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11SamplerState(nullptr) { // Sanity checks RHI_ASSERT(direct3D11Rhi.getContext(), Rhi::FilterMode::UNKNOWN != samplerState.filter, "Direct3D 11 filter mode must not be unknown") RHI_ASSERT(direct3D11Rhi.getContext(), samplerState.maxAnisotropy <= direct3D11Rhi.getCapabilities().maximumAnisotropy, "Maximum Direct3D 11 anisotropy value violated") // Create the Direct3D 11 sampler state // -> "Rhi::SamplerState" maps directly to Direct3D 10 & 11, do not change it static_assert(sizeof(Rhi::SamplerState) == sizeof(D3D11_SAMPLER_DESC), "Direct3D 11 structure mismatch detected"); FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateSamplerState(reinterpret_cast<const D3D11_SAMPLER_DESC*>(&samplerState), &mD3D11SamplerState)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11SamplerState) { // Avoid "D3D11 WARNING: ID3D11SamplerState::SetPrivateData: Existing private data of same name with different size found! [ STATE_SETTING WARNING #55: SETPRIVATEDATA_CHANGINGPARAMS]" messages by checking whether or not a debug name is already set (first wins) // -> This can happen since Direct3D 11 internally automatically checks if a sampler state instance with the requested configuration already exists // -> The result of "ID3D11DeviceChild::GetPrivateData()" is not checked by intent since this probably means that no debug name has been set, yet UINT existingDataSize = 0; mD3D11SamplerState->GetPrivateData(WKPDID_D3DDebugObjectName, &existingDataSize, nullptr); if (0 == existingDataSize) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Sampler state", 16) // 16 = "Sampler state: " including terminating zero FAILED_DEBUG_BREAK(mD3D11SamplerState->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } } #endif } /** * @brief * Destructor */ virtual ~SamplerState() override { // Release the Direct3D 11 sampler state if (nullptr != mD3D11SamplerState) { mD3D11SamplerState->Release(); } } /** * @brief * Return the Direct3D 11 sampler state * * @return * The Direct3D 11 sampler state, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11SamplerState* getD3D11SamplerState() const { return mD3D11SamplerState; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), SamplerState, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit SamplerState(const SamplerState& source) = delete; SamplerState& operator =(const SamplerState& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11SamplerState* mD3D11SamplerState; ///< Direct3D 11 sampler state, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/State/IState.h ] //[-------------------------------------------------------] /** * @brief * Abstract state base class */ class IState { //[-------------------------------------------------------] //[ Protected methods ] //[-------------------------------------------------------] protected: /** * @brief * Default constructor */ inline IState() {} /** * @brief * Destructor */ inline ~IState() {} }; //[-------------------------------------------------------] //[ Direct3D11Rhi/State/RasterizerState.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 rasterizer state class */ class RasterizerState final : public IState { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] rasterizerState * Rasterizer state to use */ RasterizerState(Direct3D11Rhi& direct3D11Rhi, const Rhi::RasterizerState& rasterizerState) : mD3D11RasterizerState(nullptr) { // Create the Direct3D 11 rasterizer state // -> "ID3D11Device::CreateRasterizerState()" takes automatically care of duplicate rasterizer state handling // -> Thank's to Direct3D 12, "Rhi::RasterizerState" doesn't map directly to Direct3D 10 & 11 - but at least the constants directly still map D3D11_RASTERIZER_DESC d3d11RasterizerDesc; d3d11RasterizerDesc.FillMode = static_cast<D3D11_FILL_MODE>(rasterizerState.fillMode); d3d11RasterizerDesc.CullMode = static_cast<D3D11_CULL_MODE>(rasterizerState.cullMode); d3d11RasterizerDesc.FrontCounterClockwise = rasterizerState.frontCounterClockwise; d3d11RasterizerDesc.DepthBias = rasterizerState.depthBias; d3d11RasterizerDesc.DepthBiasClamp = rasterizerState.depthBiasClamp; d3d11RasterizerDesc.SlopeScaledDepthBias = rasterizerState.slopeScaledDepthBias; d3d11RasterizerDesc.DepthClipEnable = rasterizerState.depthClipEnable; d3d11RasterizerDesc.ScissorEnable = rasterizerState.scissorEnable; d3d11RasterizerDesc.MultisampleEnable = rasterizerState.multisampleEnable; d3d11RasterizerDesc.AntialiasedLineEnable = rasterizerState.antialiasedLineEnable; FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateRasterizerState(&d3d11RasterizerDesc, &mD3D11RasterizerState)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11RasterizerState) { static constexpr char NAME[] = "Rasterizer state"; FAILED_DEBUG_BREAK(mD3D11RasterizerState->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(NAME)), NAME)) } #endif } /** * @brief * Destructor */ ~RasterizerState() { // Release the Direct3D 11 rasterizer state if (nullptr != mD3D11RasterizerState) { mD3D11RasterizerState->Release(); } } /** * @brief * Return the Direct3D 11 rasterizer state * * @return * The Direct3D 11 rasterizer state, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11RasterizerState* getD3D11RasterizerState() const { return mD3D11RasterizerState; } //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11RasterizerState* mD3D11RasterizerState; ///< Direct3D 11 rasterizer state, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/State/DepthStencilState.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 depth stencil state class */ class DepthStencilState final : public IState { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] depthStencilState * Depth stencil state to use */ DepthStencilState(Direct3D11Rhi& direct3D11Rhi, const Rhi::DepthStencilState& depthStencilState) : mD3D11DepthStencilState(nullptr) { // Create the Direct3D 11 depth stencil state // -> "ID3D11Device::CreateDepthStencilState()" takes automatically care of duplicate depth stencil state handling // -> "Rhi::DepthStencilState" maps directly to Direct3D 10 & 11 & 12, do not change it FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateDepthStencilState(reinterpret_cast<const D3D11_DEPTH_STENCIL_DESC*>(&depthStencilState), &mD3D11DepthStencilState)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11DepthStencilState) { static constexpr char NAME[] = "Depth stencil state"; FAILED_DEBUG_BREAK(mD3D11DepthStencilState->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(NAME)), NAME)) } #endif } /** * @brief * Destructor */ ~DepthStencilState() { // Release the Direct3D 11 depth stencil state if (nullptr != mD3D11DepthStencilState) { mD3D11DepthStencilState->Release(); } } /** * @brief * Return the Direct3D 11 depth stencil state * * @return * The Direct3D 11 depth stencil state, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11DepthStencilState* getD3D11DepthStencilState() const { return mD3D11DepthStencilState; } //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11DepthStencilState* mD3D11DepthStencilState; ///< Direct3D 11 depth stencil state, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/State/BlendState.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 blend state class */ class BlendState final : public IState { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] blendState * Blend state to use */ BlendState(Direct3D11Rhi& direct3D11Rhi, const Rhi::BlendState& blendState) : mD3D11BlendState(nullptr) { // Create the Direct3D 11 depth stencil state // -> "ID3D11Device::CreateBlendState()" takes automatically care of duplicate blend state handling // -> "Rhi::DepthStencilState" maps directly to Direct3D 10 & 11, do not change it static_assert(sizeof(Rhi::BlendState) == sizeof(D3D11_BLEND_DESC), "Direct3D 11 structure mismatch detected"); FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateBlendState(reinterpret_cast<const D3D11_BLEND_DESC*>(&blendState), &mD3D11BlendState)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11BlendState) { static constexpr char NAME[] = "Blend state"; FAILED_DEBUG_BREAK(mD3D11BlendState->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(NAME)), NAME)) } #endif } /** * @brief * Destructor */ ~BlendState() { // Release the Direct3D 11 blend state if (nullptr != mD3D11BlendState) { mD3D11BlendState->Release(); } } /** * @brief * Return the Direct3D 11 blend state * * @return * The Direct3D 11 blend state, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11BlendState* getD3D11BlendState() const { return mD3D11BlendState; } //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11BlendState* mD3D11BlendState; ///< Direct3D 11 blend state, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/RenderTarget/RenderPass.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 render pass interface */ class RenderPass final : public Rhi::IRenderPass { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] rhi * Owner RHI instance * @param[in] numberOfColorAttachments * Number of color render target textures, must be <="Rhi::Capabilities::maximumNumberOfSimultaneousRenderTargets" * @param[in] colorAttachmentTextureFormats * The color render target texture formats, can be a null pointer or can contain null pointers, if not a null pointer there must be at * least "numberOfColorAttachments" textures in the provided C-array of pointers * @param[in] depthStencilAttachmentTextureFormat * The optional depth stencil render target texture format, can be a "Rhi::TextureFormat::UNKNOWN" if there should be no depth buffer * @param[in] numberOfMultisamples * The number of multisamples per pixel (valid values: 1, 2, 4, 8) */ RenderPass(Rhi::IRhi& rhi, uint32_t numberOfColorAttachments, const Rhi::TextureFormat::Enum* colorAttachmentTextureFormats, Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat, uint8_t numberOfMultisamples RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IRenderPass(rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mNumberOfColorAttachments(numberOfColorAttachments), mDepthStencilAttachmentTextureFormat(depthStencilAttachmentTextureFormat), mNumberOfMultisamples(numberOfMultisamples) { RHI_ASSERT(rhi.getContext(), mNumberOfColorAttachments < 8, "Invalid number of Direct3D 11 color attachments") memcpy(mColorAttachmentTextureFormats, colorAttachmentTextureFormats, sizeof(Rhi::TextureFormat::Enum) * mNumberOfColorAttachments); } /** * @brief * Destructor */ inline virtual ~RenderPass() override {} /** * @brief * Return the number of color render target textures * * @return * The number of color render target textures */ [[nodiscard]] inline uint32_t getNumberOfColorAttachments() const { return mNumberOfColorAttachments; } /** * @brief * Return the number of render target textures (color and depth stencil) * * @return * The number of render target textures (color and depth stencil) */ [[nodiscard]] inline uint32_t getNumberOfAttachments() const { return (mDepthStencilAttachmentTextureFormat != Rhi::TextureFormat::Enum::UNKNOWN) ? (mNumberOfColorAttachments + 1) : mNumberOfColorAttachments; } /** * @brief * Return the color attachment texture format * * @param[in] colorAttachmentIndex * Color attachment index * * @return * The color attachment texture format */ [[nodiscard]] inline Rhi::TextureFormat::Enum getColorAttachmentTextureFormat(uint32_t colorAttachmentIndex) const { RHI_ASSERT(getRhi().getContext(), colorAttachmentIndex < mNumberOfColorAttachments, "Invalid Direct3D 11 color attachment index") return mColorAttachmentTextureFormats[colorAttachmentIndex]; } /** * @brief * Return the depth stencil attachment texture format * * @return * The depth stencil attachment texture format */ [[nodiscard]] inline Rhi::TextureFormat::Enum getDepthStencilAttachmentTextureFormat() const { return mDepthStencilAttachmentTextureFormat; } /** * @brief * Return the number of multisamples * * @return * The number of multisamples */ [[nodiscard]] inline uint8_t getNumberOfMultisamples() const { return mNumberOfMultisamples; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), RenderPass, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit RenderPass(const RenderPass& source) = delete; RenderPass& operator =(const RenderPass& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: uint32_t mNumberOfColorAttachments; Rhi::TextureFormat::Enum mColorAttachmentTextureFormats[8]; Rhi::TextureFormat::Enum mDepthStencilAttachmentTextureFormat; uint8_t mNumberOfMultisamples; }; //[-------------------------------------------------------] //[ Direct3D11Rhi/QueryPool.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 asynchronous query pool interface */ class QueryPool final : public Rhi::IQueryPool { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] queryType * Query type * @param[in] numberOfQueries * Number of queries */ QueryPool(Direct3D11Rhi& direct3D11Rhi, Rhi::QueryType queryType, uint32_t numberOfQueries RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IQueryPool(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mQueryType(queryType), mNumberOfQueries(numberOfQueries), mD3D11Queries(RHI_MALLOC_TYPED(direct3D11Rhi.getContext(), ID3D11Query*, numberOfQueries)) { // Get Direct3D 11 query description D3D11_QUERY_DESC d3d11QueryDesc = {}; switch (queryType) { case Rhi::QueryType::OCCLUSION: d3d11QueryDesc.Query = D3D11_QUERY_OCCLUSION; break; case Rhi::QueryType::PIPELINE_STATISTICS: d3d11QueryDesc.Query = D3D11_QUERY_PIPELINE_STATISTICS; break; case Rhi::QueryType::TIMESTAMP: d3d11QueryDesc.Query = D3D11_QUERY_TIMESTAMP; break; } { // Create Direct3D 11 queries ID3D11Device* d3d11Device = direct3D11Rhi.getD3D11Device(); for (uint32_t i = 0; i < numberOfQueries; ++i) { FAILED_DEBUG_BREAK(d3d11Device->CreateQuery(&d3d11QueryDesc, &mD3D11Queries[i])) } } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG switch (queryType) { case Rhi::QueryType::OCCLUSION: { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Occlusion query", 18) // 18 = "Occlusion query: " including terminating zero const UINT detailedDebugNameLength = static_cast<UINT>(strlen(detailedDebugName)); for (uint32_t i = 0; i < mNumberOfQueries; ++i) { ID3D11Query* d3d11Query = mD3D11Queries[i]; if (nullptr != d3d11Query) { FAILED_DEBUG_BREAK(d3d11Query->SetPrivateData(WKPDID_D3DDebugObjectName, detailedDebugNameLength, detailedDebugName)) } } break; } case Rhi::QueryType::PIPELINE_STATISTICS: { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Pipeline statistics query", 28) // 28 = "Pipeline statistics query: " including terminating zero const UINT detailedDebugNameLength = static_cast<UINT>(strlen(detailedDebugName)); for (uint32_t i = 0; i < mNumberOfQueries; ++i) { ID3D11Query* d3d11Query = mD3D11Queries[i]; if (nullptr != d3d11Query) { FAILED_DEBUG_BREAK(d3d11Query->SetPrivateData(WKPDID_D3DDebugObjectName, detailedDebugNameLength, detailedDebugName)) } } break; } case Rhi::QueryType::TIMESTAMP: { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Timestamp query", 18) // 18 = "Timestamp query: " including terminating zero const UINT detailedDebugNameLength = static_cast<UINT>(strlen(detailedDebugName)); for (uint32_t i = 0; i < mNumberOfQueries; ++i) { ID3D11Query* d3d11Query = mD3D11Queries[i]; if (nullptr != d3d11Query) { FAILED_DEBUG_BREAK(d3d11Query->SetPrivateData(WKPDID_D3DDebugObjectName, detailedDebugNameLength, detailedDebugName)) } } break; } } #endif } /** * @brief * Destructor */ virtual ~QueryPool() override { for (uint32_t i = 0; i < mNumberOfQueries; ++i) { mD3D11Queries[i]->Release(); } RHI_FREE(getRhi().getContext(), mD3D11Queries); } /** * @brief * Return the query type * * @return * The query type */ [[nodiscard]] inline Rhi::QueryType getQueryType() const { return mQueryType; } /** * @brief * Return the number of queries * * @return * The number of queries */ [[nodiscard]] inline uint32_t getNumberOfQueries() const { return mNumberOfQueries; } /** * @brief * Return the Direct3D 11 queries * * @return * The Direct3D 11 queries, considered to be always valid */ [[nodiscard]] inline ID3D11Query** getD3D11Queries() const { return mD3D11Queries; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), QueryPool, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit QueryPool(const QueryPool& source) = delete; QueryPool& operator =(const QueryPool& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::QueryType mQueryType; uint32_t mNumberOfQueries; ID3D11Query** mD3D11Queries; // The Direct3D 11 queries, considered to be always valid }; //[-------------------------------------------------------] //[ Direct3D11Rhi/RenderTarget/SwapChain.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 swap chain class */ class SwapChain final : public Rhi::ISwapChain { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] renderPass * Render pass to use, the swap chain keeps a reference to the render pass * @param[in] windowHandle * Information about the window to render into */ SwapChain(Rhi::IRenderPass& renderPass, Rhi::WindowHandle windowHandle RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ISwapChain(renderPass RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11DeviceContext1(nullptr), mDxgiSwapChain(nullptr), mD3D11RenderTargetView(nullptr), mD3D11DepthStencilView(nullptr), mSynchronizationInterval(0), mAllowTearing(false) { const RenderPass& d3d11RenderPass = static_cast<RenderPass&>(renderPass); const Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(d3d11RenderPass.getRhi()); FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11DeviceContext()->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&mD3D11DeviceContext1))) // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), 1 == d3d11RenderPass.getNumberOfColorAttachments(), "There must be exactly one Direct3D 11 render pass color attachment") // Get the Direct3D 11 device instance ID3D11Device* d3d11Device = direct3D11Rhi.getD3D11Device(); // Get the native window handle const HWND hWnd = reinterpret_cast<HWND>(windowHandle.nativeWindowHandle); // Get a DXGI factory instance const bool isWindows10OrGreater = ::detail::isWindows10OrGreater(); IDXGIFactory1* dxgiFactory1 = nullptr; IDXGIFactory2* dxgiFactory2 = nullptr; { IDXGIDevice* dxgiDevice = nullptr; IDXGIAdapter* dxgiAdapter = nullptr; FAILED_DEBUG_BREAK(d3d11Device->QueryInterface(IID_PPV_ARGS(&dxgiDevice))) FAILED_DEBUG_BREAK(dxgiDevice->GetAdapter(&dxgiAdapter)) FAILED_DEBUG_BREAK(dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory1))) FAILED_DEBUG_BREAK(dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory2))) // Determines whether tearing support is available for fullscreen borderless windows // -> To unlock frame rates of UWP applications on the Windows Store and providing support for both AMD Freesync and NVIDIA's G-SYNC we must explicitly allow tearing // -> See "Windows Dev Center" -> "Variable refresh rate displays": https://msdn.microsoft.com/en-us/library/windows/desktop/mt742104(v=vs.85).aspx if (isWindows10OrGreater) { IDXGIFactory5* dxgiFactory5 = nullptr; FAILED_DEBUG_BREAK(dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory5))) if (nullptr != dxgiFactory5) { BOOL allowTearing = FALSE; if (SUCCEEDED(dxgiFactory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing, sizeof(allowTearing)))) { mAllowTearing = true; } dxgiFactory5->Release(); } } // Release references dxgiAdapter->Release(); dxgiDevice->Release(); } // Get the width and height of the given native window and ensure they are never ever zero // -> See "getSafeWidthAndHeight()"-method comments for details long width = 1; long height = 1; { // Get the client rectangle of the given native window RECT rect; ::GetClientRect(hWnd, &rect); // Get the width and height... width = rect.right - rect.left; height = rect.bottom - rect.top; // ... and ensure that none of them is ever zero if (width < 1) { width = 1; } if (height < 1) { height = 1; } } { // Create the swap chain UINT bufferCount = 1; DXGI_SWAP_EFFECT swapEffect = DXGI_SWAP_EFFECT_DISCARD; const bool isWindows8OrGreater = ::IsWindows8OrGreater(); if (isWindows10OrGreater) { RHI_ASSERT(direct3D11Rhi.getContext(), d3d11RenderPass.getNumberOfMultisamples() == 1, "Direct3D 11 doesn't support multisampling if the flip model vertical synchronization is used") bufferCount = 2; swapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; } else if (isWindows8OrGreater) { RHI_ASSERT(direct3D11Rhi.getContext(), d3d11RenderPass.getNumberOfMultisamples() == 1, "Direct3D 11 doesn't support multisampling if the flip model vertical synchronization is used") bufferCount = 2; swapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; } // Quote from https://msdn.microsoft.com/de-de/library/windows/desktop/hh404557(v=vs.85).aspx : "Platform Update for Windows 7: DXGI_SCALING_NONE is not supported on Windows 7 or Windows Server 2008 R2" if (direct3D11Rhi.getD3DFeatureLevel() == D3D_FEATURE_LEVEL_11_1 && nullptr != dxgiFactory2 && isWindows8OrGreater) { // Fill DXGI swap chain description DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = {}; dxgiSwapChainDesc1.Width = static_cast<UINT>(width); dxgiSwapChainDesc1.Height = static_cast<UINT>(height); dxgiSwapChainDesc1.Format = Mapping::getDirect3D11Format(d3d11RenderPass.getColorAttachmentTextureFormat(0)); dxgiSwapChainDesc1.SampleDesc.Count = 1; dxgiSwapChainDesc1.SampleDesc.Quality = 0; dxgiSwapChainDesc1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; dxgiSwapChainDesc1.BufferCount = bufferCount; dxgiSwapChainDesc1.SwapEffect = swapEffect; dxgiSwapChainDesc1.Flags = mAllowTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0u; // Fill DXGI swap chain fullscreen description DXGI_SWAP_CHAIN_FULLSCREEN_DESC dxgiSwapChainFullscreenDesc = {}; dxgiSwapChainFullscreenDesc.RefreshRate.Numerator = 60; dxgiSwapChainFullscreenDesc.RefreshRate.Denominator = 1; dxgiSwapChainFullscreenDesc.Windowed = TRUE; // Create swap chain IDXGISwapChain1* dxgiSwapChain = nullptr; FAILED_DEBUG_BREAK(dxgiFactory2->CreateSwapChainForHwnd(d3d11Device, hWnd, &dxgiSwapChainDesc1, &dxgiSwapChainFullscreenDesc, nullptr, &dxgiSwapChain)) mDxgiSwapChain = reinterpret_cast<IDXGISwapChain*>(dxgiSwapChain); } else { // Fill DXGI swap chain description DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc = {}; dxgiSwapChainDesc.BufferCount = bufferCount; dxgiSwapChainDesc.BufferDesc.Width = static_cast<UINT>(width); dxgiSwapChainDesc.BufferDesc.Height = static_cast<UINT>(height); dxgiSwapChainDesc.BufferDesc.Format = Mapping::getDirect3D11Format(d3d11RenderPass.getColorAttachmentTextureFormat(0)); dxgiSwapChainDesc.BufferDesc.RefreshRate.Numerator = 60; dxgiSwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; dxgiSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; dxgiSwapChainDesc.OutputWindow = hWnd; dxgiSwapChainDesc.SampleDesc.Count = 1; dxgiSwapChainDesc.SampleDesc.Quality = 0; dxgiSwapChainDesc.Windowed = TRUE; dxgiSwapChainDesc.SwapEffect = swapEffect; dxgiSwapChainDesc.Flags = mAllowTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0u; // Create swap chain FAILED_DEBUG_BREAK(dxgiFactory1->CreateSwapChain(d3d11Device, &dxgiSwapChainDesc, &mDxgiSwapChain)) } } // Disable alt-return for automatic fullscreen state change // -> We handle this manually to have more control over it FAILED_DEBUG_BREAK(dxgiFactory1->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER)) // Release our DXGI factory dxgiFactory1->Release(); dxgiFactory2->Release(); // Create the Direct3D 11 views if (nullptr != mDxgiSwapChain) { createDirect3D11Views(); // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Swap chain", 13) // 13 = "Swap chain: " including terminating zero FAILED_DEBUG_BREAK(mDxgiSwapChain->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) if (nullptr != mD3D11RenderTargetView) { FAILED_DEBUG_BREAK(mD3D11RenderTargetView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } if (nullptr != mD3D11DepthStencilView) { FAILED_DEBUG_BREAK(mD3D11DepthStencilView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } } /** * @brief * Destructor */ virtual ~SwapChain() override { // "DXGI Overview - Destroying a Swap Chain" at MSDN http://msdn.microsoft.com/en-us/library/bb205075.aspx states // "You may not release a swap chain in full-screen mode because doing so may create thread contention (which will // cause DXGI to raise a non-continuable exception). Before releasing a swap chain, first switch to windowed mode // (using IDXGISwapChain::SetFullscreenState( FALSE, NULL )) and then call IUnknown::Release." if (getFullscreenState()) { setFullscreenState(false); } // Release the used resources if (nullptr != mD3D11DepthStencilView) { mD3D11DepthStencilView->Release(); } if (nullptr != mD3D11RenderTargetView) { mD3D11RenderTargetView->Release(); } if (nullptr != mDxgiSwapChain) { mDxgiSwapChain->Release(); } if (nullptr != mD3D11DeviceContext1) { mD3D11DeviceContext1->Release(); } // After releasing references to these resources, we need to call "Flush()" to ensure that Direct3D also releases any references it might still have to the same resources - such as pipeline bindings static_cast<Direct3D11Rhi&>(getRhi()).getD3D11DeviceContext()->Flush(); } /** * @brief * Return the DXGI swap chain instance * * @return * The DXGI swap chain instance, null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline IDXGISwapChain* getDxgiSwapChain() const { return mDxgiSwapChain; } /** * @brief * Return the Direct3D 11 render target view instance * * @return * The Direct3D 11 render target view instance, null pointer on error, do not release the returned instance unless you added an own reference to it * * @note * - It's highly recommended to not keep any references to the returned instance, else issues may occur when resizing the swap chain */ [[nodiscard]] inline ID3D11RenderTargetView* getD3D11RenderTargetView() const { return mD3D11RenderTargetView; } /** * @brief * Return the Direct3D 11 depth stencil view instance * * @return * The Direct3D 11 depth stencil view instance, null pointer on error, do not release the returned instance unless you added an own reference to it * * @note * - It's highly recommended to not keep any references to the returned instance, else issues may occur when resizing the swap chain */ [[nodiscard]] inline ID3D11DepthStencilView* getD3D11DepthStencilView() const { return mD3D11DepthStencilView; } //[-------------------------------------------------------] //[ Public virtual Rhi::IRenderTarget methods ] //[-------------------------------------------------------] public: virtual void getWidthAndHeight(uint32_t& width, uint32_t& height) const override { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { // Get the Direct3D 11 swap chain description DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc; FAILED_DEBUG_BREAK(mDxgiSwapChain->GetDesc(&dxgiSwapChainDesc)) // Get the width and height long swapChainWidth = 1; long swapChainHeight = 1; { // Get the client rectangle of the native output window // -> Don't use the width and height stored in "DXGI_SWAP_CHAIN_DESC" -> "DXGI_MODE_DESC" // because it might have been modified in order to avoid zero values RECT rect; ::GetClientRect(dxgiSwapChainDesc.OutputWindow, &rect); // Get the width and height... swapChainWidth = rect.right - rect.left; swapChainHeight = rect.bottom - rect.top; // ... and ensure that none of them is ever zero if (swapChainWidth < 1) { swapChainWidth = 1; } if (swapChainHeight < 1) { swapChainHeight = 1; } } // Write out the width and height width = static_cast<UINT>(swapChainWidth); height = static_cast<UINT>(swapChainHeight); } else { // Set known default return values width = 1; height = 1; } } //[-------------------------------------------------------] //[ Public virtual Rhi::ISwapChain methods ] //[-------------------------------------------------------] public: [[nodiscard]] virtual Rhi::handle getNativeWindowHandle() const override { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { // Get the Direct3D 11 swap chain description DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc; FAILED_DEBUG_BREAK(mDxgiSwapChain->GetDesc(&dxgiSwapChainDesc)) // Return the native window handle return reinterpret_cast<Rhi::handle>(dxgiSwapChainDesc.OutputWindow); } // Error! return NULL_HANDLE; } inline virtual void setVerticalSynchronizationInterval(uint32_t synchronizationInterval) override { mSynchronizationInterval = synchronizationInterval; } virtual void present() override { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { // TODO(co) "!getFullscreenState()": Add support for borderless window to get rid of this const Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRenderPass().getRhi()); const UINT flags = ((mAllowTearing && 0 == mSynchronizationInterval && !getFullscreenState()) ? DXGI_PRESENT_ALLOW_TEARING : 0); handleDeviceLost(direct3D11Rhi, mDxgiSwapChain->Present(mSynchronizationInterval, flags)); // Discard the contents of the render target // -> This is a valid operation only when the existing contents will be entirely overwritten. If dirty or scroll rectangles are used, this call should be removed. if (nullptr != mD3D11DeviceContext1) { mD3D11DeviceContext1->DiscardView(mD3D11RenderTargetView); if (nullptr != mD3D11DepthStencilView) { // Discard the contents of the depth stencil mD3D11DeviceContext1->DiscardView(mD3D11DepthStencilView); } } } } virtual void resizeBuffers() override { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Get the currently set render target Rhi::IRenderTarget* renderTargetBackup = direct3D11Rhi.omGetRenderTarget(); // In case this swap chain is the current render target, we have to unset it before continuing if (this == renderTargetBackup) { direct3D11Rhi.setGraphicsRenderTarget(nullptr); } else { renderTargetBackup = nullptr; } // Release the views if (nullptr != mD3D11DepthStencilView) { mD3D11DepthStencilView->Release(); mD3D11DepthStencilView = nullptr; } if (nullptr != mD3D11RenderTargetView) { mD3D11RenderTargetView->Release(); mD3D11RenderTargetView = nullptr; } // Get the swap chain width and height, ensures they are never ever zero UINT width = 1; UINT height = 1; getSafeWidthAndHeight(width, height); // Resize the Direct3D 11 swap chain // -> Preserve the existing buffer count and format const HRESULT result = mDxgiSwapChain->ResizeBuffers(0, width, height, DXGI_FORMAT_UNKNOWN, mAllowTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0u); if (SUCCEEDED(result)) { // Create the Direct3D 11 views // TODO(co) Rescue and reassign the resource debug name createDirect3D11Views(); // If required, restore the previously set render target if (nullptr != renderTargetBackup) { direct3D11Rhi.setGraphicsRenderTarget(renderTargetBackup); } } else { handleDeviceLost(direct3D11Rhi, result); } } } [[nodiscard]] virtual bool getFullscreenState() const override { // Window mode by default BOOL fullscreen = FALSE; // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { FAILED_DEBUG_BREAK(mDxgiSwapChain->GetFullscreenState(&fullscreen, nullptr)) } // Done return (FALSE != fullscreen); } virtual void setFullscreenState(bool fullscreen) override { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { FAILED_DEBUG_BREAK(mDxgiSwapChain->SetFullscreenState(fullscreen, nullptr)) } } inline virtual void setRenderWindow([[maybe_unused]] Rhi::IRenderWindow* renderWindow) override { // TODO(sw) implement me } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), SwapChain, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit SwapChain(const SwapChain& source) = delete; SwapChain& operator =(const SwapChain& source) = delete; /** * @brief * Return the swap chain width and height * * @param[out] width * Receives the swap chain width * @param[out] height * Receives the swap chain height * * @remarks * For instance "IDXGISwapChain::ResizeBuffers()" can automatically choose the width and height to match the client * rectangle of the native window, but as soon as the width or height is zero we will get the error message * "DXGI Error: The buffer height inferred from the output window is zero. Taking 8 as a reasonable default instead" * "D3D11: ERROR: ID3D11Device::CreateTexture2D: The Dimensions are invalid. For feature level D3D_FEATURE_LEVEL_11_0, * the Width (value = 116) must be between 1 and 16384, inclusively. The Height (value = 0) must be between 1 and 16384, * inclusively. And, the ArraySize (value = 1) must be between 1 and 2048, inclusively. [ STATE_CREATION ERROR #101: CREATETEXTURE2D_INVALIDDIMENSIONS ]" * including an evil memory leak. So, best to use this method which gets the width and height of the native output * window manually and ensures it's never zero. * * @note * - "mDxgiSwapChain" must be valid when calling this method */ void getSafeWidthAndHeight(uint32_t& width, uint32_t& height) const { // Get the Direct3D 11 swap chain description DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc; FAILED_DEBUG_BREAK(mDxgiSwapChain->GetDesc(&dxgiSwapChainDesc)) // Get the client rectangle of the native output window RECT rect; ::GetClientRect(dxgiSwapChainDesc.OutputWindow, &rect); // Get the width and height... long swapChainWidth = rect.right - rect.left; long swapChainHeight = rect.bottom - rect.top; // ... and ensure that none of them is ever zero if (swapChainWidth < 1) { swapChainWidth = 1; } if (swapChainHeight < 1) { swapChainHeight = 1; } // Write out the width and height width = static_cast<UINT>(swapChainWidth); height = static_cast<UINT>(swapChainHeight); } /** * @brief * Create the Direct3D 11 views */ void createDirect3D11Views() { // Create a render target view ID3D11Texture2D* d3d11Texture2DBackBuffer = nullptr; FAILED_DEBUG_BREAK(mDxgiSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(&d3d11Texture2DBackBuffer))) // Get the Direct3D 11 device instance ID3D11Device* d3d11Device = static_cast<Direct3D11Rhi&>(getRhi()).getD3D11Device(); // Create a render target view FAILED_DEBUG_BREAK(d3d11Device->CreateRenderTargetView(d3d11Texture2DBackBuffer, nullptr, &mD3D11RenderTargetView)) d3d11Texture2DBackBuffer->Release(); // Create depth stencil texture const Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat = static_cast<RenderPass&>(getRenderPass()).getDepthStencilAttachmentTextureFormat(); if (Rhi::TextureFormat::Enum::UNKNOWN != depthStencilAttachmentTextureFormat) { // Get the swap chain width and height, ensures they are never ever zero UINT width = 1; UINT height = 1; getSafeWidthAndHeight(width, height); // Create depth stencil texture ID3D11Texture2D* d3d11Texture2DDepthStencil = nullptr; D3D11_TEXTURE2D_DESC d3d11Texture2DDesc = {}; d3d11Texture2DDesc.Width = width; d3d11Texture2DDesc.Height = height; d3d11Texture2DDesc.MipLevels = 1; d3d11Texture2DDesc.ArraySize = 1; d3d11Texture2DDesc.Format = Mapping::getDirect3D11Format(depthStencilAttachmentTextureFormat); d3d11Texture2DDesc.SampleDesc.Count = 1; d3d11Texture2DDesc.SampleDesc.Quality = 0; d3d11Texture2DDesc.Usage = D3D11_USAGE_DEFAULT; d3d11Texture2DDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; d3d11Texture2DDesc.CPUAccessFlags = 0; d3d11Texture2DDesc.MiscFlags = 0; FAILED_DEBUG_BREAK(d3d11Device->CreateTexture2D(&d3d11Texture2DDesc, nullptr, &d3d11Texture2DDepthStencil)) // Create the depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC d3d11DepthStencilViewDesc = {}; d3d11DepthStencilViewDesc.Format = d3d11Texture2DDesc.Format; d3d11DepthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; d3d11DepthStencilViewDesc.Texture2D.MipSlice = 0; FAILED_DEBUG_BREAK(d3d11Device->CreateDepthStencilView(d3d11Texture2DDepthStencil, &d3d11DepthStencilViewDesc, &mD3D11DepthStencilView)) d3d11Texture2DDepthStencil->Release(); } } //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11DeviceContext1* mD3D11DeviceContext1; IDXGISwapChain* mDxgiSwapChain; ///< The DXGI swap chain instance, null pointer on error ID3D11RenderTargetView* mD3D11RenderTargetView; ///< The Direct3D 11 render target view instance, null pointer on error ID3D11DepthStencilView* mD3D11DepthStencilView; ///< The Direct3D 11 depth stencil view instance, null pointer on error uint32_t mSynchronizationInterval; bool mAllowTearing; }; //[-------------------------------------------------------] //[ Direct3D11Rhi/RenderTarget/Framebuffer.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 framebuffer class */ class Framebuffer final : public Rhi::IFramebuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] renderPass * Render pass to use, the swap chain keeps a reference to the render pass * @param[in] colorFramebufferAttachments * The color render target textures, can be a null pointer or can contain null pointers, if not a null pointer there must be at * least "Rhi::IRenderPass::getNumberOfColorAttachments()" textures in the provided C-array of pointers * @param[in] depthStencilFramebufferAttachment * The depth stencil render target texture, can be a null pointer * * @note * - The framebuffer keeps a reference to the provided texture instances */ Framebuffer(Rhi::IRenderPass& renderPass, const Rhi::FramebufferAttachment* colorFramebufferAttachments, const Rhi::FramebufferAttachment* depthStencilFramebufferAttachment RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IFramebuffer(renderPass RHI_RESOURCE_DEBUG_PASS_PARAMETER), mNumberOfColorTextures(static_cast<RenderPass&>(renderPass).getNumberOfColorAttachments()), mColorTextures(nullptr), // Set below mDepthStencilTexture(nullptr), mWidth(UINT_MAX), mHeight(UINT_MAX), mD3D11RenderTargetViews(nullptr), mD3D11DepthStencilView(nullptr) { // The Direct3D 11 "ID3D11DeviceContext::OMSetRenderTargets method"-documentation at MSDN http://msdn.microsoft.com/en-us/library/windows/desktop/ff476464%28v=vs.85%29.aspx // says the following about the framebuffer width and height when using multiple render targets // "All render targets must have the same size in all dimensions (width and height, and depth for 3D or array size for *Array types)" // So, in here I use the smallest width and height as the size of the framebuffer and let Direct3D 11 handle the rest regarding errors. // Add a reference to the used color textures const Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(renderPass.getRhi()); const Rhi::Context& context = direct3D11Rhi.getContext(); if (mNumberOfColorTextures > 0) { mColorTextures = RHI_MALLOC_TYPED(context, Rhi::ITexture*, mNumberOfColorTextures); mD3D11RenderTargetViews = RHI_MALLOC_TYPED(context, ID3D11RenderTargetView*, mNumberOfColorTextures); // Loop through all color textures ID3D11RenderTargetView** d3d11RenderTargetView = mD3D11RenderTargetViews; Rhi::ITexture** colorTexturesEnd = mColorTextures + mNumberOfColorTextures; for (Rhi::ITexture** colorTexture = mColorTextures; colorTexture < colorTexturesEnd; ++colorTexture, ++colorFramebufferAttachments, ++d3d11RenderTargetView) { // Sanity check RHI_ASSERT(context, nullptr != colorFramebufferAttachments->texture, "Invalid Direct3D 11 color framebuffer attachment texture") // TODO(co) Add security check: Is the given resource one of the currently used RHI? *colorTexture = colorFramebufferAttachments->texture; (*colorTexture)->addReference(); // Evaluate the color texture type switch ((*colorTexture)->getResourceType()) { case Rhi::ResourceType::TEXTURE_2D: { const Texture2D* texture2D = static_cast<Texture2D*>(*colorTexture); // Sanity checks RHI_ASSERT(context, colorFramebufferAttachments->mipmapIndex < Texture2D::getNumberOfMipmaps(texture2D->getWidth(), texture2D->getHeight()), "Invalid Direct3D 11 color framebuffer attachment mipmap index") RHI_ASSERT(context, 0 == colorFramebufferAttachments->layerIndex, "Invalid Direct3D 11 color framebuffer attachment layer index") // Update the framebuffer width and height if required ::detail::updateWidthHeight(colorFramebufferAttachments->mipmapIndex, texture2D->getWidth(), texture2D->getHeight(), mWidth, mHeight); // Create the Direct3D 11 render target view instance D3D11_RENDER_TARGET_VIEW_DESC d3d11RenderTargetViewDesc = {}; d3d11RenderTargetViewDesc.Format = Mapping::getDirect3D11Format(texture2D->getTextureFormat()); d3d11RenderTargetViewDesc.ViewDimension = (texture2D->getNumberOfMultisamples() > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D; d3d11RenderTargetViewDesc.Texture2D.MipSlice = colorFramebufferAttachments->mipmapIndex; FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateRenderTargetView(texture2D->getD3D11Texture2D(), &d3d11RenderTargetViewDesc, d3d11RenderTargetView)) break; } case Rhi::ResourceType::TEXTURE_2D_ARRAY: { // Update the framebuffer width and height if required const Texture2DArray* texture2DArray = static_cast<Texture2DArray*>(*colorTexture); ::detail::updateWidthHeight(colorFramebufferAttachments->mipmapIndex, texture2DArray->getWidth(), texture2DArray->getHeight(), mWidth, mHeight); // Create the Direct3D 11 render target view instance D3D11_RENDER_TARGET_VIEW_DESC d3d11RenderTargetViewDesc = {}; d3d11RenderTargetViewDesc.Format = Mapping::getDirect3D11Format(texture2DArray->getTextureFormat()); d3d11RenderTargetViewDesc.ViewDimension = (texture2DArray->getNumberOfMultisamples() > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY : D3D11_RTV_DIMENSION_TEXTURE2DARRAY; d3d11RenderTargetViewDesc.Texture2DArray.MipSlice = colorFramebufferAttachments->mipmapIndex; d3d11RenderTargetViewDesc.Texture2DArray.FirstArraySlice = colorFramebufferAttachments->layerIndex; d3d11RenderTargetViewDesc.Texture2DArray.ArraySize = 1; FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateRenderTargetView(texture2DArray->getD3D11Texture2D(), &d3d11RenderTargetViewDesc, d3d11RenderTargetView)) break; } case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::TEXTURE_BUFFER: case Rhi::ResourceType::STRUCTURED_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::TEXTURE_1D: case Rhi::ResourceType::TEXTURE_1D_ARRAY: case Rhi::ResourceType::TEXTURE_3D: case Rhi::ResourceType::TEXTURE_CUBE: case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: default: RHI_ASSERT(direct3D11Rhi.getContext(), false, "The type of the given color texture at index %u is not supported by the Direct3D 11 RHI implementation", colorTexture - mColorTextures) *d3d11RenderTargetView = nullptr; break; } } } // Add a reference to the used depth stencil texture if (nullptr != depthStencilFramebufferAttachment) { mDepthStencilTexture = depthStencilFramebufferAttachment->texture; RHI_ASSERT(context, nullptr != mDepthStencilTexture, "Invalid Direct3D 11 depth stencil framebuffer attachment texture") mDepthStencilTexture->addReference(); // Evaluate the depth stencil texture type switch (mDepthStencilTexture->getResourceType()) { case Rhi::ResourceType::TEXTURE_2D: { const Texture2D* texture2D = static_cast<Texture2D*>(mDepthStencilTexture); // Sanity checks RHI_ASSERT(context, depthStencilFramebufferAttachment->mipmapIndex < Texture2D::getNumberOfMipmaps(texture2D->getWidth(), texture2D->getHeight()), "Invalid Direct3D 11 depth stencil framebuffer attachment mipmap index") RHI_ASSERT(context, 0 == depthStencilFramebufferAttachment->layerIndex, "Invalid Direct3D 11 depth stencil framebuffer attachment layer index") // Update the framebuffer width and height if required ::detail::updateWidthHeight(depthStencilFramebufferAttachment->mipmapIndex, texture2D->getWidth(), texture2D->getHeight(), mWidth, mHeight); // Create the Direct3D 11 render target view instance D3D11_DEPTH_STENCIL_VIEW_DESC d3d11DepthStencilViewDesc = {}; d3d11DepthStencilViewDesc.Format = Mapping::getDirect3D11Format(texture2D->getTextureFormat()); d3d11DepthStencilViewDesc.ViewDimension = (texture2D->getNumberOfMultisamples() > 1) ? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D; d3d11DepthStencilViewDesc.Texture2D.MipSlice = depthStencilFramebufferAttachment->mipmapIndex; FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateDepthStencilView(texture2D->getD3D11Texture2D(), &d3d11DepthStencilViewDesc, &mD3D11DepthStencilView)) break; } case Rhi::ResourceType::TEXTURE_2D_ARRAY: { // Update the framebuffer width and height if required const Texture2DArray* texture2DArray = static_cast<Texture2DArray*>(mDepthStencilTexture); ::detail::updateWidthHeight(depthStencilFramebufferAttachment->mipmapIndex, texture2DArray->getWidth(), texture2DArray->getHeight(), mWidth, mHeight); // Create the Direct3D 11 render target view instance D3D11_DEPTH_STENCIL_VIEW_DESC d3d11DepthStencilViewDesc = {}; d3d11DepthStencilViewDesc.Format = Mapping::getDirect3D11Format(texture2DArray->getTextureFormat()); d3d11DepthStencilViewDesc.ViewDimension = (texture2DArray->getNumberOfMultisamples() > 1) ? D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY : D3D11_DSV_DIMENSION_TEXTURE2DARRAY; d3d11DepthStencilViewDesc.Texture2DArray.MipSlice = depthStencilFramebufferAttachment->mipmapIndex; d3d11DepthStencilViewDesc.Texture2DArray.FirstArraySlice = depthStencilFramebufferAttachment->layerIndex; d3d11DepthStencilViewDesc.Texture2DArray.ArraySize = 1; FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateDepthStencilView(texture2DArray->getD3D11Texture2D(), &d3d11DepthStencilViewDesc, &mD3D11DepthStencilView)) break; } case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::TEXTURE_BUFFER: case Rhi::ResourceType::STRUCTURED_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::TEXTURE_1D: case Rhi::ResourceType::TEXTURE_1D_ARRAY: case Rhi::ResourceType::TEXTURE_3D: case Rhi::ResourceType::TEXTURE_CUBE: case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: default: RHI_ASSERT(direct3D11Rhi.getContext(), false, "The type of the given depth stencil texture is not supported by the Direct3D 11 RHI implementation") break; } } // Validate the framebuffer width and height if (0 == mWidth || UINT_MAX == mWidth) { RHI_ASSERT(context, false, "Invalid Direct3D 11 framebuffer width") mWidth = 1; } if (0 == mHeight || UINT_MAX == mHeight) { RHI_ASSERT(context, false, "Invalid Direct3D 11 framebuffer height") mHeight = 1; } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "FBO", 6) // 6 = "FBO: " including terminating zero const size_t detailedDebugNameLength = strlen(detailedDebugName); { // Assign a debug name to the Direct3D 11 render target view, do also add the index to the name const size_t adjustedDetailedDebugNameLength = detailedDebugNameLength + 5; // Direct3D 11 supports 8 render targets ("D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT", so: One digit + one [ + one ] + one space + terminating zero = 5 characters) char* nameWithIndex = RHI_MALLOC_TYPED(context, char, adjustedDetailedDebugNameLength); ID3D11RenderTargetView** d3d11RenderTargetViewsEnd = mD3D11RenderTargetViews + mNumberOfColorTextures; for (ID3D11RenderTargetView** d3d11RenderTargetView = mD3D11RenderTargetViews; d3d11RenderTargetView < d3d11RenderTargetViewsEnd; ++d3d11RenderTargetView) { sprintf_s(nameWithIndex, adjustedDetailedDebugNameLength, "%s [%u]", detailedDebugName, static_cast<uint32_t>(d3d11RenderTargetView - mD3D11RenderTargetViews)); FAILED_DEBUG_BREAK((*d3d11RenderTargetView)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(adjustedDetailedDebugNameLength), nameWithIndex)) } RHI_FREE(context, nameWithIndex); } // Assign a debug name to the Direct3D 11 depth stencil view if (nullptr != mD3D11DepthStencilView) { FAILED_DEBUG_BREAK(mD3D11DepthStencilView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(detailedDebugNameLength), detailedDebugName)) } #endif } /** * @brief * Destructor */ virtual ~Framebuffer() override { // Release the reference to the used color textures const Rhi::Context& context = getRhi().getContext(); if (nullptr != mD3D11RenderTargetViews) { // Release references ID3D11RenderTargetView** d3d11RenderTargetViewsEnd = mD3D11RenderTargetViews + mNumberOfColorTextures; for (ID3D11RenderTargetView** d3d11RenderTargetView = mD3D11RenderTargetViews; d3d11RenderTargetView < d3d11RenderTargetViewsEnd; ++d3d11RenderTargetView) { (*d3d11RenderTargetView)->Release(); } // Cleanup RHI_FREE(context, mD3D11RenderTargetViews); } if (nullptr != mColorTextures) { // Release references Rhi::ITexture** colorTexturesEnd = mColorTextures + mNumberOfColorTextures; for (Rhi::ITexture** colorTexture = mColorTextures; colorTexture < colorTexturesEnd; ++colorTexture) { (*colorTexture)->releaseReference(); } // Cleanup RHI_FREE(context, mColorTextures); } // Release the reference to the used depth stencil texture if (nullptr != mD3D11DepthStencilView) { // Release reference mD3D11DepthStencilView->Release(); } if (nullptr != mDepthStencilTexture) { // Release reference mDepthStencilTexture->releaseReference(); } } /** * @brief * Return the number of color textures * * @return * The number of color textures */ [[nodiscard]] inline uint32_t getNumberOfColorTextures() const { return mNumberOfColorTextures; } /** * @brief * Return the color textures * * @return * The color textures, can be a null pointer, do not release the returned instances unless you added an own reference to it */ [[nodiscard]] inline Rhi::ITexture** getColorTextures() const { return mColorTextures; } /** * @brief * Return the depth stencil texture * * @return * The depth stencil texture, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline Rhi::ITexture* getDepthStencilTexture() const { return mDepthStencilTexture; } /** * @brief * Return the Direct3D 11 render target views * * @return * The Direct3D 11 render target views, can be a null pointer, do not release the returned instances unless you added an own reference to it */ [[nodiscard]] inline ID3D11RenderTargetView** getD3D11RenderTargetViews() const { return mD3D11RenderTargetViews; } /** * @brief * Return the Direct3D 11 depth stencil view * * @return * The Direct3D 11 depth stencil view, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11DepthStencilView* getD3D11DepthStencilView() const { return mD3D11DepthStencilView; } //[-------------------------------------------------------] //[ Public virtual Rhi::IRenderTarget methods ] //[-------------------------------------------------------] public: inline virtual void getWidthAndHeight(uint32_t& width, uint32_t& height) const override { // No fancy implementation in here, just copy over the internal information width = mWidth; height = mHeight; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Framebuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Framebuffer(const Framebuffer& source) = delete; Framebuffer& operator =(const Framebuffer& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: // Generic part uint32_t mNumberOfColorTextures; ///< Number of color render target textures Rhi::ITexture** mColorTextures; ///< The color render target textures (we keep a reference to it), can be a null pointer or can contain null pointers, if not a null pointer there must be at least "m_nNumberOfColorTextures" textures in the provided C-array of pointers Rhi::ITexture* mDepthStencilTexture; ///< The depth stencil render target texture (we keep a reference to it), can be a null pointer uint32_t mWidth; ///< The framebuffer width uint32_t mHeight; ///< The framebuffer height // Direct3D 11 part ID3D11RenderTargetView** mD3D11RenderTargetViews; ///< The Direct3D 11 render target views (we keep a reference to it), can be a null pointer or can contain null pointers, if not a null pointer there must be at least "m_nNumberOfColorTextures" views in the provided C-array of pointers ID3D11DepthStencilView* mD3D11DepthStencilView; ///< The Direct3D 11 depth stencil view (we keep a reference to it), can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Shader/VertexShaderHlsl.h ] //[-------------------------------------------------------] /** * @brief * HLSL vertex shader class */ class VertexShaderHlsl final : public Rhi::IVertexShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor for creating a vertex shader from shader bytecode * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] shaderBytecode * Shader bytecode */ VertexShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IVertexShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3DBlobVertexShader(nullptr), mD3D11VertexShader(nullptr) { // Backup the vertex shader bytecode D3DCreateBlob(shaderBytecode.getNumberOfBytes(), &mD3DBlobVertexShader); memcpy(mD3DBlobVertexShader->GetBufferPointer(), shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes()); // Create the Direct3D 11 vertex shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateVertexShader(shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes(), nullptr, &mD3D11VertexShader)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11VertexShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "VS", 5) // 5 = "VS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11VertexShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Constructor for creating a vertex shader from shader source code * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] sourceCode * Shader ASCII source code, must be valid */ VertexShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IVertexShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3DBlobVertexShader(nullptr), mD3D11VertexShader(nullptr) { // Create the Direct3D 11 binary large object for the vertex shader mD3DBlobVertexShader = loadShaderFromSourcecode(direct3D11Rhi.getContext(), "vs_5_0", sourceCode, nullptr, optimizationLevel); if (nullptr != mD3DBlobVertexShader) { // Create the Direct3D 11 vertex shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateVertexShader(mD3DBlobVertexShader->GetBufferPointer(), mD3DBlobVertexShader->GetBufferSize(), nullptr, &mD3D11VertexShader)) // Return shader bytecode, if requested do to so if (nullptr != shaderBytecode) { shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(mD3DBlobVertexShader->GetBufferSize()), static_cast<uint8_t*>(mD3DBlobVertexShader->GetBufferPointer())); } // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11VertexShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "VS", 5) // 5 = "VS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11VertexShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } } /** * @brief * Destructor */ virtual ~VertexShaderHlsl() override { // Release the Direct3D 11 shader binary large object if (nullptr != mD3DBlobVertexShader) { mD3DBlobVertexShader->Release(); } // Release the Direct3D 11 vertex shader if (nullptr != mD3D11VertexShader) { mD3D11VertexShader->Release(); } } /** * @brief * Return the Direct3D 11 vertex shader blob * * @return * Direct3D 11 vertex shader blob, can be a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3DBlob* getD3DBlobVertexShader() const { return mD3DBlobVertexShader; } /** * @brief * Return the Direct3D 11 vertex shader * * @return * Direct3D 11 vertex shader, can be a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11VertexShader* getD3D11VertexShader() const { return mD3D11VertexShader; } //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::HLSL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), VertexShaderHlsl, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit VertexShaderHlsl(const VertexShaderHlsl& source) = delete; VertexShaderHlsl& operator =(const VertexShaderHlsl& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3DBlob* mD3DBlobVertexShader; ///< Direct3D 11 vertex shader blob, can be a null pointer ID3D11VertexShader* mD3D11VertexShader; ///< Direct3D 11 vertex shader, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Shader/TessellationControlShaderHlsl.h ] //[-------------------------------------------------------] /** * @brief * HLSL tessellation control shader ("hull shader" in Direct3D terminology) class */ class TessellationControlShaderHlsl final : public Rhi::ITessellationControlShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor for creating a tessellation control shader ("hull shader" in Direct3D terminology) from shader bytecode * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] shaderBytecode * Shader bytecode */ TessellationControlShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITessellationControlShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11HullShader(nullptr) { // Create the Direct3D 11 hull shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateHullShader(shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes(), nullptr, &mD3D11HullShader)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11HullShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "TCS", 6) // 6 = "TCS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11HullShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Constructor for creating a tessellation control shader ("hull shader" in Direct3D terminology) from shader source code * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] sourceCode * Shader ASCII source code, must be valid */ TessellationControlShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITessellationControlShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11HullShader(nullptr) { // Create the Direct3D 11 binary large object for the hull shader ID3DBlob* d3dBlob = loadShaderFromSourcecode(direct3D11Rhi.getContext(), "hs_5_0", sourceCode, nullptr, optimizationLevel); if (nullptr != d3dBlob) { // Create the Direct3D 11 hull shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateHullShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), nullptr, &mD3D11HullShader)) // Return shader bytecode, if requested do to so if (nullptr != shaderBytecode) { shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(d3dBlob->GetBufferSize()), static_cast<uint8_t*>(d3dBlob->GetBufferPointer())); } // Release the Direct3D 11 shader binary large object d3dBlob->Release(); // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11HullShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "TCS", 6) // 6 = "TCS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11HullShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } } /** * @brief * Destructor */ virtual ~TessellationControlShaderHlsl() override { // Release the Direct3D 11 hull shader if (nullptr != mD3D11HullShader) { mD3D11HullShader->Release(); } } /** * @brief * Return the Direct3D 11 hull shader * * @return * Direct3D 11 hull shader, can be a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11HullShader* getD3D11HullShader() const { return mD3D11HullShader; } //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::HLSL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TessellationControlShaderHlsl, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TessellationControlShaderHlsl(const TessellationControlShaderHlsl& source) = delete; TessellationControlShaderHlsl& operator =(const TessellationControlShaderHlsl& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11HullShader* mD3D11HullShader; ///< Direct3D 11 hull shader, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Shader/TessellationEvaluationShaderHlsl.h ] //[-------------------------------------------------------] /** * @brief * HLSL tessellation evaluation shader ("domain shader" in Direct3D terminology) class */ class TessellationEvaluationShaderHlsl final : public Rhi::ITessellationEvaluationShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor for creating a tessellation evaluation shader ("domain shader" in Direct3D terminology) from shader bytecode * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] shaderBytecode * Shader bytecode */ TessellationEvaluationShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITessellationEvaluationShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11DomainShader(nullptr) { // Create the Direct3D 11 domain shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateDomainShader(shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes(), nullptr, &mD3D11DomainShader)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11DomainShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "TES", 6) // 6 = "TES: " including terminating zero FAILED_DEBUG_BREAK(mD3D11DomainShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Constructor for creating a tessellation evaluation shader ("domain shader" in Direct3D terminology) from shader source code * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] sourceCode * Shader ASCII source code, must be valid */ TessellationEvaluationShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : ITessellationEvaluationShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11DomainShader(nullptr) { // Create the Direct3D 11 binary large object for the domain shader ID3DBlob* d3dBlob = loadShaderFromSourcecode(direct3D11Rhi.getContext(), "ds_5_0", sourceCode, nullptr, optimizationLevel); if (nullptr != d3dBlob) { // Create the Direct3D 11 domain shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateDomainShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), nullptr, &mD3D11DomainShader)) // Return shader bytecode, if requested do to so if (nullptr != shaderBytecode) { shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(d3dBlob->GetBufferSize()), static_cast<uint8_t*>(d3dBlob->GetBufferPointer())); } // Release the Direct3D 11 shader binary large object d3dBlob->Release(); // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11DomainShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "TES", 6) // 6 = "TES: " including terminating zero FAILED_DEBUG_BREAK(mD3D11DomainShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } } /** * @brief * Destructor */ virtual ~TessellationEvaluationShaderHlsl() override { // Release the Direct3D 11 domain shader if (nullptr != mD3D11DomainShader) { mD3D11DomainShader->Release(); } } /** * @brief * Return the Direct3D 11 domain shader * * @return * Direct3D 11 domain shader, can be a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11DomainShader* getD3D11DomainShader() const { return mD3D11DomainShader; } //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::HLSL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TessellationEvaluationShaderHlsl, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TessellationEvaluationShaderHlsl(const TessellationEvaluationShaderHlsl& source) = delete; TessellationEvaluationShaderHlsl& operator =(const TessellationEvaluationShaderHlsl& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11DomainShader* mD3D11DomainShader; ///< Direct3D 11 domain shader, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Shader/GeometryShaderHlsl.h ] //[-------------------------------------------------------] /** * @brief * HLSL geometry shader class */ class GeometryShaderHlsl final : public Rhi::IGeometryShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor for creating a geometry shader from shader bytecode * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] shaderBytecode * Shader bytecode */ GeometryShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IGeometryShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11GeometryShader(nullptr) { // Create the Direct3D 11 geometry shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateGeometryShader(shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes(), nullptr, &mD3D11GeometryShader)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11GeometryShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "GS", 5) // 5 = "GS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11GeometryShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Constructor for creating a geometry shader from shader source code * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] sourceCode * Shader ASCII source code, must be valid */ GeometryShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IGeometryShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11GeometryShader(nullptr) { // Create the Direct3D 11 binary large object for the geometry shader ID3DBlob* d3dBlob = loadShaderFromSourcecode(direct3D11Rhi.getContext(), "gs_5_0", sourceCode, nullptr, optimizationLevel); if (nullptr != d3dBlob) { // Create the Direct3D 11 geometry shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateGeometryShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), nullptr, &mD3D11GeometryShader)) // Return shader bytecode, if requested do to so if (nullptr != shaderBytecode) { shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(d3dBlob->GetBufferSize()), static_cast<uint8_t*>(d3dBlob->GetBufferPointer())); } // Release the Direct3D 11 shader binary large object d3dBlob->Release(); // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11GeometryShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "GS", 5) // 5 = "GS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11GeometryShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } } /** * @brief * Destructor */ virtual ~GeometryShaderHlsl() override { // Release the Direct3D 11 geometry shader if (nullptr != mD3D11GeometryShader) { mD3D11GeometryShader->Release(); } } /** * @brief * Return the Direct3D 11 geometry shader * * @return * Direct3D 11 geometry shader, can be a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11GeometryShader* getD3D11GeometryShader() const { return mD3D11GeometryShader; } //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::HLSL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), GeometryShaderHlsl, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit GeometryShaderHlsl(const GeometryShaderHlsl& source) = delete; GeometryShaderHlsl& operator =(const GeometryShaderHlsl& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11GeometryShader* mD3D11GeometryShader; ///< Direct3D 11 geometry shader, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Shader/FragmentShaderHlsl.h ] //[-------------------------------------------------------] /** * @brief * HLSL fragment shader ("pixel shader" in Direct3D terminology) class */ class FragmentShaderHlsl final : public Rhi::IFragmentShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor for creating a fragment shader from shader bytecode * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] shaderBytecode * Shader bytecode */ FragmentShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IFragmentShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11PixelShader(nullptr) { // Create the Direct3D 11 pixel shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreatePixelShader(shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes(), nullptr, &mD3D11PixelShader)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11PixelShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "FS", 5) // 5 = "FS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11PixelShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Constructor for creating a fragment shader from shader source code * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] sourceCode * Shader ASCII source code, must be valid */ FragmentShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IFragmentShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11PixelShader(nullptr) { // Create the Direct3D 11 binary large object for the pixel shader ID3DBlob* d3dBlob = loadShaderFromSourcecode(direct3D11Rhi.getContext(), "ps_5_0", sourceCode, nullptr, optimizationLevel); if (nullptr != d3dBlob) { // Create the Direct3D 11 pixel shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreatePixelShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), nullptr, &mD3D11PixelShader)) // Return shader bytecode, if requested do to so if (nullptr != shaderBytecode) { shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(d3dBlob->GetBufferSize()), static_cast<uint8_t*>(d3dBlob->GetBufferPointer())); } // Release the Direct3D 11 shader binary large object d3dBlob->Release(); // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11PixelShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "FS", 5) // 5 = "FS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11PixelShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } } /** * @brief * Destructor */ virtual ~FragmentShaderHlsl() override { // Release the Direct3D 11 pixel shader if (nullptr != mD3D11PixelShader) { mD3D11PixelShader->Release(); } } /** * @brief * Return the Direct3D 11 pixel shader * * @return * Direct3D 11 pixel shader, can be a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11PixelShader* getD3D11PixelShader() const { return mD3D11PixelShader; } //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::HLSL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), FragmentShaderHlsl, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit FragmentShaderHlsl(const FragmentShaderHlsl& source) = delete; FragmentShaderHlsl& operator =(const FragmentShaderHlsl& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11PixelShader* mD3D11PixelShader; ///< Direct3D 11 pixel shader, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Shader/ComputeShaderHlsl.h ] //[-------------------------------------------------------] /** * @brief * HLSL compute shader (CS) class */ class ComputeShaderHlsl final : public Rhi::IComputeShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor for creating a compute shader from shader bytecode * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] shaderBytecode * Shader bytecode */ ComputeShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IComputeShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11ComputeShader(nullptr) { // Create the Direct3D 11 compute shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateComputeShader(shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes(), nullptr, &mD3D11ComputeShader)) // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11ComputeShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "CS", 5) // 5 = "CS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11ComputeShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } /** * @brief * Constructor for creating a compute shader from shader source code * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] sourceCode * Shader ASCII source code, must be valid */ ComputeShaderHlsl(Direct3D11Rhi& direct3D11Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IComputeShader(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11ComputeShader(nullptr) { // Create the Direct3D 11 binary large object for the compute shader ID3DBlob* d3dBlob = loadShaderFromSourcecode(direct3D11Rhi.getContext(), "cs_5_0", sourceCode, nullptr, optimizationLevel); if (nullptr != d3dBlob) { // Create the Direct3D 11 compute shader FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateComputeShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), nullptr, &mD3D11ComputeShader)) // Return shader bytecode, if requested do to so if (nullptr != shaderBytecode) { shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(d3dBlob->GetBufferSize()), static_cast<uint8_t*>(d3dBlob->GetBufferPointer())); } // Release the Direct3D 11 shader binary large object d3dBlob->Release(); // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11ComputeShader) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "CS", 5) // 5 = "CS: " including terminating zero FAILED_DEBUG_BREAK(mD3D11ComputeShader->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } } /** * @brief * Destructor */ virtual ~ComputeShaderHlsl() override { // Release the Direct3D 11 compute shader if (nullptr != mD3D11ComputeShader) { mD3D11ComputeShader->Release(); } } /** * @brief * Return the Direct3D 11 compute shader * * @return * Direct3D 11 compute shader, can be a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11ComputeShader* getD3D11ComputeShader() const { return mD3D11ComputeShader; } //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::HLSL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), ComputeShaderHlsl, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit ComputeShaderHlsl(const ComputeShaderHlsl& source) = delete; ComputeShaderHlsl& operator =(const ComputeShaderHlsl& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11ComputeShader* mD3D11ComputeShader; ///< Direct3D 11 compute shader, can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Shader/GraphicsProgramHlsl.h ] //[-------------------------------------------------------] /** * @brief * HLSL graphics program class */ class GraphicsProgramHlsl final : public Rhi::IGraphicsProgram { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] vertexShaderHlsl * Vertex shader the graphics program is using, can be a null pointer * @param[in] tessellationControlShaderHlsl * Tessellation control shader the graphics program is using, can be a null pointer * @param[in] tessellationEvaluationShaderHlsl * Tessellation evaluation shader the graphics program is using, can be a null pointer * @param[in] geometryShaderHlsl * Geometry shader the graphics program is using, can be a null pointer * @param[in] fragmentShaderHlsl * Fragment shader the graphics program is using, can be a null pointer * * @note * - The graphics program keeps a reference to the provided shaders and releases it when no longer required */ GraphicsProgramHlsl(Direct3D11Rhi& direct3D11Rhi, VertexShaderHlsl* vertexShaderHlsl, TessellationControlShaderHlsl* tessellationControlShaderHlsl, TessellationEvaluationShaderHlsl* tessellationEvaluationShaderHlsl, GeometryShaderHlsl* geometryShaderHlsl, FragmentShaderHlsl* fragmentShaderHlsl RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IGraphicsProgram(direct3D11Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mVertexShaderHlsl(vertexShaderHlsl), mTessellationControlShaderHlsl(tessellationControlShaderHlsl), mTessellationEvaluationShaderHlsl(tessellationEvaluationShaderHlsl), mGeometryShaderHlsl(geometryShaderHlsl), mFragmentShaderHlsl(fragmentShaderHlsl) { // Add references to the provided shaders if (nullptr != mVertexShaderHlsl) { mVertexShaderHlsl->addReference(); } if (nullptr != mTessellationControlShaderHlsl) { mTessellationControlShaderHlsl->addReference(); } if (nullptr != mTessellationEvaluationShaderHlsl) { mTessellationEvaluationShaderHlsl->addReference(); } if (nullptr != mGeometryShaderHlsl) { mGeometryShaderHlsl->addReference(); } if (nullptr != mFragmentShaderHlsl) { mFragmentShaderHlsl->addReference(); } } /** * @brief * Destructor */ virtual ~GraphicsProgramHlsl() override { // Release the shader references if (nullptr != mVertexShaderHlsl) { mVertexShaderHlsl->releaseReference(); } if (nullptr != mTessellationControlShaderHlsl) { mTessellationControlShaderHlsl->releaseReference(); } if (nullptr != mTessellationEvaluationShaderHlsl) { mTessellationEvaluationShaderHlsl->releaseReference(); } if (nullptr != mGeometryShaderHlsl) { mGeometryShaderHlsl->releaseReference(); } if (nullptr != mFragmentShaderHlsl) { mFragmentShaderHlsl->releaseReference(); } } /** * @brief * Return the HLSL vertex shader the graphics program is using * * @return * The HLSL vertex shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline VertexShaderHlsl* getVertexShaderHlsl() const { return mVertexShaderHlsl; } /** * @brief * Return the HLSL tessellation control shader the graphics program is using * * @return * The HLSL tessellation control shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline TessellationControlShaderHlsl* getTessellationControlShaderHlsl() const { return mTessellationControlShaderHlsl; } /** * @brief * Return the HLSL tessellation evaluation shader the graphics program is using * * @return * The HLSL tessellation evaluation shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline TessellationEvaluationShaderHlsl* getTessellationEvaluationShaderHlsl() const { return mTessellationEvaluationShaderHlsl; } /** * @brief * Return the HLSL geometry shader the graphics program is using * * @return * The HLSL geometry shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline GeometryShaderHlsl* getGeometryShaderHlsl() const { return mGeometryShaderHlsl; } /** * @brief * Return the HLSL fragment shader the graphics program is using * * @return * The HLSL fragment shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline FragmentShaderHlsl* getFragmentShaderHlsl() const { return mFragmentShaderHlsl; } //[-------------------------------------------------------] //[ Public virtual Rhi::IGraphicsProgram methods ] //[-------------------------------------------------------] public: [[nodiscard]] virtual Rhi::handle getUniformHandle(const char*) override { RHI_ASSERT(getRhi().getContext(), false, "The Direct3D 11 RHI graphics program HLSL implementation doesn't have legacy uniform support") return NULL_HANDLE; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), GraphicsProgramHlsl, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit GraphicsProgramHlsl(const GraphicsProgramHlsl& source) = delete; GraphicsProgramHlsl& operator =(const GraphicsProgramHlsl& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: VertexShaderHlsl* mVertexShaderHlsl; ///< Vertex shader the graphics program is using (we keep a reference to it), can be a null pointer TessellationControlShaderHlsl* mTessellationControlShaderHlsl; ///< Tessellation control shader the graphics program is using (we keep a reference to it), can be a null pointer TessellationEvaluationShaderHlsl* mTessellationEvaluationShaderHlsl; ///< Tessellation evaluation shader the graphics program is using (we keep a reference to it), can be a null pointer GeometryShaderHlsl* mGeometryShaderHlsl; ///< Geometry shader the graphics program is using (we keep a reference to it), can be a null pointer FragmentShaderHlsl* mFragmentShaderHlsl; ///< Fragment shader the graphics program is using (we keep a reference to it), can be a null pointer }; //[-------------------------------------------------------] //[ Direct3D11Rhi/Shader/ShaderLanguageHlsl.h ] //[-------------------------------------------------------] /** * @brief * HLSL shader language class */ class ShaderLanguageHlsl final : public Rhi::IShaderLanguage { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance */ inline explicit ShaderLanguageHlsl(Direct3D11Rhi& direct3D11Rhi) : IShaderLanguage(direct3D11Rhi) {} /** * @brief * Destructor */ inline virtual ~ShaderLanguageHlsl() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShaderLanguage methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::HLSL_NAME; } [[nodiscard]] inline virtual Rhi::IVertexShader* createVertexShaderFromBytecode([[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 11 vertex shader bytecode is invalid") // There's no need to check for "Rhi::Capabilities::vertexShader", we know there's vertex shader support return RHI_NEW(direct3D11Rhi.getContext(), VertexShaderHlsl)(direct3D11Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IVertexShader* createVertexShaderFromSourceCode([[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::vertexShader", we know there's vertex shader support Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), VertexShaderHlsl)(direct3D11Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITessellationControlShader* createTessellationControlShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // "hull shader" in Direct3D terminology Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 11 tessellation control shader bytecode is invalid") // There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation control shader support return RHI_NEW(direct3D11Rhi.getContext(), TessellationControlShaderHlsl)(direct3D11Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITessellationControlShader* createTessellationControlShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // "hull shader" in Direct3D terminology // There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation control shader support Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), TessellationControlShaderHlsl)(direct3D11Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITessellationEvaluationShader* createTessellationEvaluationShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // "domain shader" in Direct3D terminology Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 11 tessellation evaluation shader bytecode is invalid") // There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation evaluation shader support return RHI_NEW(direct3D11Rhi.getContext(), TessellationEvaluationShaderHlsl)(direct3D11Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITessellationEvaluationShader* createTessellationEvaluationShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // "domain shader" in Direct3D terminology // There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation evaluation shader support Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), TessellationEvaluationShaderHlsl)(direct3D11Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IGeometryShader* createGeometryShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 11 geometry shader bytecode is invalid") // There's no need to check for "Rhi::Capabilities::maximumNumberOfGsOutputVertices", we know there's geometry shader support return RHI_NEW(direct3D11Rhi.getContext(), GeometryShaderHlsl)(direct3D11Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IGeometryShader* createGeometryShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::maximumNumberOfGsOutputVertices", we know there's geometry shader support Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), GeometryShaderHlsl)(direct3D11Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IFragmentShader* createFragmentShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 11 fragment shader bytecode is invalid") // There's no need to check for "Rhi::Capabilities::fragmentShader", we know there's fragment shader support return RHI_NEW(direct3D11Rhi.getContext(), FragmentShaderHlsl)(direct3D11Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IFragmentShader* createFragmentShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::fragmentShader", we know there's fragment shader support Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), FragmentShaderHlsl)(direct3D11Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITaskShader* createTaskShaderFromBytecode(const Rhi::ShaderBytecode& RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER) override { RHI_ASSERT(getRhi().getContext(), false, "Direct3D 11 has no task shader support") return nullptr; } [[nodiscard]] inline virtual Rhi::ITaskShader* createTaskShaderFromSourceCode(const Rhi::ShaderSourceCode&, Rhi::ShaderBytecode* = nullptr RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER) override { RHI_ASSERT(getRhi().getContext(), false, "Direct3D 11 has no task shader support") return nullptr; } [[nodiscard]] inline virtual Rhi::IMeshShader* createMeshShaderFromBytecode(const Rhi::ShaderBytecode& RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER) override { RHI_ASSERT(getRhi().getContext(), false, "Direct3D 11 has no mesh shader support") return nullptr; } [[nodiscard]] inline virtual Rhi::IMeshShader* createMeshShaderFromSourceCode(const Rhi::ShaderSourceCode&, Rhi::ShaderBytecode* = nullptr RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER) override { RHI_ASSERT(getRhi().getContext(), false, "Direct3D 11 has no mesh shader support") return nullptr; } [[nodiscard]] inline virtual Rhi::IComputeShader* createComputeShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity check RHI_ASSERT(direct3D11Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 11 compute shader bytecode is invalid") // There's no need to check for "Rhi::Capabilities::computeShader", we know there's compute shader support return RHI_NEW(direct3D11Rhi.getContext(), ComputeShaderHlsl)(direct3D11Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IComputeShader* createComputeShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::computeShader", we know there's compute shader support Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); return RHI_NEW(direct3D11Rhi.getContext(), ComputeShaderHlsl)(direct3D11Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::IGraphicsProgram* createGraphicsProgram([[maybe_unused]] const Rhi::IRootSignature& rootSignature, [[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, Rhi::IVertexShader* vertexShader, Rhi::ITessellationControlShader* tessellationControlShader, Rhi::ITessellationEvaluationShader* tessellationEvaluationShader, Rhi::IGeometryShader* geometryShader, Rhi::IFragmentShader* fragmentShader RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Direct3D11Rhi& direct3D11Rhi = static_cast<Direct3D11Rhi&>(getRhi()); // Sanity checks // -> A shader can be a null pointer, but if it's not the shader and graphics program language must match // -> Optimization: Comparing the shader language name by directly comparing the pointer address of // the name is safe because we know that we always reference to one and the same name address // TODO(co) Add security check: Is the given resource one of the currently used RHI? RHI_ASSERT(direct3D11Rhi.getContext(), nullptr == vertexShader || vertexShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 11 vertex shader language mismatch") RHI_ASSERT(direct3D11Rhi.getContext(), nullptr == tessellationControlShader || tessellationControlShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 11 tessellation control shader language mismatch") RHI_ASSERT(direct3D11Rhi.getContext(), nullptr == tessellationEvaluationShader || tessellationEvaluationShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 11 tessellation evaluation shader language mismatch") RHI_ASSERT(direct3D11Rhi.getContext(), nullptr == geometryShader || geometryShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 11 geometry shader language mismatch") RHI_ASSERT(direct3D11Rhi.getContext(), nullptr == fragmentShader || fragmentShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 11 fragment shader language mismatch") // Create the graphics program return RHI_NEW(direct3D11Rhi.getContext(), GraphicsProgramHlsl)(direct3D11Rhi, static_cast<VertexShaderHlsl*>(vertexShader), static_cast<TessellationControlShaderHlsl*>(tessellationControlShader), static_cast<TessellationEvaluationShaderHlsl*>(tessellationEvaluationShader), static_cast<GeometryShaderHlsl*>(geometryShader), static_cast<FragmentShaderHlsl*>(fragmentShader) RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::IGraphicsProgram* createGraphicsProgram([[maybe_unused]] const Rhi::IRootSignature& rootSignature, [[maybe_unused]] Rhi::ITaskShader* taskShader, [[maybe_unused]] Rhi::IMeshShader& meshShader, [[maybe_unused]] Rhi::IFragmentShader* fragmentShader RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER) { RHI_ASSERT(getRhi().getContext(), false, "Direct3D 11 has no mesh shader support") return nullptr; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), ShaderLanguageHlsl, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit ShaderLanguageHlsl(const ShaderLanguageHlsl& source) = delete; ShaderLanguageHlsl& operator =(const ShaderLanguageHlsl& source) = delete; }; //[-------------------------------------------------------] //[ Direct3D11Rhi/State/GraphicsPipelineState.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 graphics pipeline state class */ class GraphicsPipelineState final : public Rhi::IGraphicsPipelineState { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] graphicsPipelineState * Graphics pipeline state to use * @param[in] id * The unique compact graphics pipeline state ID */ GraphicsPipelineState(Direct3D11Rhi& direct3D11Rhi, const Rhi::GraphicsPipelineState& graphicsPipelineState, uint16_t id RHI_RESOURCE_DEBUG_NAME_PARAMETER) : IGraphicsPipelineState(direct3D11Rhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER), mGraphicsProgram(graphicsPipelineState.graphicsProgram), mRenderPass(graphicsPipelineState.renderPass), mD3D11PrimitiveTopology(static_cast<D3D11_PRIMITIVE_TOPOLOGY>(graphicsPipelineState.primitiveTopology)), mD3D11InputLayout(nullptr), mRasterizerState(direct3D11Rhi, graphicsPipelineState.rasterizerState), mDepthStencilState(direct3D11Rhi, graphicsPipelineState.depthStencilState), mBlendState(direct3D11Rhi, graphicsPipelineState.blendState) { // Ensure a correct reference counter behaviour graphicsPipelineState.rootSignature->addReference(); graphicsPipelineState.rootSignature->releaseReference(); // Add a reference to the referenced RHI resources mGraphicsProgram->addReference(); mRenderPass->addReference(); // Create Direct3D 11 input element descriptions with support for attribute-less rendering const uint32_t numberOfAttributes = graphicsPipelineState.vertexAttributes.numberOfAttributes; if (numberOfAttributes > 0) { const VertexShaderHlsl* vertexShaderHlsl = static_cast<GraphicsProgramHlsl*>(mGraphicsProgram)->getVertexShaderHlsl(); if (nullptr != vertexShaderHlsl) { ID3DBlob* d3dBlobVertexShader = vertexShaderHlsl->getD3DBlobVertexShader(); RHI_ASSERT(direct3D11Rhi.getContext(), nullptr != d3dBlobVertexShader, "Failed to create the Direct3D 11 graphics pipeline stage input layout because there's no vertex shader") const Rhi::VertexAttribute* attributes = graphicsPipelineState.vertexAttributes.attributes; // TODO(co) We could manage in here without new/delete when using a fixed maximum supported number of elements const Rhi::Context& context = direct3D11Rhi.getContext(); D3D11_INPUT_ELEMENT_DESC* d3d11InputElementDescs = numberOfAttributes ? RHI_MALLOC_TYPED(context, D3D11_INPUT_ELEMENT_DESC, numberOfAttributes) : RHI_MALLOC_TYPED(context, D3D11_INPUT_ELEMENT_DESC, 1); D3D11_INPUT_ELEMENT_DESC* d3d11InputElementDesc = d3d11InputElementDescs; D3D11_INPUT_ELEMENT_DESC* d3d11InputElementDescEnd = d3d11InputElementDescs + numberOfAttributes; for (; d3d11InputElementDesc < d3d11InputElementDescEnd; ++d3d11InputElementDesc, ++attributes) { // Fill the "D3D11_INPUT_ELEMENT_DESC"-content d3d11InputElementDesc->SemanticName = attributes->semanticName; // Semantic name (LPCSTR) d3d11InputElementDesc->SemanticIndex = attributes->semanticIndex; // Semantic index (UINT) d3d11InputElementDesc->Format = Mapping::getDirect3D11Format(attributes->vertexAttributeFormat); // Format (DXGI_FORMAT) d3d11InputElementDesc->InputSlot = static_cast<UINT>(attributes->inputSlot); // Input slot (UINT) d3d11InputElementDesc->AlignedByteOffset = attributes->alignedByteOffset; // Aligned byte offset (UINT) // Per-instance instead of per-vertex? if (attributes->instancesPerElement > 0) { d3d11InputElementDesc->InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; // Input classification (D3D11_INPUT_CLASSIFICATION) d3d11InputElementDesc->InstanceDataStepRate = attributes->instancesPerElement; // Instance data step rate (UINT) } else { d3d11InputElementDesc->InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; // Input classification (D3D11_INPUT_CLASSIFICATION) d3d11InputElementDesc->InstanceDataStepRate = 0; // Instance data step rate (UINT) } } // Create the Direct3D 11 input layout FAILED_DEBUG_BREAK(direct3D11Rhi.getD3D11Device()->CreateInputLayout(d3d11InputElementDescs, numberOfAttributes, d3dBlobVertexShader->GetBufferPointer(), d3dBlobVertexShader->GetBufferSize(), &mD3D11InputLayout)) // Destroy Direct3D 11 input element descriptions RHI_FREE(context, d3d11InputElementDescs); // Assign a default name to the resource for debugging purposes #ifdef RHI_DEBUG if (nullptr != mD3D11InputLayout) { RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Graphics PSO", 15) // 15 = "Graphics PSO: " including terminating zero FAILED_DEBUG_BREAK(mD3D11InputLayout->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName)) } #endif } } } /** * @brief * Destructor */ virtual ~GraphicsPipelineState() override { // Release referenced RHI resources mGraphicsProgram->releaseReference(); mRenderPass->releaseReference(); // Release the Direct3D 11 input layout if (nullptr != mD3D11InputLayout) { mD3D11InputLayout->Release(); } // Free the unique compact graphics pipeline state ID static_cast<Direct3D11Rhi&>(getRhi()).GraphicsPipelineStateMakeId.DestroyID(getId()); } /** * @brief * Return the Direct3D 11 primitive topology * * @return * The Direct3D 11 primitive topology */ [[nodiscard]] inline D3D11_PRIMITIVE_TOPOLOGY getD3D11PrimitiveTopology() const { return mD3D11PrimitiveTopology; } /** * @brief * Return the Direct3D 11 input layout * * @return * Direct3D 11 input layout instance, can be a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11InputLayout* getD3D11InputLayout() const { return mD3D11InputLayout; } /** * @brief * Bind the graphics pipeline state * * @param[in] d3d11DeviceContext * The Direct3D 11 device context instance */ void bindGraphicsPipelineState(ID3D11DeviceContext& d3d11DeviceContext, CurrentGraphicsPipelineState& currentGraphicsPipelineState) const { // Set the graphics program if (currentGraphicsPipelineState.graphicsProgram != mGraphicsProgram) { currentGraphicsPipelineState.graphicsProgram = mGraphicsProgram; static_cast<Direct3D11Rhi&>(getRhi()).setGraphicsProgram(mGraphicsProgram); } // Set the Direct3D 11 input layout if (nullptr != mD3D11InputLayout && currentGraphicsPipelineState.d3d11InputLayout != mD3D11InputLayout) { currentGraphicsPipelineState.d3d11InputLayout = mD3D11InputLayout; d3d11DeviceContext.IASetInputLayout(mD3D11InputLayout); } // Set the Direct3D 11 rasterizer state if (currentGraphicsPipelineState.d3d11RasterizerState != mRasterizerState.getD3D11RasterizerState()) { currentGraphicsPipelineState.d3d11RasterizerState = mRasterizerState.getD3D11RasterizerState(); d3d11DeviceContext.RSSetState(currentGraphicsPipelineState.d3d11RasterizerState); } // Set Direct3D 11 depth stencil state if (currentGraphicsPipelineState.d3d11DepthStencilState != mDepthStencilState.getD3D11DepthStencilState()) { currentGraphicsPipelineState.d3d11DepthStencilState = mDepthStencilState.getD3D11DepthStencilState(); d3d11DeviceContext.OMSetDepthStencilState(currentGraphicsPipelineState.d3d11DepthStencilState, 0); } // Set Direct3D 11 blend state if (currentGraphicsPipelineState.d3d11BlendState != mBlendState.getD3D11BlendState()) { currentGraphicsPipelineState.d3d11BlendState = mBlendState.getD3D11BlendState(); d3d11DeviceContext.OMSetBlendState(currentGraphicsPipelineState.d3d11BlendState, 0, 0xffffffff); } } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), GraphicsPipelineState, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit GraphicsPipelineState(const GraphicsPipelineState& source) = delete; GraphicsPipelineState& operator =(const GraphicsPipelineState& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::IGraphicsProgram* mGraphicsProgram; Rhi::IRenderPass* mRenderPass; D3D11_PRIMITIVE_TOPOLOGY mD3D11PrimitiveTopology; ID3D11InputLayout* mD3D11InputLayout; ///< Direct3D 11 input layout, can be a null pointer RasterizerState mRasterizerState; DepthStencilState mDepthStencilState; BlendState mBlendState; }; //[-------------------------------------------------------] //[ Direct3D11Rhi/State/ComputePipelineState.h ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 compute pipeline state class */ class ComputePipelineState final : public Rhi::IComputePipelineState { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Rhi * Owner Direct3D 11 RHI instance * @param[in] computeShader * Compute shader to use * @param[in] id * The unique compact compute pipeline state ID */ ComputePipelineState(Direct3D11Rhi& direct3D11Rhi, Rhi::IComputeShader& computeShader, uint16_t id RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IComputePipelineState(direct3D11Rhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER), mD3D11ComputeShader(static_cast<ComputeShaderHlsl&>(computeShader).getD3D11ComputeShader()) { // Ensure a correct reference counter behaviour if (nullptr != mD3D11ComputeShader) { mD3D11ComputeShader->AddRef(); } computeShader.addReference(); computeShader.releaseReference(); } /** * @brief * Destructor */ virtual ~ComputePipelineState() override { // Release the Direct3D 11 compute shader if (nullptr != mD3D11ComputeShader) { mD3D11ComputeShader->Release(); } // Free the unique compact compute pipeline state ID static_cast<Direct3D11Rhi&>(getRhi()).ComputePipelineStateMakeId.DestroyID(getId()); } /** * @brief * Return the Direct3D 11 compute shader * * @return * Direct3D 11 compute shader, can be a null pointer on error, do not release the returned instance unless you added an own reference to it */ [[nodiscard]] inline ID3D11ComputeShader* getD3D11ComputeShader() const { return mD3D11ComputeShader; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), ComputePipelineState, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit ComputePipelineState(const ComputePipelineState& source) = delete; ComputePipelineState& operator =(const ComputePipelineState& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ID3D11ComputeShader* mD3D11ComputeShader; ///< Direct3D 11 compute shader, can be a null pointer }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Direct3D11Rhi //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] namespace { namespace detail { //[-------------------------------------------------------] //[ Global functions ] //[-------------------------------------------------------] bool createDevice(AGSContext* agsContext, UINT flags, ID3D11Device** d3d11Device, ID3D11DeviceContext** d3d11DeviceContext, D3D_FEATURE_LEVEL& d3dFeatureLevel) { // Driver types static constexpr D3D_DRIVER_TYPE D3D_DRIVER_TYPES[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; static constexpr UINT NUMBER_OF_DRIVER_TYPES = _countof(D3D_DRIVER_TYPES); // Feature levels static constexpr D3D_FEATURE_LEVEL D3D_FEATURE_LEVELS[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; static constexpr UINT NUMBER_OF_FEATURE_LEVELS = _countof(D3D_FEATURE_LEVELS); // Create the Direct3D 11 device if (nullptr != agsContext) { for (UINT deviceType = 0; deviceType < NUMBER_OF_DRIVER_TYPES; ++deviceType) { AGSDX11ExtensionParams agsDx11ExtensionParams = {}; AGSDX11ReturnedParams agsDx11ReturnedParams = {}; AGSDX11DeviceCreationParams agsDx11DeviceCreationParams1 = { nullptr, D3D_DRIVER_TYPES[deviceType], nullptr, flags, D3D_FEATURE_LEVELS, NUMBER_OF_FEATURE_LEVELS, D3D11_SDK_VERSION, nullptr }; if (agsDriverExtensionsDX11_CreateDevice(agsContext, &agsDx11DeviceCreationParams1, &agsDx11ExtensionParams, &agsDx11ReturnedParams) == AGS_SUCCESS) { *d3d11Device = agsDx11ReturnedParams.pDevice; *d3d11DeviceContext = agsDx11ReturnedParams.pImmediateContext; // Done return true; } else { // Maybe the system doesn't support Direct3D 11.1, try again requesting Direct3D 11 AGSDX11DeviceCreationParams agsDx11DeviceCreationParams2 = { nullptr, D3D_DRIVER_TYPES[deviceType], nullptr, flags, &D3D_FEATURE_LEVELS[1], NUMBER_OF_FEATURE_LEVELS - 1, D3D11_SDK_VERSION, nullptr }; if (agsDriverExtensionsDX11_CreateDevice(agsContext, &agsDx11DeviceCreationParams2, &agsDx11ExtensionParams, &agsDx11ReturnedParams) == AGS_SUCCESS) { *d3d11Device = agsDx11ReturnedParams.pDevice; *d3d11DeviceContext = agsDx11ReturnedParams.pImmediateContext; // Done return true; } } } } else { for (UINT deviceType = 0; deviceType < NUMBER_OF_DRIVER_TYPES; ++deviceType) { const HRESULT result = Direct3D11Rhi::D3D11CreateDevice(nullptr, D3D_DRIVER_TYPES[deviceType], nullptr, flags, D3D_FEATURE_LEVELS, NUMBER_OF_FEATURE_LEVELS, D3D11_SDK_VERSION, d3d11Device, &d3dFeatureLevel, d3d11DeviceContext); if (SUCCEEDED(result)) { // Done return true; } else if (E_INVALIDARG == result) { // Maybe the system doesn't support Direct3D 11.1, try again requesting Direct3D 11 if (SUCCEEDED(Direct3D11Rhi::D3D11CreateDevice(nullptr, D3D_DRIVER_TYPES[deviceType], nullptr, flags, &D3D_FEATURE_LEVELS[1], NUMBER_OF_FEATURE_LEVELS - 1, D3D11_SDK_VERSION, d3d11Device, &d3dFeatureLevel, d3d11DeviceContext))) { // Done return true; } } } } // Error! return false; } namespace ImplementationDispatch { //[-------------------------------------------------------] //[ Command buffer ] //[-------------------------------------------------------] void DispatchCommandBuffer(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DispatchCommandBuffer* realData = static_cast<const Rhi::Command::DispatchCommandBuffer*>(data); RHI_ASSERT(rhi.getContext(), nullptr != realData->commandBufferToDispatch, "The Direct3D 11 command buffer to dispatch must be valid") static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).dispatchCommandBufferInternal(*realData->commandBufferToDispatch); } //[-------------------------------------------------------] //[ Graphics ] //[-------------------------------------------------------] void SetGraphicsRootSignature(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetGraphicsRootSignature* realData = static_cast<const Rhi::Command::SetGraphicsRootSignature*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setGraphicsRootSignature(realData->rootSignature); } void SetGraphicsPipelineState(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetGraphicsPipelineState* realData = static_cast<const Rhi::Command::SetGraphicsPipelineState*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setGraphicsPipelineState(realData->graphicsPipelineState); } void SetGraphicsResourceGroup(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetGraphicsResourceGroup* realData = static_cast<const Rhi::Command::SetGraphicsResourceGroup*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setGraphicsResourceGroup(realData->rootParameterIndex, realData->resourceGroup); } void SetGraphicsVertexArray(const void* data, Rhi::IRhi& rhi) { // Input-assembler (IA) stage const Rhi::Command::SetGraphicsVertexArray* realData = static_cast<const Rhi::Command::SetGraphicsVertexArray*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setGraphicsVertexArray(realData->vertexArray); } void SetGraphicsViewports(const void* data, Rhi::IRhi& rhi) { // Rasterizer (RS) stage const Rhi::Command::SetGraphicsViewports* realData = static_cast<const Rhi::Command::SetGraphicsViewports*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setGraphicsViewports(realData->numberOfViewports, (nullptr != realData->viewports) ? realData->viewports : reinterpret_cast<const Rhi::Viewport*>(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData))); } void SetGraphicsScissorRectangles(const void* data, Rhi::IRhi& rhi) { // Rasterizer (RS) stage const Rhi::Command::SetGraphicsScissorRectangles* realData = static_cast<const Rhi::Command::SetGraphicsScissorRectangles*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setGraphicsScissorRectangles(realData->numberOfScissorRectangles, (nullptr != realData->scissorRectangles) ? realData->scissorRectangles : reinterpret_cast<const Rhi::ScissorRectangle*>(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData))); } void SetGraphicsRenderTarget(const void* data, Rhi::IRhi& rhi) { // Output-merger (OM) stage const Rhi::Command::SetGraphicsRenderTarget* realData = static_cast<const Rhi::Command::SetGraphicsRenderTarget*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setGraphicsRenderTarget(realData->renderTarget); } void ClearGraphics(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::ClearGraphics* realData = static_cast<const Rhi::Command::ClearGraphics*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).clearGraphics(realData->clearFlags, realData->color, realData->z, realData->stencil); } void DrawGraphics(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DrawGraphics* realData = static_cast<const Rhi::Command::DrawGraphics*>(data); if (nullptr != realData->indirectBuffer) { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawGraphics(*realData->indirectBuffer, realData->indirectBufferOffset, realData->numberOfDraws); } else { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws); } } void DrawGraphicsAgs(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DrawGraphics* realData = static_cast<const Rhi::Command::DrawGraphics*>(data); if (nullptr != realData->indirectBuffer) { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawGraphicsAgs(*realData->indirectBuffer, realData->indirectBufferOffset, realData->numberOfDraws); } else { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws); } } void DrawGraphicsNvApi(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DrawGraphics* realData = static_cast<const Rhi::Command::DrawGraphics*>(data); if (nullptr != realData->indirectBuffer) { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawGraphicsNvApi(*realData->indirectBuffer, realData->indirectBufferOffset, realData->numberOfDraws); } else { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws); } } void DrawIndexedGraphics(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DrawIndexedGraphics* realData = static_cast<const Rhi::Command::DrawIndexedGraphics*>(data); if (nullptr != realData->indirectBuffer) { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawIndexedGraphics(*realData->indirectBuffer, realData->indirectBufferOffset, realData->numberOfDraws); } else { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawIndexedGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws); } } void DrawIndexedGraphicsAgs(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DrawIndexedGraphics* realData = static_cast<const Rhi::Command::DrawIndexedGraphics*>(data); if (nullptr != realData->indirectBuffer) { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawIndexedGraphicsAgs(*realData->indirectBuffer, realData->indirectBufferOffset, realData->numberOfDraws); } else { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawIndexedGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws); } } void DrawIndexedGraphicsNvApi(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DrawIndexedGraphics* realData = static_cast<const Rhi::Command::DrawIndexedGraphics*>(data); if (nullptr != realData->indirectBuffer) { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawIndexedGraphicsNvApi(*realData->indirectBuffer, realData->indirectBufferOffset, realData->numberOfDraws); } else { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).drawIndexedGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws); } } void DrawMeshTasks(const void*, [[maybe_unused]] Rhi::IRhi& rhi) { RHI_ASSERT(static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).getContext(), false, "Direct3D 11 doesn't support mesh shaders") } //[-------------------------------------------------------] //[ Compute ] //[-------------------------------------------------------] void SetComputeRootSignature(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetComputeRootSignature* realData = static_cast<const Rhi::Command::SetComputeRootSignature*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setComputeRootSignature(realData->rootSignature); } void SetComputePipelineState(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetComputePipelineState* realData = static_cast<const Rhi::Command::SetComputePipelineState*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setComputePipelineState(realData->computePipelineState); } void SetComputeResourceGroup(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetComputeResourceGroup* realData = static_cast<const Rhi::Command::SetComputeResourceGroup*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setComputeResourceGroup(realData->rootParameterIndex, realData->resourceGroup); } void DispatchCompute(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DispatchCompute* realData = static_cast<const Rhi::Command::DispatchCompute*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).dispatchCompute(realData->groupCountX, realData->groupCountY, realData->groupCountZ); } //[-------------------------------------------------------] //[ Resource ] //[-------------------------------------------------------] void SetTextureMinimumMaximumMipmapIndex(const void* data, [[maybe_unused]] Rhi::IRhi& rhi) { const Rhi::Command::SetTextureMinimumMaximumMipmapIndex* realData = static_cast<const Rhi::Command::SetTextureMinimumMaximumMipmapIndex*>(data); RHI_ASSERT(static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).getContext(), realData->texture->getResourceType() == Rhi::ResourceType::TEXTURE_2D, "Unsupported Direct3D 11 texture resource type") static_cast<Direct3D11Rhi::Texture2D*>(realData->texture)->setMinimumMaximumMipmapIndex(realData->minimumMipmapIndex, realData->maximumMipmapIndex); } void ResolveMultisampleFramebuffer(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::ResolveMultisampleFramebuffer* realData = static_cast<const Rhi::Command::ResolveMultisampleFramebuffer*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).resolveMultisampleFramebuffer(*realData->destinationRenderTarget, *realData->sourceMultisampleFramebuffer); } void CopyResource(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::CopyResource* realData = static_cast<const Rhi::Command::CopyResource*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).copyResource(*realData->destinationResource, *realData->sourceResource); } void GenerateMipmaps(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::GenerateMipmaps* realData = static_cast<const Rhi::Command::GenerateMipmaps*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).generateMipmaps(*realData->resource); } void CopyUniformBufferData(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::CopyUniformBufferData* realData = static_cast<const Rhi::Command::CopyUniformBufferData*>(data); Rhi::MappedSubresource mappedSubresource; if (rhi.map(*realData->uniformBuffer, 0, Rhi::MapType::WRITE_DISCARD, 0, mappedSubresource)) { memcpy(mappedSubresource.data, Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->numberOfBytes); rhi.unmap(*realData->uniformBuffer, 0); } } void SetUniform(const void*, [[maybe_unused]] Rhi::IRhi& rhi) { RHI_ASSERT(rhi.getContext(), false, "The set uniform command isn't supported by the Direct3D 11 RHI implementation") } //[-------------------------------------------------------] //[ Query ] //[-------------------------------------------------------] void ResetQueryPool(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::ResetQueryPool* realData = static_cast<const Rhi::Command::ResetQueryPool*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).resetQueryPool(*realData->queryPool, realData->firstQueryIndex, realData->numberOfQueries); } void BeginQuery(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::BeginQuery* realData = static_cast<const Rhi::Command::BeginQuery*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).beginQuery(*realData->queryPool, realData->queryIndex, realData->queryControlFlags); } void EndQuery(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::EndQuery* realData = static_cast<const Rhi::Command::EndQuery*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).endQuery(*realData->queryPool, realData->queryIndex); } void WriteTimestampQuery(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::WriteTimestampQuery* realData = static_cast<const Rhi::Command::WriteTimestampQuery*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).writeTimestampQuery(*realData->queryPool, realData->queryIndex); } //[-------------------------------------------------------] //[ Debug ] //[-------------------------------------------------------] #ifdef RHI_DEBUG void SetDebugMarker(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetDebugMarker* realData = static_cast<const Rhi::Command::SetDebugMarker*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).setDebugMarker(realData->name); } void BeginDebugEvent(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::BeginDebugEvent* realData = static_cast<const Rhi::Command::BeginDebugEvent*>(data); static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).beginDebugEvent(realData->name); } void EndDebugEvent(const void*, Rhi::IRhi& rhi) { static_cast<Direct3D11Rhi::Direct3D11Rhi&>(rhi).endDebugEvent(); } #else inline void SetDebugMarker(const void*, Rhi::IRhi&) {} inline void BeginDebugEvent(const void*, Rhi::IRhi&) {} inline void EndDebugEvent(const void*, Rhi::IRhi&) {} #endif } //[-------------------------------------------------------] //[ Global definitions ] //[-------------------------------------------------------] static Rhi::ImplementationDispatchFunction DISPATCH_FUNCTIONS[static_cast<uint8_t>(Rhi::CommandDispatchFunctionIndex::NUMBER_OF_FUNCTIONS)] = { // Command buffer &ImplementationDispatch::DispatchCommandBuffer, // Graphics &ImplementationDispatch::SetGraphicsRootSignature, &ImplementationDispatch::SetGraphicsPipelineState, &ImplementationDispatch::SetGraphicsResourceGroup, &ImplementationDispatch::SetGraphicsVertexArray, // Input-assembler (IA) stage &ImplementationDispatch::SetGraphicsViewports, // Rasterizer (RS) stage &ImplementationDispatch::SetGraphicsScissorRectangles, // Rasterizer (RS) stage &ImplementationDispatch::SetGraphicsRenderTarget, // Output-merger (OM) stage &ImplementationDispatch::ClearGraphics, &ImplementationDispatch::DrawGraphics, &ImplementationDispatch::DrawIndexedGraphics, &ImplementationDispatch::DrawMeshTasks, // Compute &ImplementationDispatch::SetComputeRootSignature, &ImplementationDispatch::SetComputePipelineState, &ImplementationDispatch::SetComputeResourceGroup, &ImplementationDispatch::DispatchCompute, // Resource &ImplementationDispatch::SetTextureMinimumMaximumMipmapIndex, &ImplementationDispatch::ResolveMultisampleFramebuffer, &ImplementationDispatch::CopyResource, &ImplementationDispatch::GenerateMipmaps, &ImplementationDispatch::CopyUniformBufferData, &ImplementationDispatch::SetUniform, // Query &ImplementationDispatch::ResetQueryPool, &ImplementationDispatch::BeginQuery, &ImplementationDispatch::EndQuery, &ImplementationDispatch::WriteTimestampQuery, // Debug &ImplementationDispatch::SetDebugMarker, &ImplementationDispatch::BeginDebugEvent, &ImplementationDispatch::EndDebugEvent }; //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] } // detail } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Direct3D11Rhi { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] Direct3D11Rhi::Direct3D11Rhi(const Rhi::Context& context) : IRhi(Rhi::NameId::DIRECT3D11, context), VertexArrayMakeId(context.getAllocator()), GraphicsPipelineStateMakeId(context.getAllocator()), ComputePipelineStateMakeId(context.getAllocator()), mDirect3D11RuntimeLinking(nullptr), mD3D11Device(nullptr), mD3D11DeviceContext(nullptr), mD3DFeatureLevel(D3D_FEATURE_LEVEL_11_0), mD3DUserDefinedAnnotation(nullptr), mShaderLanguageHlsl(nullptr), mD3D11QueryFlush(nullptr), mRenderTarget(nullptr), mGraphicsRootSignature(nullptr), mComputeRootSignature(nullptr), mD3D11PrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_UNDEFINED), mD3d11VertexShader(nullptr), mD3d11HullShader(nullptr), mD3d11DomainShader(nullptr), mD3d11GeometryShader(nullptr), mD3d11PixelShader(nullptr), mD3d11ComputeShader(nullptr) { mDirect3D11RuntimeLinking = RHI_NEW(context, Direct3D11RuntimeLinking)(*this); // Is Direct3D 11 available? if (mDirect3D11RuntimeLinking->isDirect3D11Avaiable()) { // Flags UINT flags = 0; #ifdef RHI_DEBUG flags |= D3D11_CREATE_DEVICE_DEBUG; #endif // Create the Direct3D 11 device AGSContext* agsContext = mDirect3D11RuntimeLinking->getAgsContext(); if (!detail::createDevice(agsContext, flags, &mD3D11Device, &mD3D11DeviceContext, mD3DFeatureLevel) && (flags & D3D11_CREATE_DEVICE_DEBUG)) { RHI_LOG(mContext, CRITICAL, "Failed to create the Direct3D 11 device instance, retrying without debug flag (maybe no Windows SDK is installed)") flags &= ~D3D11_CREATE_DEVICE_DEBUG; detail::createDevice(agsContext, flags, &mD3D11Device, &mD3D11DeviceContext, mD3DFeatureLevel); } // Update dispatch draw function pointers, if needed if (nullptr != agsContext) { detail::DISPATCH_FUNCTIONS[static_cast<uint32_t>(Rhi::CommandDispatchFunctionIndex::DRAW_GRAPHICS)] = &detail::ImplementationDispatch::DrawGraphicsAgs; detail::DISPATCH_FUNCTIONS[static_cast<uint32_t>(Rhi::CommandDispatchFunctionIndex::DRAW_INDEXED_GRAPHICS)] = &detail::ImplementationDispatch::DrawIndexedGraphicsAgs; } else { detail::DISPATCH_FUNCTIONS[static_cast<uint32_t>(Rhi::CommandDispatchFunctionIndex::DRAW_GRAPHICS)] = (nullptr != NvAPI_D3D11_MultiDrawInstancedIndirect) ? &detail::ImplementationDispatch::DrawGraphicsNvApi : &detail::ImplementationDispatch::DrawGraphics; detail::DISPATCH_FUNCTIONS[static_cast<uint32_t>(Rhi::CommandDispatchFunctionIndex::DRAW_INDEXED_GRAPHICS)] = (nullptr != NvAPI_D3D11_MultiDrawIndexedInstancedIndirect) ? &detail::ImplementationDispatch::DrawIndexedGraphicsNvApi : &detail::ImplementationDispatch::DrawIndexedGraphics; } // Is there a valid Direct3D 11 device and device context? if (nullptr != mD3D11Device && nullptr != mD3D11DeviceContext) { // Direct3D 11 debug related stuff if (flags & D3D11_CREATE_DEVICE_DEBUG) { #ifdef RHI_DEBUG // Try to get the Direct3D 11 user defined annotation interface, Direct3D 11.1 feature FAILED_DEBUG_BREAK(mD3D11DeviceContext->QueryInterface(__uuidof(ID3DUserDefinedAnnotation), reinterpret_cast<LPVOID*>(&mD3DUserDefinedAnnotation))) #endif // Direct3D 11 debug settings ID3D11Debug* d3d11Debug = nullptr; if (SUCCEEDED(mD3D11Device->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<LPVOID*>(&d3d11Debug)))) { ID3D11InfoQueue* d3d11InfoQueue = nullptr; if (SUCCEEDED(d3d11Debug->QueryInterface(__uuidof(ID3D11InfoQueue), reinterpret_cast<LPVOID*>(&d3d11InfoQueue)))) { // When using render-to-texture, Direct3D 11 will quickly spam the log with // " // D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets: Resource being set to OM RenderTarget slot 0 is still bound on input! [ STATE_SETTING WARNING #9: DEVICE_OMSETRENDERTARGETS_HAZARD] // D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing VS shader resource slot 0 to NULL. [ STATE_SETTING WARNING #3: DEVICE_VSSETSHADERRESOURCES_HAZARD] // D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing HS shader resource slot 0 to NULL. [ STATE_SETTING WARNING #2097173: DEVICE_HSSETSHADERRESOURCES_HAZARD] // D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing DS shader resource slot 0 to NULL. [ STATE_SETTING WARNING #2097189: DEVICE_DSSETSHADERRESOURCES_HAZARD] // D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing GS shader resource slot 0 to NULL. [ STATE_SETTING WARNING #5: DEVICE_GSSETSHADERRESOURCES_HAZARD] // D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing PS shader resource slot 0 to NULL. [ STATE_SETTING WARNING #7: DEVICE_PSSETSHADERRESOURCES_HAZARD] // " // When not unbinding render targets from shader resources, even if shaders never access the render target by reading. We could add extra // logic to avoid this situation, but on the other hand, the RHI implementation should be as slim as possible. Since those Direct3D 11 warnings // are pretty annoying and introduce the risk of missing relevant warnings, let's suppress those warnings. Thought about this for a while, feels // like the best solution considering the alternatives even if suppressing warnings is not always the best idea. D3D11_MESSAGE_ID d3d11MessageIds[] = { D3D11_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_HAZARD, D3D11_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_HAZARD, D3D11_MESSAGE_ID_DEVICE_OMSETRENDERTARGETS_HAZARD, D3D11_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_HAZARD, D3D11_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_HAZARD, D3D11_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_HAZARD, D3D11_MESSAGE_ID_DEVICE_HSSETSHADERRESOURCES_HAZARD, D3D11_MESSAGE_ID_DEVICE_DSSETSHADERRESOURCES_HAZARD, D3D11_MESSAGE_ID_DEVICE_CSSETSHADERRESOURCES_HAZARD, D3D11_MESSAGE_ID_DEVICE_CSSETUNORDEREDACCESSVIEWS_HAZARD }; D3D11_INFO_QUEUE_FILTER d3d11InfoQueueFilter = {}; d3d11InfoQueueFilter.DenyList.NumIDs = _countof(d3d11MessageIds); d3d11InfoQueueFilter.DenyList.pIDList = d3d11MessageIds; FAILED_DEBUG_BREAK(d3d11InfoQueue->AddStorageFilterEntries(&d3d11InfoQueueFilter)) // Sadly, when using the Direct3D 11 break feature we're having a confusing call stack, so we don't use this and use "FAILED_DEBUG_BREAK()" instead // d3d11InfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true); // d3d11InfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true); // d3d11InfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_WARNING, true); // d3d11InfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_INFO, true); d3d11InfoQueue->Release(); } d3d11Debug->Release(); } } // Initialize the capabilities initializeCapabilities(); } else { RHI_LOG(mContext, CRITICAL, "Failed to create the Direct3D 11 device and device context instance") } } } Direct3D11Rhi::~Direct3D11Rhi() { // Release instances for (Rhi::ITexture* texture : mGenerateAsynchronousMipmapsForTextures) { texture->releaseReference(); } if (nullptr != mRenderTarget) { mRenderTarget->releaseReference(); mRenderTarget = nullptr; } if (nullptr != mGraphicsRootSignature) { mGraphicsRootSignature->releaseReference(); mGraphicsRootSignature = nullptr; } if (nullptr != mComputeRootSignature) { mComputeRootSignature->releaseReference(); mComputeRootSignature = nullptr; } #ifdef RHI_STATISTICS { // For debugging: At this point there should be no resource instances left, validate this! // -> Are the currently any resource instances? const uint32_t numberOfCurrentResources = getStatistics().getNumberOfCurrentResources(); if (numberOfCurrentResources > 0) { // Error! if (numberOfCurrentResources > 1) { RHI_ASSERT(mContext, false, "The Direct3D 11 RHI implementation is going to be destroyed, but there are still %u resource instances left (memory leak)", numberOfCurrentResources) } else { RHI_ASSERT(mContext, false, "The Direct3D 11 RHI implementation is going to be destroyed, but there is still one resource instance left (memory leak)") } // Use debug output to show the current number of resource instances getStatistics().debugOutputCurrentResouces(mContext); } } #endif // Release the Direct3D 11 query instance used for flush, in case we have one if (nullptr != mD3D11QueryFlush) { mD3D11QueryFlush->Release(); } // Release the HLSL shader language instance, in case we have one if (nullptr != mShaderLanguageHlsl) { mShaderLanguageHlsl->releaseReference(); } // Release the Direct3D 11 device we've created if (nullptr != mD3DUserDefinedAnnotation) { mD3DUserDefinedAnnotation->Release(); mD3DUserDefinedAnnotation = nullptr; } { AGSContext* agsContext = mDirect3D11RuntimeLinking->getAgsContext(); if (nullptr != agsContext) { unsigned int deviceReferences = 0; unsigned int immediateContextReferences = 0; agsDriverExtensionsDX11_DestroyDevice(agsContext, mD3D11Device, &deviceReferences, mD3D11DeviceContext, &immediateContextReferences); // TODO(co) AMD AGS v5.3.0 - November 22, 2018 behaves odd when it comes to the reference counters, "deviceReferences" handles as "immediateContextReferences"? // When done in any other way there will be crashes or resource leaks. if (nullptr != mD3D11DeviceContext && deviceReferences > 0) { mD3D11DeviceContext->Release(); } mD3D11DeviceContext = nullptr; mD3D11Device = nullptr; } else { if (nullptr != mD3D11DeviceContext) { mD3D11DeviceContext->Release(); mD3D11DeviceContext = nullptr; } if (nullptr != mD3D11Device) { mD3D11Device->Release(); mD3D11Device = nullptr; } } } // Destroy the Direct3D 11 runtime linking instance RHI_DELETE(mContext, Direct3D11RuntimeLinking, mDirect3D11RuntimeLinking); } void Direct3D11Rhi::dispatchCommandBufferInternal(const Rhi::CommandBuffer& commandBuffer) { // Loop through all commands const uint8_t* commandPacketBuffer = commandBuffer.getCommandPacketBuffer(); Rhi::ConstCommandPacket constCommandPacket = commandPacketBuffer; while (nullptr != constCommandPacket) { { // Dispatch command packet const Rhi::CommandDispatchFunctionIndex commandDispatchFunctionIndex = Rhi::CommandPacketHelper::loadCommandDispatchFunctionIndex(constCommandPacket); const void* command = Rhi::CommandPacketHelper::loadCommand(constCommandPacket); detail::DISPATCH_FUNCTIONS[static_cast<uint32_t>(commandDispatchFunctionIndex)](command, *this); } { // Next command const uint32_t nextCommandPacketByteIndex = Rhi::CommandPacketHelper::getNextCommandPacketByteIndex(constCommandPacket); constCommandPacket = (~0u != nextCommandPacketByteIndex) ? &commandPacketBuffer[nextCommandPacketByteIndex] : nullptr; } } } //[-------------------------------------------------------] //[ Graphics ] //[-------------------------------------------------------] void Direct3D11Rhi::setGraphicsRootSignature(Rhi::IRootSignature* rootSignature) { if (nullptr != mGraphicsRootSignature) { mGraphicsRootSignature->releaseReference(); } mGraphicsRootSignature = static_cast<RootSignature*>(rootSignature); if (nullptr != mGraphicsRootSignature) { mGraphicsRootSignature->addReference(); // Sanity check RHI_MATCH_CHECK(*this, *rootSignature) } } void Direct3D11Rhi::setGraphicsPipelineState(Rhi::IGraphicsPipelineState* graphicsPipelineState) { if (nullptr != graphicsPipelineState) { // Sanity check RHI_MATCH_CHECK(*this, *graphicsPipelineState) // Set primitive topology // -> The "Rhi::PrimitiveTopology" values directly map to Direct3D 9 & 10 & 11 constants, do not change them const GraphicsPipelineState* direct3D11GraphicsPipelineState = static_cast<const GraphicsPipelineState*>(graphicsPipelineState); if (mD3D11PrimitiveTopology != direct3D11GraphicsPipelineState->getD3D11PrimitiveTopology()) { mD3D11PrimitiveTopology = direct3D11GraphicsPipelineState->getD3D11PrimitiveTopology(); mD3D11DeviceContext->IASetPrimitiveTopology(mD3D11PrimitiveTopology); } // Set graphics pipeline state direct3D11GraphicsPipelineState->bindGraphicsPipelineState(*mD3D11DeviceContext, mCurrentGraphicsPipelineState); } else { // TODO(co) Handle this situation? } } void Direct3D11Rhi::setGraphicsResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup) { // Security checks #ifdef RHI_DEBUG { RHI_ASSERT(mContext, nullptr != mGraphicsRootSignature, "No Direct3D 11 RHI implementation graphics root signature set") const Rhi::RootSignature& rootSignature = mGraphicsRootSignature->getRootSignature(); RHI_ASSERT(mContext, rootParameterIndex < rootSignature.numberOfParameters, "The Direct3D 11 RHI implementation root parameter index is out of bounds") const Rhi::RootParameter& rootParameter = rootSignature.parameters[rootParameterIndex]; RHI_ASSERT(mContext, Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType, "The Direct3D 11 RHI implementation root parameter index doesn't reference a descriptor table") RHI_ASSERT(mContext, nullptr != reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges), "The Direct3D 11 RHI implementation descriptor ranges is a null pointer") } #endif if (nullptr != resourceGroup) { // Sanity check RHI_MATCH_CHECK(*this, *resourceGroup) // Set graphics resource group const ResourceGroup* d3d11ResourceGroup = static_cast<ResourceGroup*>(resourceGroup); const uint32_t numberOfResources = d3d11ResourceGroup->getNumberOfResources(); Rhi::IResource** resources = d3d11ResourceGroup->getResources(); const Rhi::RootParameter& rootParameter = mGraphicsRootSignature->getRootSignature().parameters[rootParameterIndex]; for (uint32_t resourceIndex = 0; resourceIndex < numberOfResources; ++resourceIndex, ++resources) { const Rhi::IResource* resource = *resources; RHI_ASSERT(mContext, nullptr != reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges), "Invalid Direct3D 11 descriptor ranges") const Rhi::DescriptorRange& descriptorRange = reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges)[resourceIndex]; // Check the type of resource to set // TODO(co) Some additional resource type root signature security checks in debug build? const Rhi::ResourceType resourceType = resource->getResourceType(); switch (resourceType) { case Rhi::ResourceType::UNIFORM_BUFFER: { ID3D11Buffer* d3d11Buffers = static_cast<const UniformBuffer*>(resource)->getD3D11Buffer(); const UINT startSlot = descriptorRange.baseShaderRegister; switch (descriptorRange.shaderVisibility) { case Rhi::ShaderVisibility::ALL: mD3D11DeviceContext->VSSetConstantBuffers(startSlot, 1, &d3d11Buffers); mD3D11DeviceContext->HSSetConstantBuffers(startSlot, 1, &d3d11Buffers); mD3D11DeviceContext->DSSetConstantBuffers(startSlot, 1, &d3d11Buffers); mD3D11DeviceContext->GSSetConstantBuffers(startSlot, 1, &d3d11Buffers); mD3D11DeviceContext->PSSetConstantBuffers(startSlot, 1, &d3d11Buffers); break; case Rhi::ShaderVisibility::VERTEX: mD3D11DeviceContext->VSSetConstantBuffers(startSlot, 1, &d3d11Buffers); break; case Rhi::ShaderVisibility::TESSELLATION_CONTROL: // "hull shader" in Direct3D terminology mD3D11DeviceContext->HSSetConstantBuffers(startSlot, 1, &d3d11Buffers); break; case Rhi::ShaderVisibility::TESSELLATION_EVALUATION: // "domain shader" in Direct3D terminology mD3D11DeviceContext->DSSetConstantBuffers(startSlot, 1, &d3d11Buffers); break; case Rhi::ShaderVisibility::GEOMETRY: mD3D11DeviceContext->GSSetConstantBuffers(startSlot, 1, &d3d11Buffers); break; case Rhi::ShaderVisibility::FRAGMENT: // "pixel shader" in Direct3D terminology mD3D11DeviceContext->PSSetConstantBuffers(startSlot, 1, &d3d11Buffers); break; case Rhi::ShaderVisibility::TASK: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 task shader visibility") break; case Rhi::ShaderVisibility::MESH: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 mesh shader visibility") break; case Rhi::ShaderVisibility::COMPUTE: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 compute shader visibility") break; case Rhi::ShaderVisibility::ALL_GRAPHICS: mD3D11DeviceContext->VSSetConstantBuffers(startSlot, 1, &d3d11Buffers); mD3D11DeviceContext->HSSetConstantBuffers(startSlot, 1, &d3d11Buffers); mD3D11DeviceContext->DSSetConstantBuffers(startSlot, 1, &d3d11Buffers); mD3D11DeviceContext->GSSetConstantBuffers(startSlot, 1, &d3d11Buffers); mD3D11DeviceContext->PSSetConstantBuffers(startSlot, 1, &d3d11Buffers); break; } break; } case Rhi::ResourceType::STRUCTURED_BUFFER: case Rhi::ResourceType::TEXTURE_BUFFER: case Rhi::ResourceType::TEXTURE_1D: case Rhi::ResourceType::TEXTURE_1D_ARRAY: case Rhi::ResourceType::TEXTURE_2D: case Rhi::ResourceType::TEXTURE_2D_ARRAY: case Rhi::ResourceType::TEXTURE_3D: case Rhi::ResourceType::TEXTURE_CUBE: case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: { ID3D11ShaderResourceView* d3d11ShaderResourceView = nullptr; switch (resourceType) { case Rhi::ResourceType::TEXTURE_BUFFER: d3d11ShaderResourceView = static_cast<const TextureBuffer*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::STRUCTURED_BUFFER: d3d11ShaderResourceView = static_cast<const StructuredBuffer*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_1D: d3d11ShaderResourceView = static_cast<const Texture1D*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_1D_ARRAY: d3d11ShaderResourceView = static_cast<const Texture1DArray*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_2D: d3d11ShaderResourceView = static_cast<const Texture2D*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_2D_ARRAY: d3d11ShaderResourceView = static_cast<const Texture2DArray*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_3D: d3d11ShaderResourceView = static_cast<const Texture3D*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_CUBE: d3d11ShaderResourceView = static_cast<const TextureCube*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: d3d11ShaderResourceView = static_cast<const TextureCubeArray*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 RHI implementation resource type") break; } const UINT startSlot = descriptorRange.baseShaderRegister; switch (descriptorRange.shaderVisibility) { case Rhi::ShaderVisibility::ALL: mD3D11DeviceContext->VSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); mD3D11DeviceContext->HSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); mD3D11DeviceContext->DSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); mD3D11DeviceContext->GSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); mD3D11DeviceContext->PSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); break; case Rhi::ShaderVisibility::VERTEX: mD3D11DeviceContext->VSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); break; case Rhi::ShaderVisibility::TESSELLATION_CONTROL: // "hull shader" in Direct3D terminology mD3D11DeviceContext->HSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); break; case Rhi::ShaderVisibility::TESSELLATION_EVALUATION: // "domain shader" in Direct3D terminology mD3D11DeviceContext->DSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); break; case Rhi::ShaderVisibility::GEOMETRY: mD3D11DeviceContext->GSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); break; case Rhi::ShaderVisibility::FRAGMENT: // "pixel shader" in Direct3D terminology mD3D11DeviceContext->PSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); break; case Rhi::ShaderVisibility::TASK: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 task shader visibility") break; case Rhi::ShaderVisibility::MESH: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 mesh shader visibility") break; case Rhi::ShaderVisibility::COMPUTE: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 compute shader visibility") break; case Rhi::ShaderVisibility::ALL_GRAPHICS: mD3D11DeviceContext->VSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); mD3D11DeviceContext->HSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); mD3D11DeviceContext->DSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); mD3D11DeviceContext->GSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); mD3D11DeviceContext->PSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); break; } break; } case Rhi::ResourceType::SAMPLER_STATE: { ID3D11SamplerState* d3d11SamplerState = static_cast<const SamplerState*>(resource)->getD3D11SamplerState(); const UINT startSlot = descriptorRange.baseShaderRegister; switch (descriptorRange.shaderVisibility) { case Rhi::ShaderVisibility::ALL: mD3D11DeviceContext->VSSetSamplers(startSlot, 1, &d3d11SamplerState); mD3D11DeviceContext->HSSetSamplers(startSlot, 1, &d3d11SamplerState); mD3D11DeviceContext->DSSetSamplers(startSlot, 1, &d3d11SamplerState); mD3D11DeviceContext->GSSetSamplers(startSlot, 1, &d3d11SamplerState); mD3D11DeviceContext->PSSetSamplers(startSlot, 1, &d3d11SamplerState); break; case Rhi::ShaderVisibility::VERTEX: mD3D11DeviceContext->VSSetSamplers(startSlot, 1, &d3d11SamplerState); break; case Rhi::ShaderVisibility::TESSELLATION_CONTROL: // "hull shader" in Direct3D terminology mD3D11DeviceContext->HSSetSamplers(startSlot, 1, &d3d11SamplerState); break; case Rhi::ShaderVisibility::TESSELLATION_EVALUATION: // "domain shader" in Direct3D terminology mD3D11DeviceContext->DSSetSamplers(startSlot, 1, &d3d11SamplerState); break; case Rhi::ShaderVisibility::GEOMETRY: mD3D11DeviceContext->GSSetSamplers(startSlot, 1, &d3d11SamplerState); break; case Rhi::ShaderVisibility::FRAGMENT: // "pixel shader" in Direct3D terminology mD3D11DeviceContext->PSSetSamplers(startSlot, 1, &d3d11SamplerState); break; case Rhi::ShaderVisibility::TASK: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 task shader visibility") break; case Rhi::ShaderVisibility::MESH: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 mesh shader visibility") break; case Rhi::ShaderVisibility::COMPUTE: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 compute shader visibility") break; case Rhi::ShaderVisibility::ALL_GRAPHICS: mD3D11DeviceContext->VSSetSamplers(startSlot, 1, &d3d11SamplerState); mD3D11DeviceContext->HSSetSamplers(startSlot, 1, &d3d11SamplerState); mD3D11DeviceContext->DSSetSamplers(startSlot, 1, &d3d11SamplerState); mD3D11DeviceContext->GSSetSamplers(startSlot, 1, &d3d11SamplerState); mD3D11DeviceContext->PSSetSamplers(startSlot, 1, &d3d11SamplerState); break; } break; } case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 RHI implementation resource type") break; } } } else { // TODO(co) Handle this situation? } } void Direct3D11Rhi::setGraphicsVertexArray(Rhi::IVertexArray* vertexArray) { // Input-assembler (IA) stage if (nullptr != vertexArray) { // Sanity check RHI_MATCH_CHECK(*this, *vertexArray) // Begin debug event RHI_BEGIN_DEBUG_EVENT_FUNCTION(this) static_cast<VertexArray*>(vertexArray)->setDirect3DIASetInputLayoutAndStreamSource(*mD3D11DeviceContext); // End debug event RHI_END_DEBUG_EVENT(this) } else { // Set no Direct3D 11 input layout mD3D11DeviceContext->IASetInputLayout(nullptr); mCurrentGraphicsPipelineState.d3d11InputLayout = nullptr; } } void Direct3D11Rhi::setGraphicsViewports(uint32_t numberOfViewports, const Rhi::Viewport* viewports) { // Rasterizer (RS) stage // Sanity check RHI_ASSERT(mContext, numberOfViewports > 0 && nullptr != viewports, "Invalid Direct3D 11 rasterizer state viewports") // Set the Direct3D 11 viewports // -> "Rhi::Viewport" directly maps to Direct3D 11, do not change it // -> Let Direct3D 11 perform the index validation for us (the Direct3D 11 debug features are pretty good) static_assert(sizeof(Rhi::Viewport) == sizeof(D3D11_VIEWPORT), "Direct3D 11 structure mismatch detected"); mD3D11DeviceContext->RSSetViewports(numberOfViewports, reinterpret_cast<const D3D11_VIEWPORT*>(viewports)); } void Direct3D11Rhi::setGraphicsScissorRectangles(uint32_t numberOfScissorRectangles, const Rhi::ScissorRectangle* scissorRectangles) { // Rasterizer (RS) stage // Sanity check RHI_ASSERT(mContext, numberOfScissorRectangles > 0 && nullptr != scissorRectangles, "Invalid Direct3D 11 rasterizer state scissor rectangles") // Set the Direct3D 11 scissor rectangles // -> "Rhi::ScissorRectangle" directly maps to Direct3D 9 & 10 & 11, do not change it // -> Let Direct3D 11 perform the index validation for us (the Direct3D 11 debug features are pretty good) static_assert(sizeof(Rhi::ScissorRectangle) == sizeof(D3D11_RECT), "Direct3D 11 structure mismatch detected"); mD3D11DeviceContext->RSSetScissorRects(numberOfScissorRectangles, reinterpret_cast<const D3D11_RECT*>(scissorRectangles)); } void Direct3D11Rhi::setGraphicsRenderTarget(Rhi::IRenderTarget* renderTarget) { // Output-merger (OM) stage // New render target? if (mRenderTarget != renderTarget) { // Set a render target? if (nullptr != renderTarget) { // Sanity check RHI_MATCH_CHECK(*this, *renderTarget) // Release the render target reference, in case we have one if (nullptr != mRenderTarget) { // Release reference mRenderTarget->releaseReference(); } // Set new render target and add a reference to it mRenderTarget = renderTarget; mRenderTarget->addReference(); // Evaluate the render target type switch (mRenderTarget->getResourceType()) { case Rhi::ResourceType::SWAP_CHAIN: { // Get the Direct3D 11 swap chain instance const SwapChain* swapChain = static_cast<SwapChain*>(mRenderTarget); // Direct3D 11 needs a pointer to a pointer, so give it one ID3D11RenderTargetView* d3d11RenderTargetView = swapChain->getD3D11RenderTargetView(); mD3D11DeviceContext->OMSetRenderTargets(1, &d3d11RenderTargetView, swapChain->getD3D11DepthStencilView()); break; } case Rhi::ResourceType::FRAMEBUFFER: { // Get the Direct3D 11 framebuffer instance const Framebuffer* framebuffer = static_cast<Framebuffer*>(mRenderTarget); // Set the Direct3D 11 render targets mD3D11DeviceContext->OMSetRenderTargets(framebuffer->getNumberOfColorTextures(), framebuffer->getD3D11RenderTargetViews(), framebuffer->getD3D11DepthStencilView()); break; } case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::TEXTURE_BUFFER: case Rhi::ResourceType::STRUCTURED_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::TEXTURE_1D: case Rhi::ResourceType::TEXTURE_1D_ARRAY: case Rhi::ResourceType::TEXTURE_2D: case Rhi::ResourceType::TEXTURE_2D_ARRAY: case Rhi::ResourceType::TEXTURE_3D: case Rhi::ResourceType::TEXTURE_CUBE: case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: default: // Not handled in here break; } } else { // Set the Direct3D 11 render targets mD3D11DeviceContext->OMSetRenderTargets(0, nullptr, nullptr); // Release the render target reference, in case we have one if (nullptr != mRenderTarget) { mRenderTarget->releaseReference(); mRenderTarget = nullptr; } } } } void Direct3D11Rhi::clearGraphics(uint32_t clearFlags, const float color[4], float z, uint32_t stencil) { // Unlike Direct3D 9, OpenGL or OpenGL ES 3, Direct3D 11 clears a given render target view and not the currently bound // Sanity check RHI_ASSERT(mContext, z >= 0.0f && z <= 1.0f, "The Direct3D 11 clear graphics z value must be between [0, 1] (inclusive)") // Begin debug event RHI_BEGIN_DEBUG_EVENT_FUNCTION(this) // Render target set? if (nullptr != mRenderTarget) { // Evaluate the render target type switch (mRenderTarget->getResourceType()) { case Rhi::ResourceType::SWAP_CHAIN: { // Get the Direct3D 11 swap chain instance SwapChain* swapChain = static_cast<SwapChain*>(mRenderTarget); // Clear the Direct3D 11 render target view? if (clearFlags & Rhi::ClearFlag::COLOR) { mD3D11DeviceContext->ClearRenderTargetView(swapChain->getD3D11RenderTargetView(), color); } // Clear the Direct3D 11 depth stencil view? if (nullptr != swapChain->getD3D11DepthStencilView()) { // Get the Direct3D 11 clear flags UINT direct3D11ClearFlags = (clearFlags & Rhi::ClearFlag::DEPTH) ? D3D11_CLEAR_DEPTH : 0u; if (clearFlags & Rhi::ClearFlag::STENCIL) { direct3D11ClearFlags |= D3D11_CLEAR_STENCIL; } if (0 != direct3D11ClearFlags) { // Clear the Direct3D 11 depth stencil view mD3D11DeviceContext->ClearDepthStencilView(swapChain->getD3D11DepthStencilView(), direct3D11ClearFlags, z, static_cast<UINT8>(stencil)); } } break; } case Rhi::ResourceType::FRAMEBUFFER: { // Get the Direct3D 11 framebuffer instance Framebuffer* framebuffer = static_cast<Framebuffer*>(mRenderTarget); // Clear all Direct3D 11 render target views? if (clearFlags & Rhi::ClearFlag::COLOR) { // Loop through all Direct3D 11 render target views ID3D11RenderTargetView** d3d11RenderTargetViewsEnd = framebuffer->getD3D11RenderTargetViews() + framebuffer->getNumberOfColorTextures(); for (ID3D11RenderTargetView** d3d11RenderTargetView = framebuffer->getD3D11RenderTargetViews(); d3d11RenderTargetView < d3d11RenderTargetViewsEnd; ++d3d11RenderTargetView) { // Valid Direct3D 11 render target view? if (nullptr != *d3d11RenderTargetView) { mD3D11DeviceContext->ClearRenderTargetView(*d3d11RenderTargetView, color); } } } // Clear the Direct3D 11 depth stencil view? if (nullptr != framebuffer->getD3D11DepthStencilView()) { // Get the Direct3D 11 clear flags UINT direct3D11ClearFlags = (clearFlags & Rhi::ClearFlag::DEPTH) ? D3D11_CLEAR_DEPTH : 0u; if (clearFlags & Rhi::ClearFlag::STENCIL) { direct3D11ClearFlags |= D3D11_CLEAR_STENCIL; } if (0 != direct3D11ClearFlags) { // Clear the Direct3D 11 depth stencil view mD3D11DeviceContext->ClearDepthStencilView(framebuffer->getD3D11DepthStencilView(), direct3D11ClearFlags, z, static_cast<UINT8>(stencil)); } } break; } case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::TEXTURE_BUFFER: case Rhi::ResourceType::STRUCTURED_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::TEXTURE_1D: case Rhi::ResourceType::TEXTURE_1D_ARRAY: case Rhi::ResourceType::TEXTURE_2D: case Rhi::ResourceType::TEXTURE_2D_ARRAY: case Rhi::ResourceType::TEXTURE_3D: case Rhi::ResourceType::TEXTURE_CUBE: case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: default: // Not handled in here break; } } else { // In case no render target is currently set we don't have to do anything in here } // End debug event RHI_END_DEBUG_EVENT(this) } void Direct3D11Rhi::drawGraphics(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset, uint32_t numberOfDraws) { // Sanity checks RHI_MATCH_CHECK(*this, indirectBuffer) RHI_ASSERT(mContext, numberOfDraws > 0, "Number of Direct3D 11 draws must not be zero") // Draw indirect ID3D11Buffer* d3D11Buffer = static_cast<const IndirectBuffer&>(indirectBuffer).getD3D11Buffer(); if (1 == numberOfDraws) { mD3D11DeviceContext->DrawInstancedIndirect(d3D11Buffer, indirectBufferOffset); } else if (numberOfDraws > 1) { // Emulate multi-draw-indirect #ifdef RHI_DEBUG beginDebugEvent("Multi-draw-indirect emulation"); #endif for (uint32_t i = 0; i < numberOfDraws; ++i) { mD3D11DeviceContext->DrawInstancedIndirect(d3D11Buffer, indirectBufferOffset); indirectBufferOffset += sizeof(Rhi::DrawArguments); } #ifdef RHI_DEBUG endDebugEvent(); #endif } } void Direct3D11Rhi::drawGraphicsAgs(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset, uint32_t numberOfDraws) { // Sanity checks RHI_MATCH_CHECK(*this, indirectBuffer) RHI_ASSERT(mContext, numberOfDraws > 0, "Number of Direct3D 11 draws must not be zero") RHI_ASSERT(mContext, nullptr != agsDriverExtensionsDX11_MultiDrawInstancedIndirect, "Direct3D 11: AMD AGS function \"agsDriverExtensionsDX11_MultiDrawInstancedIndirect()\" not found") // Draw indirect ID3D11Buffer* d3D11Buffer = static_cast<const IndirectBuffer&>(indirectBuffer).getD3D11Buffer(); if (1 == numberOfDraws) { mD3D11DeviceContext->DrawInstancedIndirect(d3D11Buffer, indirectBufferOffset); } else if (numberOfDraws > 1) { // AMD: "agsDriverExtensionsDX11_MultiDrawInstancedIndirect()" - https://gpuopen-librariesandsdks.github.io/ags/group__mdi.html agsDriverExtensionsDX11_MultiDrawInstancedIndirect(mDirect3D11RuntimeLinking->getAgsContext(), mD3D11DeviceContext, numberOfDraws, d3D11Buffer, indirectBufferOffset, sizeof(Rhi::DrawArguments)); } } void Direct3D11Rhi::drawGraphicsNvApi(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset, uint32_t numberOfDraws) { // Sanity checks RHI_MATCH_CHECK(*this, indirectBuffer) RHI_ASSERT(mContext, numberOfDraws > 0, "Number of Direct3D 11 draws must not be zero") RHI_ASSERT(mContext, nullptr != NvAPI_D3D11_MultiDrawInstancedIndirect, "Direct3D 11: NvAPI function \"NvAPI_D3D11_MultiDrawInstancedIndirect()\" not found") // Draw indirect ID3D11Buffer* d3D11Buffer = static_cast<const IndirectBuffer&>(indirectBuffer).getD3D11Buffer(); if (1 == numberOfDraws) { mD3D11DeviceContext->DrawInstancedIndirect(d3D11Buffer, indirectBufferOffset); } else if (numberOfDraws > 1) { // NVIDIA: "NvAPI_D3D11_MultiDrawInstancedIndirect()" - http://docs.nvidia.com/gameworks/content/gameworkslibrary/coresdk/nvapi/group__dx.html#gaf417228a716d10efcb29fa592795f160 NvAPI_D3D11_MultiDrawInstancedIndirect(mD3D11DeviceContext, numberOfDraws, d3D11Buffer, indirectBufferOffset, sizeof(Rhi::DrawArguments)); } } void Direct3D11Rhi::drawGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset, uint32_t numberOfDraws) { // Sanity checks RHI_ASSERT(mContext, nullptr != emulationData, "The Direct3D 11 emulation data must be valid") RHI_ASSERT(mContext, numberOfDraws > 0, "The number of Direct3D 11 draws must not be zero") // TODO(co) Currently no buffer overflow check due to lack of interface provided data emulationData += indirectBufferOffset; // Emit the draw calls #ifdef RHI_DEBUG if (numberOfDraws > 1) { beginDebugEvent("Multi-draw-indirect emulation"); } #endif for (uint32_t i = 0; i < numberOfDraws; ++i) { const Rhi::DrawArguments& drawArguments = *reinterpret_cast<const Rhi::DrawArguments*>(emulationData); // Draw if (drawArguments.instanceCount > 1 || drawArguments.startInstanceLocation > 0) { // With instancing mD3D11DeviceContext->DrawInstanced( drawArguments.vertexCountPerInstance, // Vertex count per instance (UINT) drawArguments.instanceCount, // Instance count (UINT) drawArguments.startVertexLocation, // Start vertex location (UINT) drawArguments.startInstanceLocation // Start instance location (UINT) ); } else { // Without instancing mD3D11DeviceContext->Draw( drawArguments.vertexCountPerInstance, // Vertex count (UINT) drawArguments.startVertexLocation // Start index location (UINT) ); } // Advance emulationData += sizeof(Rhi::DrawArguments); } #ifdef RHI_DEBUG if (numberOfDraws > 1) { endDebugEvent(); } #endif } void Direct3D11Rhi::drawIndexedGraphics(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset, uint32_t numberOfDraws) { // Sanity checks RHI_MATCH_CHECK(*this, indirectBuffer) RHI_ASSERT(mContext, numberOfDraws > 0, "Number of Direct3D 11 draws must not be zero") // Draw indirect ID3D11Buffer* d3D11Buffer = static_cast<const IndirectBuffer&>(indirectBuffer).getD3D11Buffer(); if (1 == numberOfDraws) { mD3D11DeviceContext->DrawIndexedInstancedIndirect(d3D11Buffer, indirectBufferOffset); } else if (numberOfDraws > 1) { // Emulate multi-draw-indirect #ifdef RHI_DEBUG beginDebugEvent("Multi-indexed-draw-indirect emulation"); #endif for (uint32_t i = 0; i < numberOfDraws; ++i) { mD3D11DeviceContext->DrawIndexedInstancedIndirect(d3D11Buffer, indirectBufferOffset); indirectBufferOffset += sizeof(Rhi::DrawIndexedArguments); } #ifdef RHI_DEBUG endDebugEvent(); #endif } } void Direct3D11Rhi::drawIndexedGraphicsAgs(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset, uint32_t numberOfDraws) { // Sanity checks RHI_MATCH_CHECK(*this, indirectBuffer) RHI_ASSERT(mContext, numberOfDraws > 0, "Number of Direct3D 11 draws must not be zero") RHI_ASSERT(mContext, nullptr != agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect, "Direct3D 11: NvAPI function \"agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect()\" not found") // Draw indirect ID3D11Buffer* d3D11Buffer = static_cast<const IndirectBuffer&>(indirectBuffer).getD3D11Buffer(); if (1 == numberOfDraws) { mD3D11DeviceContext->DrawIndexedInstancedIndirect(d3D11Buffer, indirectBufferOffset); } else if (numberOfDraws > 1) { // AMD: "agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect()" - https://gpuopen-librariesandsdks.github.io/ags/group__mdi.html agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect(mDirect3D11RuntimeLinking->getAgsContext(), mD3D11DeviceContext, numberOfDraws, d3D11Buffer, indirectBufferOffset, sizeof(Rhi::DrawIndexedArguments)); } } void Direct3D11Rhi::drawIndexedGraphicsNvApi(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset, uint32_t numberOfDraws) { // Sanity checks RHI_MATCH_CHECK(*this, indirectBuffer) RHI_ASSERT(mContext, numberOfDraws > 0, "Number of Direct3D 11 draws must not be zero") RHI_ASSERT(mContext, nullptr != NvAPI_D3D11_MultiDrawIndexedInstancedIndirect, "Direct3D 11: NvAPI function \"NvAPI_D3D11_MultiDrawIndexedInstancedIndirect()\" not found") // Draw indirect ID3D11Buffer* d3D11Buffer = static_cast<const IndirectBuffer&>(indirectBuffer).getD3D11Buffer(); if (1 == numberOfDraws) { mD3D11DeviceContext->DrawIndexedInstancedIndirect(d3D11Buffer, indirectBufferOffset); } else if (numberOfDraws > 1) { // NVIDIA: "NvAPI_D3D11_MultiDrawIndexedInstancedIndirect()" - http://docs.nvidia.com/gameworks/content/gameworkslibrary/coresdk/nvapi/group__dx.html#ga04cbd1b776a391e45d38377bd3156f9e NvAPI_D3D11_MultiDrawIndexedInstancedIndirect(mD3D11DeviceContext, numberOfDraws, d3D11Buffer, indirectBufferOffset, sizeof(Rhi::DrawIndexedArguments)); } } void Direct3D11Rhi::drawIndexedGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset, uint32_t numberOfDraws) { // Sanity checks RHI_ASSERT(mContext, nullptr != emulationData, "The Direct3D 11 emulation data must be valid") RHI_ASSERT(mContext, numberOfDraws > 0, "The number of Direct3D 11 draws must not be zero") // TODO(co) Currently no buffer overflow check due to lack of interface provided data emulationData += indirectBufferOffset; // Emit the draw calls #ifdef RHI_DEBUG if (numberOfDraws > 1) { beginDebugEvent("Multi-indexed-draw-indirect emulation"); } #endif for (uint32_t i = 0; i < numberOfDraws; ++i) { const Rhi::DrawIndexedArguments& drawIndexedArguments = *reinterpret_cast<const Rhi::DrawIndexedArguments*>(emulationData); // Draw if (drawIndexedArguments.instanceCount > 1 || drawIndexedArguments.startInstanceLocation > 0) { // With instancing mD3D11DeviceContext->DrawIndexedInstanced( drawIndexedArguments.indexCountPerInstance, // Index count per instance (UINT) drawIndexedArguments.instanceCount, // Instance count (UINT) drawIndexedArguments.startIndexLocation, // Start index location (UINT) drawIndexedArguments.baseVertexLocation, // Base vertex location (INT) drawIndexedArguments.startInstanceLocation // Start instance location (UINT) ); } else { // Without instancing mD3D11DeviceContext->DrawIndexed( drawIndexedArguments.indexCountPerInstance, // Index count (UINT) drawIndexedArguments.startIndexLocation, // Start index location (UINT) drawIndexedArguments.baseVertexLocation // Base vertex location (INT) ); } // Advance emulationData += sizeof(Rhi::DrawIndexedArguments); } #ifdef RHI_DEBUG if (numberOfDraws > 1) { endDebugEvent(); } #endif } //[-------------------------------------------------------] //[ Compute ] //[-------------------------------------------------------] void Direct3D11Rhi::setComputeRootSignature(Rhi::IRootSignature* rootSignature) { if (nullptr != mComputeRootSignature) { mComputeRootSignature->releaseReference(); } mComputeRootSignature = static_cast<RootSignature*>(rootSignature); if (nullptr != mComputeRootSignature) { mComputeRootSignature->addReference(); // Sanity check RHI_MATCH_CHECK(*this, *rootSignature) } } void Direct3D11Rhi::setComputePipelineState(Rhi::IComputePipelineState* computePipelineState) { if (nullptr != computePipelineState) { // Sanity check RHI_MATCH_CHECK(*this, *computePipelineState) // Set compute pipeline state ID3D11ComputeShader* d3d11ComputeShader = static_cast<const ComputePipelineState*>(computePipelineState)->getD3D11ComputeShader(); if (mD3d11ComputeShader != d3d11ComputeShader) { mD3d11ComputeShader = d3d11ComputeShader; mD3D11DeviceContext->CSSetShader(mD3d11ComputeShader, nullptr, 0); } } else { // TODO(co) Handle this situation? } } void Direct3D11Rhi::setComputeResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup) { // Security checks #ifdef RHI_DEBUG { RHI_ASSERT(mContext, nullptr != mComputeRootSignature, "No Direct3D 11 RHI implementation compute root signature set") const Rhi::RootSignature& rootSignature = mComputeRootSignature->getRootSignature(); RHI_ASSERT(mContext, rootParameterIndex < rootSignature.numberOfParameters, "The Direct3D 11 RHI implementation root parameter index is out of bounds") const Rhi::RootParameter& rootParameter = rootSignature.parameters[rootParameterIndex]; RHI_ASSERT(mContext, Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType, "The Direct3D 11 RHI implementation root parameter index doesn't reference a descriptor table") RHI_ASSERT(mContext, nullptr != reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges), "The Direct3D 11 RHI implementation descriptor ranges is a null pointer") } #endif if (nullptr != resourceGroup) { // Sanity check RHI_MATCH_CHECK(*this, *resourceGroup) // Set compute resource group const ResourceGroup* d3d11ResourceGroup = static_cast<ResourceGroup*>(resourceGroup); const uint32_t numberOfResources = d3d11ResourceGroup->getNumberOfResources(); Rhi::IResource** resources = d3d11ResourceGroup->getResources(); const Rhi::RootParameter& rootParameter = mComputeRootSignature->getRootSignature().parameters[rootParameterIndex]; for (uint32_t resourceIndex = 0; resourceIndex < numberOfResources; ++resourceIndex, ++resources) { const Rhi::IResource* resource = *resources; RHI_ASSERT(mContext, nullptr != reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges), "Invalid Direct3D 11 descriptor ranges") const Rhi::DescriptorRange& descriptorRange = reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges)[resourceIndex]; // Check the type of resource to set // TODO(co) Some additional resource type root signature security checks in debug build? const Rhi::ResourceType resourceType = resource->getResourceType(); switch (resourceType) { case Rhi::ResourceType::UNIFORM_BUFFER: { ID3D11Buffer* d3d11Buffers = static_cast<const UniformBuffer*>(resource)->getD3D11Buffer(); const UINT startSlot = descriptorRange.baseShaderRegister; switch (descriptorRange.shaderVisibility) { case Rhi::ShaderVisibility::VERTEX: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 vertex shader visibility") break; case Rhi::ShaderVisibility::TESSELLATION_CONTROL: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 tessellation control shader visibility") break; case Rhi::ShaderVisibility::TESSELLATION_EVALUATION: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 tessellation evaluation shader visibility") break; case Rhi::ShaderVisibility::GEOMETRY: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 geometry shader visibility") break; case Rhi::ShaderVisibility::FRAGMENT: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 fragment shader visibility") break; case Rhi::ShaderVisibility::TASK: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 task shader visibility") break; case Rhi::ShaderVisibility::MESH: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 mesh shader visibility") break; case Rhi::ShaderVisibility::ALL: case Rhi::ShaderVisibility::COMPUTE: mD3D11DeviceContext->CSSetConstantBuffers(startSlot, 1, &d3d11Buffers); break; case Rhi::ShaderVisibility::ALL_GRAPHICS: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 all graphics shader visibility") break; } break; } case Rhi::ResourceType::TEXTURE_BUFFER: case Rhi::ResourceType::STRUCTURED_BUFFER: case Rhi::ResourceType::TEXTURE_1D: case Rhi::ResourceType::TEXTURE_1D_ARRAY: case Rhi::ResourceType::TEXTURE_2D: case Rhi::ResourceType::TEXTURE_2D_ARRAY: case Rhi::ResourceType::TEXTURE_3D: case Rhi::ResourceType::TEXTURE_CUBE: case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: { switch (descriptorRange.rangeType) { case Rhi::DescriptorRangeType::SRV: { ID3D11ShaderResourceView* d3d11ShaderResourceView = nullptr; switch (resourceType) { case Rhi::ResourceType::TEXTURE_BUFFER: d3d11ShaderResourceView = static_cast<const TextureBuffer*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::STRUCTURED_BUFFER: d3d11ShaderResourceView = static_cast<const StructuredBuffer*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_1D: d3d11ShaderResourceView = static_cast<const Texture1D*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_1D_ARRAY: d3d11ShaderResourceView = static_cast<const Texture1DArray*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_2D: d3d11ShaderResourceView = static_cast<const Texture2D*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_2D_ARRAY: d3d11ShaderResourceView = static_cast<const Texture2DArray*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_3D: d3d11ShaderResourceView = static_cast<const Texture3D*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_CUBE: d3d11ShaderResourceView = static_cast<const TextureCube*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: d3d11ShaderResourceView = static_cast<const TextureCubeArray*>(resource)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 RHI implementation resource type") break; } const UINT startSlot = descriptorRange.baseShaderRegister; switch (descriptorRange.shaderVisibility) { case Rhi::ShaderVisibility::VERTEX: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 vertex shader visibility") break; case Rhi::ShaderVisibility::TESSELLATION_CONTROL: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 tessellation control shader visibility") break; case Rhi::ShaderVisibility::TESSELLATION_EVALUATION: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 tessellation evaluation shader visibility") break; case Rhi::ShaderVisibility::GEOMETRY: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 geometry shader visibility") break; case Rhi::ShaderVisibility::FRAGMENT: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 fragment shader visibility") break; case Rhi::ShaderVisibility::TASK: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 task shader visibility") break; case Rhi::ShaderVisibility::MESH: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 mesh shader visibility") break; case Rhi::ShaderVisibility::ALL: case Rhi::ShaderVisibility::COMPUTE: mD3D11DeviceContext->CSSetShaderResources(startSlot, 1, &d3d11ShaderResourceView); break; case Rhi::ShaderVisibility::ALL_GRAPHICS: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 all graphics shader visibility") break; } break; } case Rhi::DescriptorRangeType::UAV: { ID3D11UnorderedAccessView* d3d11UnorderedAccessView = nullptr; switch (resourceType) { case Rhi::ResourceType::TEXTURE_BUFFER: d3d11UnorderedAccessView = static_cast<const TextureBuffer*>(resource)->getD3D11UnorderedAccessView(); break; case Rhi::ResourceType::STRUCTURED_BUFFER: d3d11UnorderedAccessView = static_cast<const StructuredBuffer*>(resource)->getD3D11UnorderedAccessView(); break; case Rhi::ResourceType::TEXTURE_1D: d3d11UnorderedAccessView = static_cast<const Texture1D*>(resource)->getD3D11UnorderedAccessView(); break; case Rhi::ResourceType::TEXTURE_1D_ARRAY: d3d11UnorderedAccessView = static_cast<const Texture1DArray*>(resource)->getD3D11UnorderedAccessView(); break; case Rhi::ResourceType::TEXTURE_2D: d3d11UnorderedAccessView = static_cast<const Texture2D*>(resource)->getD3D11UnorderedAccessView(); break; case Rhi::ResourceType::TEXTURE_2D_ARRAY: d3d11UnorderedAccessView = static_cast<const Texture2DArray*>(resource)->getD3D11UnorderedAccessView(); break; case Rhi::ResourceType::TEXTURE_3D: d3d11UnorderedAccessView = static_cast<const Texture3D*>(resource)->getD3D11UnorderedAccessView(); break; case Rhi::ResourceType::TEXTURE_CUBE: d3d11UnorderedAccessView = static_cast<const TextureCube*>(resource)->getD3D11UnorderedAccessView(); break; case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: d3d11UnorderedAccessView = static_cast<const TextureCubeArray*>(resource)->getD3D11UnorderedAccessView(); break; case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 RHI implementation resource type") break; } const UINT startSlot = descriptorRange.baseShaderRegister; switch (descriptorRange.shaderVisibility) { case Rhi::ShaderVisibility::VERTEX: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 vertex shader visibility") break; case Rhi::ShaderVisibility::TESSELLATION_CONTROL: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 tessellation control shader visibility") break; case Rhi::ShaderVisibility::TESSELLATION_EVALUATION: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 tessellation evaluation shader visibility") break; case Rhi::ShaderVisibility::GEOMETRY: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 geometry shader visibility") break; case Rhi::ShaderVisibility::FRAGMENT: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 fragment shader visibility") break; case Rhi::ShaderVisibility::TASK: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 task shader visibility") break; case Rhi::ShaderVisibility::MESH: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 mesh shader visibility") break; case Rhi::ShaderVisibility::ALL: case Rhi::ShaderVisibility::COMPUTE: mD3D11DeviceContext->CSSetUnorderedAccessViews(startSlot, 1, &d3d11UnorderedAccessView, nullptr); break; case Rhi::ShaderVisibility::ALL_GRAPHICS: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 all graphics shader visibility") break; } break; } case Rhi::DescriptorRangeType::UBV: case Rhi::DescriptorRangeType::SAMPLER: case Rhi::DescriptorRangeType::NUMBER_OF_RANGE_TYPES: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 descriptor range type") break; } break; } case Rhi::ResourceType::VERTEX_BUFFER: { RHI_ASSERT(mContext, Rhi::DescriptorRangeType::SRV == descriptorRange.rangeType || Rhi::DescriptorRangeType::UAV == descriptorRange.rangeType, "Direct3D 11 vertex buffer must bound at SRV or UAV descriptor range type") RHI_ASSERT(mContext, Rhi::ShaderVisibility::ALL == descriptorRange.shaderVisibility || Rhi::ShaderVisibility::COMPUTE == descriptorRange.shaderVisibility, "Direct3D 11 descriptor range shader visibility must be \"ALL\" or \"COMPUTE\"") if (Rhi::DescriptorRangeType::SRV == descriptorRange.rangeType) { ID3D11ShaderResourceView* d3d11ShaderResourceView = static_cast<const VertexBuffer*>(resource)->getD3D11ShaderResourceView(); mD3D11DeviceContext->CSSetShaderResources(descriptorRange.baseShaderRegister, 1, &d3d11ShaderResourceView); } else { // Set UAV ID3D11UnorderedAccessView* d3d11UnorderedAccessView = static_cast<const VertexBuffer*>(resource)->getD3D11UnorderedAccessView(); mD3D11DeviceContext->CSSetUnorderedAccessViews(descriptorRange.baseShaderRegister, 1, &d3d11UnorderedAccessView, nullptr); } break; } case Rhi::ResourceType::INDEX_BUFFER: { RHI_ASSERT(mContext, Rhi::DescriptorRangeType::SRV == descriptorRange.rangeType || Rhi::DescriptorRangeType::UAV == descriptorRange.rangeType, "Direct3D 11 index buffer must bound at SRV or UAV descriptor range type") RHI_ASSERT(mContext, Rhi::ShaderVisibility::ALL == descriptorRange.shaderVisibility || Rhi::ShaderVisibility::COMPUTE == descriptorRange.shaderVisibility, "Direct3D 11 descriptor range shader visibility must be \"ALL\" or \"COMPUTE\"") if (Rhi::DescriptorRangeType::SRV == descriptorRange.rangeType) { ID3D11ShaderResourceView* d3d11ShaderResourceView = static_cast<const IndexBuffer*>(resource)->getD3D11ShaderResourceView(); mD3D11DeviceContext->CSSetShaderResources(descriptorRange.baseShaderRegister, 1, &d3d11ShaderResourceView); } else { ID3D11UnorderedAccessView* d3d11UnorderedAccessView = static_cast<const IndexBuffer*>(resource)->getD3D11UnorderedAccessView(); mD3D11DeviceContext->CSSetUnorderedAccessViews(descriptorRange.baseShaderRegister, 1, &d3d11UnorderedAccessView, nullptr); } break; } case Rhi::ResourceType::INDIRECT_BUFFER: { RHI_ASSERT(mContext, Rhi::DescriptorRangeType::SRV == descriptorRange.rangeType || Rhi::DescriptorRangeType::UAV == descriptorRange.rangeType, "Direct3D 11 indirect buffer must bound at SRV or UAV descriptor range type") RHI_ASSERT(mContext, Rhi::ShaderVisibility::ALL == descriptorRange.shaderVisibility || Rhi::ShaderVisibility::COMPUTE == descriptorRange.shaderVisibility, "Direct3D 11 descriptor range shader visibility must be \"ALL\" or \"COMPUTE\"") if (Rhi::DescriptorRangeType::SRV == descriptorRange.rangeType) { ID3D11ShaderResourceView* d3d11ShaderResourceView = static_cast<const IndirectBuffer*>(resource)->getD3D11ShaderResourceView(); mD3D11DeviceContext->CSSetShaderResources(descriptorRange.baseShaderRegister, 1, &d3d11ShaderResourceView); } else { ID3D11UnorderedAccessView* d3d11UnorderedAccessView = static_cast<const IndirectBuffer*>(resource)->getD3D11UnorderedAccessView(); mD3D11DeviceContext->CSSetUnorderedAccessViews(descriptorRange.baseShaderRegister, 1, &d3d11UnorderedAccessView, nullptr); } break; } case Rhi::ResourceType::SAMPLER_STATE: { ID3D11SamplerState* d3d11SamplerState = static_cast<const SamplerState*>(resource)->getD3D11SamplerState(); const UINT startSlot = descriptorRange.baseShaderRegister; switch (descriptorRange.shaderVisibility) { case Rhi::ShaderVisibility::VERTEX: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 vertex shader visibility") break; case Rhi::ShaderVisibility::TESSELLATION_CONTROL: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 tessellation control shader visibility") break; case Rhi::ShaderVisibility::TESSELLATION_EVALUATION: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 tessellation evaluation shader visibility") break; case Rhi::ShaderVisibility::GEOMETRY: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 geometry shader visibility") break; case Rhi::ShaderVisibility::FRAGMENT: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 fragment shader visibility") break; case Rhi::ShaderVisibility::TASK: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 task shader visibility") break; case Rhi::ShaderVisibility::MESH: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 mesh shader visibility") break; case Rhi::ShaderVisibility::ALL: case Rhi::ShaderVisibility::COMPUTE: mD3D11DeviceContext->CSSetSamplers(startSlot, 1, &d3d11SamplerState); break; case Rhi::ShaderVisibility::ALL_GRAPHICS: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 all graphics shader visibility") break; } break; } case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: RHI_ASSERT(mContext, false, "Invalid Direct3D 11 RHI implementation resource type") break; } } } else { // TODO(co) Handle this situation? } } void Direct3D11Rhi::dispatchCompute(uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ) { mD3D11DeviceContext->Dispatch(groupCountX, groupCountY, groupCountZ); { // TODO(co) Compute shader: "D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing CS shader resource slot 0 to NULL. [ STATE_SETTING WARNING #2097316: DEVICE_CSSETSHADERRESOURCES_HAZARD]" ID3D11UnorderedAccessView* d3d11UnorderedAccessView = nullptr; for (uint32_t i = 0; i < 8; ++i) { mD3D11DeviceContext->CSSetUnorderedAccessViews(i, 1, &d3d11UnorderedAccessView, nullptr); } } } //[-------------------------------------------------------] //[ Resource ] //[-------------------------------------------------------] void Direct3D11Rhi::resolveMultisampleFramebuffer(Rhi::IRenderTarget& destinationRenderTarget, Rhi::IFramebuffer& sourceMultisampleFramebuffer) { // Sanity checks RHI_MATCH_CHECK(*this, destinationRenderTarget) RHI_MATCH_CHECK(*this, sourceMultisampleFramebuffer) // Evaluate the render target type switch (destinationRenderTarget.getResourceType()) { case Rhi::ResourceType::SWAP_CHAIN: { // Get the Direct3D 11 swap chain instance // TODO(co) Implement me, not that important in practice so not directly implemented // SwapChain& swapChain = static_cast<SwapChain&>(destinationRenderTarget); break; } case Rhi::ResourceType::FRAMEBUFFER: { // Get the Direct3D 11 framebuffer instances const Framebuffer& direct3D11DestinationFramebuffer = static_cast<const Framebuffer&>(destinationRenderTarget); const Framebuffer& direct3D11SourceMultisampleFramebuffer = static_cast<const Framebuffer&>(sourceMultisampleFramebuffer); // Process all Direct3D 11 render target textures if (direct3D11DestinationFramebuffer.getNumberOfColorTextures() > 0 && direct3D11SourceMultisampleFramebuffer.getNumberOfColorTextures() > 0) { const uint32_t numberOfColorTextures = (direct3D11DestinationFramebuffer.getNumberOfColorTextures() < direct3D11SourceMultisampleFramebuffer.getNumberOfColorTextures()) ? direct3D11DestinationFramebuffer.getNumberOfColorTextures() : direct3D11SourceMultisampleFramebuffer.getNumberOfColorTextures(); Rhi::ITexture** destinationTexture = direct3D11DestinationFramebuffer.getColorTextures(); Rhi::ITexture** sourceTexture = direct3D11SourceMultisampleFramebuffer.getColorTextures(); Rhi::ITexture** sourceTextureEnd = sourceTexture + numberOfColorTextures; for (; sourceTexture < sourceTextureEnd; ++sourceTexture, ++destinationTexture) { // Valid Direct3D 11 render target views? if (nullptr != *destinationTexture && nullptr != *sourceTexture) { const Texture2D* d3d11DestinationTexture2D = static_cast<const Texture2D*>(*destinationTexture); const Texture2D* d3d11SourceTexture2D = static_cast<const Texture2D*>(*sourceTexture); mD3D11DeviceContext->ResolveSubresource(d3d11DestinationTexture2D->getD3D11Texture2D(), D3D11CalcSubresource(0, 0, 1), d3d11SourceTexture2D->getD3D11Texture2D(), D3D11CalcSubresource(0, 0, 1), Mapping::getDirect3D11Format(d3d11DestinationTexture2D->getTextureFormat())); } } } // Process Direct3D 11 depth stencil texture if (nullptr != direct3D11DestinationFramebuffer.getDepthStencilTexture() && nullptr != direct3D11SourceMultisampleFramebuffer.getDepthStencilTexture()) { const Texture2D* d3d11DestinationTexture2D = static_cast<const Texture2D*>(direct3D11DestinationFramebuffer.getDepthStencilTexture()); const Texture2D* d3d11SourceTexture2D = static_cast<const Texture2D*>(direct3D11SourceMultisampleFramebuffer.getDepthStencilTexture()); mD3D11DeviceContext->ResolveSubresource(d3d11DestinationTexture2D->getD3D11Texture2D(), D3D11CalcSubresource(0, 0, 1), d3d11SourceTexture2D->getD3D11Texture2D(), D3D11CalcSubresource(0, 0, 1), Mapping::getDirect3D11Format(d3d11DestinationTexture2D->getTextureFormat())); } break; } case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::TEXTURE_BUFFER: case Rhi::ResourceType::STRUCTURED_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::TEXTURE_1D: case Rhi::ResourceType::TEXTURE_1D_ARRAY: case Rhi::ResourceType::TEXTURE_2D: case Rhi::ResourceType::TEXTURE_2D_ARRAY: case Rhi::ResourceType::TEXTURE_3D: case Rhi::ResourceType::TEXTURE_CUBE: case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: default: // Not handled in here break; } } void Direct3D11Rhi::copyResource(Rhi::IResource& destinationResource, Rhi::IResource& sourceResource) { // Sanity checks RHI_MATCH_CHECK(*this, destinationResource) RHI_MATCH_CHECK(*this, sourceResource) // Evaluate the render target type switch (destinationResource.getResourceType()) { case Rhi::ResourceType::TEXTURE_2D: if (sourceResource.getResourceType() == Rhi::ResourceType::TEXTURE_2D) { // Get the Direct3D 11 texture 2D instances const Texture2D& direct3D11DestinationTexture2D = static_cast<const Texture2D&>(destinationResource); const Texture2D& direct3D11SourceTexture2D = static_cast<const Texture2D&>(sourceResource); // Copy resource, but only the top-level mipmap mD3D11DeviceContext->CopySubresourceRegion(direct3D11DestinationTexture2D.getD3D11Texture2D(), 0, 0, 0, 0, direct3D11SourceTexture2D.getD3D11Texture2D(), 0, nullptr); } else { // Error! RHI_ASSERT(mContext, false, "Failed to copy Direct3D 11 resource") } break; case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::TEXTURE_BUFFER: case Rhi::ResourceType::STRUCTURED_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::TEXTURE_1D: case Rhi::ResourceType::TEXTURE_1D_ARRAY: case Rhi::ResourceType::TEXTURE_2D_ARRAY: case Rhi::ResourceType::TEXTURE_3D: case Rhi::ResourceType::TEXTURE_CUBE: case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: default: // Not handled in here break; } } void Direct3D11Rhi::generateMipmaps(Rhi::IResource& resource) { // Sanity checks RHI_MATCH_CHECK(*this, resource) RHI_ASSERT(mContext, resource.getResourceType() == Rhi::ResourceType::TEXTURE_2D, "TODO(co) Mipmaps can only be generated for Direct3D 11 2D texture resources") // Generate mipmaps mD3D11DeviceContext->GenerateMips(static_cast<Texture2D&>(resource).getD3D11ShaderResourceView()); } void Direct3D11Rhi::generateAsynchronousDeferredMipmaps(Rhi::ITexture& texture, ID3D11ShaderResourceView& d3d11ShaderResourceView) { if (mCapabilities.nativeMultithreading) { std::lock_guard<std::mutex> generateAsynchronousMipmapsForTexturesMutexLock(mGenerateAsynchronousMipmapsForTexturesMutex); mGenerateAsynchronousMipmapsForTextures.push_back(&texture); texture.addReference(); } else { mD3D11DeviceContext->GenerateMips(&d3d11ShaderResourceView); } } //[-------------------------------------------------------] //[ Query ] //[-------------------------------------------------------] void Direct3D11Rhi::resetQueryPool([[maybe_unused]] Rhi::IQueryPool& queryPool, [[maybe_unused]] uint32_t firstQueryIndex, [[maybe_unused]] uint32_t numberOfQueries) { // Sanity checks RHI_MATCH_CHECK(*this, queryPool) RHI_ASSERT(mContext, firstQueryIndex < static_cast<const QueryPool&>(queryPool).getNumberOfQueries(), "Direct3D 11 out-of-bounds query index") RHI_ASSERT(mContext, (firstQueryIndex + numberOfQueries) <= static_cast<const QueryPool&>(queryPool).getNumberOfQueries(), "Direct3D 11 out-of-bounds query index") // Nothing to do in here for Direct3D 11 } void Direct3D11Rhi::beginQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex, uint32_t) { // Sanity check RHI_MATCH_CHECK(*this, queryPool) // Query pool type dependent processing const QueryPool& d3d11QueryPool = static_cast<const QueryPool&>(queryPool); RHI_ASSERT(mContext, queryIndex < d3d11QueryPool.getNumberOfQueries(), "Direct3D 11 out-of-bounds query index") switch (d3d11QueryPool.getQueryType()) { case Rhi::QueryType::OCCLUSION: case Rhi::QueryType::PIPELINE_STATISTICS: mD3D11DeviceContext->Begin(d3d11QueryPool.getD3D11Queries()[queryIndex]); break; case Rhi::QueryType::TIMESTAMP: RHI_ASSERT(mContext, false, "Direct3D 11 begin query isn't allowed for timestamp queries, use \"Rhi::Command::WriteTimestampQuery\" instead") break; } } void Direct3D11Rhi::endQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex) { // Sanity check RHI_MATCH_CHECK(*this, queryPool) // Query pool type dependent processing const QueryPool& d3d11QueryPool = static_cast<const QueryPool&>(queryPool); RHI_ASSERT(mContext, queryIndex < d3d11QueryPool.getNumberOfQueries(), "Direct3D 11 out-of-bounds query index") switch (d3d11QueryPool.getQueryType()) { case Rhi::QueryType::OCCLUSION: case Rhi::QueryType::PIPELINE_STATISTICS: mD3D11DeviceContext->End(d3d11QueryPool.getD3D11Queries()[queryIndex]); break; case Rhi::QueryType::TIMESTAMP: RHI_ASSERT(mContext, false, "Direct3D 11 end query isn't allowed for timestamp queries, use \"Rhi::Command::WriteTimestampQuery\" instead") break; } } void Direct3D11Rhi::writeTimestampQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex) { // Sanity check RHI_MATCH_CHECK(*this, queryPool) // Query pool type dependent processing const QueryPool& d3d11QueryPool = static_cast<const QueryPool&>(queryPool); RHI_ASSERT(mContext, queryIndex < d3d11QueryPool.getNumberOfQueries(), "Direct3D 11 out-of-bounds query index") switch (d3d11QueryPool.getQueryType()) { case Rhi::QueryType::OCCLUSION: RHI_ASSERT(mContext, false, "Direct3D 11 write timestamp query isn't allowed for occlusion queries, use \"Rhi::Command::BeginQuery\" and \"Rhi::Command::EndQuery\" instead") break; case Rhi::QueryType::PIPELINE_STATISTICS: RHI_ASSERT(mContext, false, "Direct3D 11 write timestamp query isn't allowed for pipeline statistics queries, use \"Rhi::Command::BeginQuery\" and \"Rhi::Command::EndQuery\" instead") break; case Rhi::QueryType::TIMESTAMP: mD3D11DeviceContext->End(d3d11QueryPool.getD3D11Queries()[queryIndex]); break; } } //[-------------------------------------------------------] //[ Debug ] //[-------------------------------------------------------] #ifdef RHI_DEBUG void Direct3D11Rhi::setDebugMarker(const char* name) { if (nullptr != mD3DUserDefinedAnnotation) { RHI_ASSERT(mContext, nullptr != name, "Direct3D 11 debug marker names must not be a null pointer") RHI_ASSERT(mContext, strlen(name) < 256, "Direct3D 11 debug marker names must not have more than 255 characters") wchar_t unicodeName[256]; std::mbstowcs(unicodeName, name, 256); mD3DUserDefinedAnnotation->SetMarker(unicodeName); } } void Direct3D11Rhi::beginDebugEvent(const char* name) { if (nullptr != mD3DUserDefinedAnnotation) { RHI_ASSERT(mContext, nullptr != name, "Direct3D 11 debug event names must not be a null pointer") RHI_ASSERT(mContext, strlen(name) < 256, "Direct3D 11 debug event names must not have more than 255 characters") wchar_t unicodeName[256]; std::mbstowcs(unicodeName, name, 256); mD3DUserDefinedAnnotation->BeginEvent(unicodeName); } } void Direct3D11Rhi::endDebugEvent() { if (nullptr != mD3DUserDefinedAnnotation) { mD3DUserDefinedAnnotation->EndEvent(); } } #endif //[-------------------------------------------------------] //[ Public virtual Rhi::IRhi methods ] //[-------------------------------------------------------] bool Direct3D11Rhi::isDebugEnabled() { // Don't check for the "RHI_DEBUG" preprocessor definition, even if debug // is disabled it has to be possible to use this function for an additional security check // -> Maybe a debugger/profiler ignores the debug state // -> Maybe someone manipulated the binary to enable the debug state, adding a second check // makes it a little bit more time consuming to hack the binary :D (but of course, this is no 100% security) return (nullptr != mD3DUserDefinedAnnotation && mD3DUserDefinedAnnotation->GetStatus() != 0); } //[-------------------------------------------------------] //[ Shader language ] //[-------------------------------------------------------] uint32_t Direct3D11Rhi::getNumberOfShaderLanguages() const { uint32_t numberOfShaderLanguages = 1; // HLSL support is always there // Done, return the number of supported shader languages return numberOfShaderLanguages; } const char* Direct3D11Rhi::getShaderLanguageName([[maybe_unused]] uint32_t index) const { RHI_ASSERT(mContext, index < getNumberOfShaderLanguages(), "Direct3D 11: Shader language index is out-of-bounds") return ::detail::HLSL_NAME; } Rhi::IShaderLanguage* Direct3D11Rhi::getShaderLanguage(const char* shaderLanguageName) { // In case "shaderLanguage" is a null pointer, use the default shader language if (nullptr != shaderLanguageName) { // Optimization: Check for shader language name pointer match, first if (::detail::HLSL_NAME == shaderLanguageName || !stricmp(shaderLanguageName, ::detail::HLSL_NAME)) { // If required, create the HLSL shader language instance right now if (nullptr == mShaderLanguageHlsl) { mShaderLanguageHlsl = RHI_NEW(mContext, ShaderLanguageHlsl)(*this); mShaderLanguageHlsl->addReference(); // Internal RHI reference } // Return the shader language instance return mShaderLanguageHlsl; } // Error! return nullptr; } // Return the HLSL shader language instance as default return getShaderLanguage(::detail::HLSL_NAME); } //[-------------------------------------------------------] //[ Resource creation ] //[-------------------------------------------------------] Rhi::IRenderPass* Direct3D11Rhi::createRenderPass(uint32_t numberOfColorAttachments, const Rhi::TextureFormat::Enum* colorAttachmentTextureFormats, Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat, uint8_t numberOfMultisamples RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { return RHI_NEW(mContext, RenderPass)(*this, numberOfColorAttachments, colorAttachmentTextureFormats, depthStencilAttachmentTextureFormat, numberOfMultisamples RHI_RESOURCE_DEBUG_PASS_PARAMETER); } Rhi::IQueryPool* Direct3D11Rhi::createQueryPool(Rhi::QueryType queryType, uint32_t numberOfQueries RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { RHI_ASSERT(mContext, numberOfQueries > 0, "Direct3D 11: Number of queries mustn't be zero") return RHI_NEW(mContext, QueryPool)(*this, queryType, numberOfQueries RHI_RESOURCE_DEBUG_PASS_PARAMETER); } Rhi::ISwapChain* Direct3D11Rhi::createSwapChain(Rhi::IRenderPass& renderPass, Rhi::WindowHandle windowHandle, bool RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { // Sanity checks RHI_MATCH_CHECK(*this, renderPass) RHI_ASSERT(mContext, NULL_HANDLE != windowHandle.nativeWindowHandle, "Direct3D 11: The provided native window handle must not be a null handle") // Create the swap chain return RHI_NEW(mContext, SwapChain)(renderPass, windowHandle RHI_RESOURCE_DEBUG_PASS_PARAMETER); } Rhi::IFramebuffer* Direct3D11Rhi::createFramebuffer(Rhi::IRenderPass& renderPass, const Rhi::FramebufferAttachment* colorFramebufferAttachments, const Rhi::FramebufferAttachment* depthStencilFramebufferAttachment RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { // Sanity check RHI_MATCH_CHECK(*this, renderPass) // Create the framebuffer return RHI_NEW(mContext, Framebuffer)(renderPass, colorFramebufferAttachments, depthStencilFramebufferAttachment RHI_RESOURCE_DEBUG_PASS_PARAMETER); } Rhi::IBufferManager* Direct3D11Rhi::createBufferManager() { return RHI_NEW(mContext, BufferManager)(*this); } Rhi::ITextureManager* Direct3D11Rhi::createTextureManager() { return RHI_NEW(mContext, TextureManager)(*this); } Rhi::IRootSignature* Direct3D11Rhi::createRootSignature(const Rhi::RootSignature& rootSignature RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { return RHI_NEW(mContext, RootSignature)(*this, rootSignature RHI_RESOURCE_DEBUG_PASS_PARAMETER); } Rhi::IGraphicsPipelineState* Direct3D11Rhi::createGraphicsPipelineState(const Rhi::GraphicsPipelineState& graphicsPipelineState RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { // Sanity checks RHI_ASSERT(mContext, nullptr != graphicsPipelineState.rootSignature, "Direct3D 11: Invalid graphics pipeline state root signature") RHI_ASSERT(mContext, nullptr != graphicsPipelineState.graphicsProgram, "Direct3D 11: Invalid graphics pipeline state graphics program") RHI_ASSERT(mContext, nullptr != graphicsPipelineState.renderPass, "Direct3D 11: Invalid graphics pipeline state render pass") // Create graphics pipeline state uint16_t id = 0; if (GraphicsPipelineStateMakeId.CreateID(id)) { return RHI_NEW(mContext, GraphicsPipelineState)(*this, graphicsPipelineState, id RHI_RESOURCE_DEBUG_PASS_PARAMETER); } // Error: Ensure a correct reference counter behaviour graphicsPipelineState.rootSignature->addReference(); graphicsPipelineState.rootSignature->releaseReference(); graphicsPipelineState.graphicsProgram->addReference(); graphicsPipelineState.graphicsProgram->releaseReference(); graphicsPipelineState.renderPass->addReference(); graphicsPipelineState.renderPass->releaseReference(); return nullptr; } Rhi::IComputePipelineState* Direct3D11Rhi::createComputePipelineState(Rhi::IRootSignature& rootSignature, Rhi::IComputeShader& computeShader RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { // Sanity checks RHI_MATCH_CHECK(*this, rootSignature) RHI_MATCH_CHECK(*this, computeShader) // Ensure a correct reference counter behaviour rootSignature.addReference(); rootSignature.releaseReference(); // Create the compute pipeline state uint16_t id = 0; if (ComputePipelineStateMakeId.CreateID(id)) { return RHI_NEW(mContext, ComputePipelineState)(*this, computeShader, id RHI_RESOURCE_DEBUG_PASS_PARAMETER); } // Error: Ensure a correct reference counter behaviour computeShader.addReference(); computeShader.releaseReference(); return nullptr; } Rhi::ISamplerState* Direct3D11Rhi::createSamplerState(const Rhi::SamplerState& samplerState RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { return RHI_NEW(mContext, SamplerState)(*this, samplerState RHI_RESOURCE_DEBUG_PASS_PARAMETER); } //[-------------------------------------------------------] //[ Resource handling ] //[-------------------------------------------------------] bool Direct3D11Rhi::map(Rhi::IResource& resource, uint32_t subresource, Rhi::MapType mapType, uint32_t mapFlags, Rhi::MappedSubresource& mappedSubresource) { // The "Rhi::MapType" values directly map to Direct3D 10 & 11 constants, do not change them // The "Rhi::MappedSubresource" structure directly maps to Direct3D 11, do not change it // Define helper macro #define TEXTURE_RESOURCE(type, typeClass) \ case type: \ { \ bool result = false; \ RHI_BEGIN_DEBUG_EVENT_FUNCTION(this) \ ID3D11Resource* d3d11Resource = nullptr; \ static_cast<typeClass&>(resource).getD3D11ShaderResourceView()->GetResource(&d3d11Resource); \ if (nullptr != d3d11Resource) \ { \ result = (S_OK == mD3D11DeviceContext->Map(d3d11Resource, subresource, static_cast<D3D11_MAP>(mapType), mapFlags, reinterpret_cast<D3D11_MAPPED_SUBRESOURCE*>(&mappedSubresource))); \ d3d11Resource->Release(); \ } \ RHI_END_DEBUG_EVENT(this) \ return result; \ } // Evaluate the resource type switch (resource.getResourceType()) { case Rhi::ResourceType::VERTEX_BUFFER: return (S_OK == mD3D11DeviceContext->Map(static_cast<VertexBuffer&>(resource).getD3D11Buffer(), subresource, static_cast<D3D11_MAP>(mapType), mapFlags, reinterpret_cast<D3D11_MAPPED_SUBRESOURCE*>(&mappedSubresource))); case Rhi::ResourceType::INDEX_BUFFER: return (S_OK == mD3D11DeviceContext->Map(static_cast<IndexBuffer&>(resource).getD3D11Buffer(), subresource, static_cast<D3D11_MAP>(mapType), mapFlags, reinterpret_cast<D3D11_MAPPED_SUBRESOURCE*>(&mappedSubresource))); case Rhi::ResourceType::TEXTURE_BUFFER: return (S_OK == mD3D11DeviceContext->Map(static_cast<TextureBuffer&>(resource).getD3D11Buffer(), subresource, static_cast<D3D11_MAP>(mapType), mapFlags, reinterpret_cast<D3D11_MAPPED_SUBRESOURCE*>(&mappedSubresource))); case Rhi::ResourceType::STRUCTURED_BUFFER: return (S_OK == mD3D11DeviceContext->Map(static_cast<StructuredBuffer&>(resource).getD3D11Buffer(), subresource, static_cast<D3D11_MAP>(mapType), mapFlags, reinterpret_cast<D3D11_MAPPED_SUBRESOURCE*>(&mappedSubresource))); case Rhi::ResourceType::INDIRECT_BUFFER: return (S_OK == mD3D11DeviceContext->Map(static_cast<IndirectBuffer&>(resource).getStagingD3D11Buffer(), subresource, static_cast<D3D11_MAP>(mapType), mapFlags, reinterpret_cast<D3D11_MAPPED_SUBRESOURCE*>(&mappedSubresource))); case Rhi::ResourceType::UNIFORM_BUFFER: return (S_OK == mD3D11DeviceContext->Map(static_cast<UniformBuffer&>(resource).getD3D11Buffer(), subresource, static_cast<D3D11_MAP>(mapType), mapFlags, reinterpret_cast<D3D11_MAPPED_SUBRESOURCE*>(&mappedSubresource))); TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_1D, Texture1D) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_1D_ARRAY, Texture1DArray) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_2D, Texture2D) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_2D_ARRAY, Texture2DArray) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_3D, Texture3D) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_CUBE, TextureCube) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_CUBE_ARRAY, TextureCubeArray) case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: default: // Nothing we can map, set known return values mappedSubresource.data = nullptr; mappedSubresource.rowPitch = 0; mappedSubresource.depthPitch = 0; // Error! return false; } // Undefine helper macro #undef TEXTURE_RESOURCE } void Direct3D11Rhi::unmap(Rhi::IResource& resource, uint32_t subresource) { // Define helper macro #define TEXTURE_RESOURCE(type, typeClass) \ case type: \ { \ ID3D11Resource* d3d11Resource = nullptr; \ static_cast<typeClass&>(resource).getD3D11ShaderResourceView()->GetResource(&d3d11Resource); \ if (nullptr != d3d11Resource) \ { \ mD3D11DeviceContext->Unmap(d3d11Resource, subresource); \ d3d11Resource->Release(); \ } \ break; \ } // Evaluate the resource type switch (resource.getResourceType()) { case Rhi::ResourceType::VERTEX_BUFFER: mD3D11DeviceContext->Unmap(static_cast<VertexBuffer&>(resource).getD3D11Buffer(), subresource); break; case Rhi::ResourceType::INDEX_BUFFER: mD3D11DeviceContext->Unmap(static_cast<IndexBuffer&>(resource).getD3D11Buffer(), subresource); break; case Rhi::ResourceType::TEXTURE_BUFFER: mD3D11DeviceContext->Unmap(static_cast<TextureBuffer&>(resource).getD3D11Buffer(), subresource); break; case Rhi::ResourceType::STRUCTURED_BUFFER: mD3D11DeviceContext->Unmap(static_cast<StructuredBuffer&>(resource).getD3D11Buffer(), subresource); break; case Rhi::ResourceType::INDIRECT_BUFFER: { IndirectBuffer& indirectBuffer = static_cast<IndirectBuffer&>(resource); ID3D11Buffer* stagingD3D11Buffer = indirectBuffer.getStagingD3D11Buffer(); mD3D11DeviceContext->Unmap(stagingD3D11Buffer, subresource); mD3D11DeviceContext->CopyResource(indirectBuffer.getD3D11Buffer(), stagingD3D11Buffer); break; } case Rhi::ResourceType::UNIFORM_BUFFER: mD3D11DeviceContext->Unmap(static_cast<UniformBuffer&>(resource).getD3D11Buffer(), subresource); break; TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_1D, Texture1D) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_1D_ARRAY, Texture1DArray) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_2D, Texture2D) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_2D_ARRAY, Texture2DArray) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_3D, Texture3D) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_CUBE, TextureCube) TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_CUBE_ARRAY, TextureCubeArray) case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: default: // Nothing we can unmap break; } // Undefine helper macro #undef TEXTURE_RESOURCE } bool Direct3D11Rhi::getQueryPoolResults(Rhi::IQueryPool& queryPool, [[maybe_unused]] uint32_t numberOfDataBytes, uint8_t* data, uint32_t firstQueryIndex, uint32_t numberOfQueries, uint32_t strideInBytes, uint32_t queryResultFlags) { // Sanity checks RHI_MATCH_CHECK(*this, queryPool) RHI_ASSERT(mContext, numberOfDataBytes >= sizeof(UINT64), "Direct3D 11 out-of-memory query access") RHI_ASSERT(mContext, 1 == numberOfQueries || strideInBytes > 0, "Direct3D 11 invalid stride in bytes") RHI_ASSERT(mContext, numberOfDataBytes >= strideInBytes * numberOfQueries, "Direct3D 11 out-of-memory query access") RHI_ASSERT(mContext, nullptr != data, "Direct3D 11 out-of-memory query access") RHI_ASSERT(mContext, numberOfQueries > 0, "Direct3D 11 number of queries mustn't be zero") // Query pool type dependent processing bool resultAvailable = true; const QueryPool& d3d11QueryPool = static_cast<const QueryPool&>(queryPool); RHI_ASSERT(mContext, firstQueryIndex < d3d11QueryPool.getNumberOfQueries(), "Direct3D 11 out-of-bounds query index") RHI_ASSERT(mContext, (firstQueryIndex + numberOfQueries) <= d3d11QueryPool.getNumberOfQueries(), "Direct3D 11 out-of-bounds query index") const bool waitForResult = ((queryResultFlags & Rhi::QueryResultFlags::WAIT) != 0); switch (d3d11QueryPool.getQueryType()) { case Rhi::QueryType::OCCLUSION: case Rhi::QueryType::TIMESTAMP: // TODO(co) Convert time to nanoseconds, see e.g. http://reedbeta.com/blog/gpu-profiling-101/ { uint8_t* currentData = data; ID3D11Query** d3D11Queries = d3d11QueryPool.getD3D11Queries(); for (uint32_t i = 0; i < numberOfQueries; ++i) { HRESULT d3d11QueryResult = S_FALSE; do { d3d11QueryResult = mD3D11DeviceContext->GetData(d3D11Queries[firstQueryIndex + i], currentData, sizeof(UINT64), 0); } while (waitForResult && S_OK != d3d11QueryResult); if (S_FALSE == d3d11QueryResult) { // Result not ready resultAvailable = false; break; } currentData += strideInBytes; } break; } case Rhi::QueryType::PIPELINE_STATISTICS: { static_assert(sizeof(Rhi::PipelineStatisticsQueryResult) == sizeof(D3D11_QUERY_DATA_PIPELINE_STATISTICS), "Direct3D 11 structure mismatch detected"); RHI_ASSERT(mContext, numberOfDataBytes >= sizeof(Rhi::PipelineStatisticsQueryResult), "Direct3D 11 out-of-memory query access") RHI_ASSERT(mContext, 1 == numberOfQueries || strideInBytes >= sizeof(Rhi::PipelineStatisticsQueryResult), "Direct3D 11 out-of-memory query access") uint8_t* currentData = data; ID3D11Query** d3D11Queries = d3d11QueryPool.getD3D11Queries(); for (uint32_t i = 0; i < numberOfQueries; ++i) { HRESULT d3d11QueryResult = S_FALSE; do { d3d11QueryResult = mD3D11DeviceContext->GetData(d3D11Queries[firstQueryIndex + i], currentData, sizeof(D3D11_QUERY_DATA_PIPELINE_STATISTICS), 0); } while (waitForResult && S_OK != d3d11QueryResult); if (S_FALSE == d3d11QueryResult) { // Result not ready resultAvailable = false; break; } currentData += strideInBytes; } break; } } // Done return resultAvailable; } //[-------------------------------------------------------] //[ Operation ] //[-------------------------------------------------------] void Direct3D11Rhi::dispatchCommandBuffer(const Rhi::CommandBuffer& commandBuffer) { // Sanity check RHI_ASSERT(mContext, !commandBuffer.isEmpty(), "The Direct3D 11 command buffer to dispatch mustn't be empty") // Generate asynchronous mipmaps for textures // -> For multithreading we could also use a deferred context, but in first tests there were random "FinishCommandList()"/"ExecuteCommandList()" state glitches // when not fully resetting the context states. On the other hand, fully resetting the context states isn't recommended. Since we just need to be able to // trigger the generation of mipmaps for textures asynchronously it's not really worth using those more complex deferred contexts for such a simple task. if (mCapabilities.nativeMultithreading) { std::lock_guard<std::mutex> generateAsynchronousMipmapsForTexturesMutexLock(mGenerateAsynchronousMipmapsForTexturesMutex); if (!mGenerateAsynchronousMipmapsForTextures.empty()) { for (Rhi::ITexture* texture : mGenerateAsynchronousMipmapsForTextures) { ID3D11ShaderResourceView* d3d11ShaderResourceView = nullptr; switch (texture->getResourceType()) { case Rhi::ResourceType::TEXTURE_1D: d3d11ShaderResourceView = static_cast<Texture1D*>(texture)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_1D_ARRAY: d3d11ShaderResourceView = static_cast<Texture1DArray*>(texture)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_2D: d3d11ShaderResourceView = static_cast<Texture2D*>(texture)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_2D_ARRAY: d3d11ShaderResourceView = static_cast<Texture2DArray*>(texture)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_3D: d3d11ShaderResourceView = static_cast<Texture3D*>(texture)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_CUBE: d3d11ShaderResourceView = static_cast<TextureCube*>(texture)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::TEXTURE_CUBE_ARRAY: d3d11ShaderResourceView = static_cast<TextureCubeArray*>(texture)->getD3D11ShaderResourceView(); break; case Rhi::ResourceType::ROOT_SIGNATURE: case Rhi::ResourceType::RESOURCE_GROUP: case Rhi::ResourceType::GRAPHICS_PROGRAM: case Rhi::ResourceType::VERTEX_ARRAY: case Rhi::ResourceType::RENDER_PASS: case Rhi::ResourceType::QUERY_POOL: case Rhi::ResourceType::SWAP_CHAIN: case Rhi::ResourceType::FRAMEBUFFER: case Rhi::ResourceType::VERTEX_BUFFER: case Rhi::ResourceType::INDEX_BUFFER: case Rhi::ResourceType::TEXTURE_BUFFER: case Rhi::ResourceType::STRUCTURED_BUFFER: case Rhi::ResourceType::INDIRECT_BUFFER: case Rhi::ResourceType::UNIFORM_BUFFER: case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE: case Rhi::ResourceType::COMPUTE_PIPELINE_STATE: case Rhi::ResourceType::SAMPLER_STATE: case Rhi::ResourceType::VERTEX_SHADER: case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER: case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER: case Rhi::ResourceType::GEOMETRY_SHADER: case Rhi::ResourceType::FRAGMENT_SHADER: case Rhi::ResourceType::TASK_SHADER: case Rhi::ResourceType::MESH_SHADER: case Rhi::ResourceType::COMPUTE_SHADER: default: RHI_ASSERT(mContext, false, "Direct3D 11: Invalid resource type") break; } RHI_ASSERT(mContext, nullptr != d3d11ShaderResourceView, "Direct3D 11: Invalid shader resource view") mD3D11DeviceContext->GenerateMips(d3d11ShaderResourceView); texture->releaseReference(); } mGenerateAsynchronousMipmapsForTextures.clear(); } } // Dispatch command buffer dispatchCommandBufferInternal(commandBuffer); // "ID3D11DeviceContext::OMSetRenderTargets()" must be called every frame since it might become invalid // -> Hence the reset of our redundant state change avoidance "Direct3D11Rhi::mRenderTarget" at this point in time if (nullptr != mRenderTarget) { mRenderTarget->releaseReference(); mRenderTarget = nullptr; } } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] void Direct3D11Rhi::initializeCapabilities() { // There are no Direct3D 11 device capabilities we could query on runtime, they depend on the chosen feature level // -> Have a look at "Devices -> Direct3D 11 on Downlevel Hardware -> Introduction" at MSDN http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx // for a table with a list of the minimum resources supported by Direct3D 11 at the different feature levels { // Get device name // Get DXGI adapter IDXGIDevice* dxgiDevice = nullptr; IDXGIAdapter* dxgiAdapter = nullptr; FAILED_DEBUG_BREAK(mD3D11Device->QueryInterface(IID_PPV_ARGS(&dxgiDevice))) FAILED_DEBUG_BREAK(dxgiDevice->GetAdapter(&dxgiAdapter)) // The adapter contains a description like "AMD Radeon R9 200 Series" DXGI_ADAPTER_DESC dxgiAdapterDesc = {}; FAILED_DEBUG_BREAK(dxgiAdapter->GetDesc(&dxgiAdapterDesc)) // Convert UTF-16 string to UTF-8 const size_t numberOfCharacters = _countof(mCapabilities.deviceName) - 1; ::WideCharToMultiByte(CP_UTF8, 0, dxgiAdapterDesc.Description, static_cast<int>(wcslen(dxgiAdapterDesc.Description)), mCapabilities.deviceName, static_cast<int>(numberOfCharacters), nullptr, nullptr); mCapabilities.deviceName[numberOfCharacters] = '\0'; // Release references dxgiAdapter->Release(); dxgiDevice->Release(); } // Preferred swap chain texture format mCapabilities.preferredSwapChainColorTextureFormat = Rhi::TextureFormat::Enum::R8G8B8A8; mCapabilities.preferredSwapChainDepthStencilTextureFormat = Rhi::TextureFormat::Enum::D32_FLOAT; // Evaluate the chosen feature level switch (mD3D11Device->GetFeatureLevel()) { case D3D_FEATURE_LEVEL_9_1: // Maximum number of viewports (always at least 1) mCapabilities.maximumNumberOfViewports = 1; // Direct3D 9 only supports a single viewport // Maximum number of simultaneous render targets (if <1 render to texture is not supported) mCapabilities.maximumNumberOfSimultaneousRenderTargets = 1; // Maximum texture dimension mCapabilities.maximumTextureDimension = 2048; // Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0) mCapabilities.maximumNumberOf1DTextureArraySlices = 0; // Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0) mCapabilities.maximumNumberOf2DTextureArraySlices = 0; // Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0) mCapabilities.maximumNumberOfCubeTextureArraySlices = 0; // Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0) mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 0; // Maximum indirect buffer size in bytes mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB // Maximum number of multisamples (always at least 1, usually 8) mCapabilities.maximumNumberOfMultisamples = 1; // Don't want to support the legacy DirectX 9 multisample support // Maximum anisotropy (always at least 1, usually 16) mCapabilities.maximumAnisotropy = 16; // Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex) mCapabilities.instancedArrays = false; // Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID) mCapabilities.drawInstanced = false; // Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch) mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 9.1 has no tessellation support // Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024) mCapabilities.maximumNumberOfGsOutputVertices = 0; // Direct3D 9.1 has no geometry shader support break; case D3D_FEATURE_LEVEL_9_2: // Maximum number of viewports (always at least 1) mCapabilities.maximumNumberOfViewports = 1; // Direct3D 9 only supports a single viewport // Maximum number of simultaneous render targets (if <1 render to texture is not supported) mCapabilities.maximumNumberOfSimultaneousRenderTargets = 1; // Maximum texture dimension mCapabilities.maximumTextureDimension = 2048; // Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0) mCapabilities.maximumNumberOf1DTextureArraySlices = 0; // Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0) mCapabilities.maximumNumberOf2DTextureArraySlices = 0; // Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0) mCapabilities.maximumNumberOfCubeTextureArraySlices = 0; // Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0) mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 0; // Maximum indirect buffer size in bytes mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB // Maximum number of multisamples (always at least 1, usually 8) mCapabilities.maximumNumberOfMultisamples = 1; // Don't want to support the legacy DirectX 9 multisample support // Maximum anisotropy (always at least 1, usually 16) mCapabilities.maximumAnisotropy = 16; // Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex) mCapabilities.instancedArrays = false; // Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID) mCapabilities.drawInstanced = false; // Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch) mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 9.2 has no tessellation support // Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024) mCapabilities.maximumNumberOfGsOutputVertices = 0; // Direct3D 9.2 has no geometry shader support break; case D3D_FEATURE_LEVEL_9_3: // Maximum number of viewports (always at least 1) mCapabilities.maximumNumberOfViewports = 1; // Direct3D 9 only supports a single viewport // Maximum number of simultaneous render targets (if <1 render to texture is not supported) mCapabilities.maximumNumberOfSimultaneousRenderTargets = 4; // Maximum texture dimension mCapabilities.maximumTextureDimension = 4096; // Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0) mCapabilities.maximumNumberOf1DTextureArraySlices = 0; // Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0) mCapabilities.maximumNumberOf2DTextureArraySlices = 0; // Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0) mCapabilities.maximumNumberOfCubeTextureArraySlices = 0; // Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0) mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 0; // Maximum indirect buffer size in bytes mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB // Maximum number of multisamples (always at least 1, usually 8) mCapabilities.maximumNumberOfMultisamples = 1; // Don't want to support the legacy DirectX 9 multisample support // Maximum anisotropy (always at least 1, usually 16) mCapabilities.maximumAnisotropy = 16; // Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex) mCapabilities.instancedArrays = true; // Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID) mCapabilities.drawInstanced = false; // Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch) mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 9.3 has no tessellation support // Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024) mCapabilities.maximumNumberOfGsOutputVertices = 0; // Direct3D 9.3 has no geometry shader support break; case D3D_FEATURE_LEVEL_10_0: // Maximum number of viewports (always at least 1) mCapabilities.maximumNumberOfViewports = D3D10_VIEWPORT_AND_SCISSORRECT_MAX_INDEX + 1; // Maximum number of simultaneous render targets (if <1 render to texture is not supported) mCapabilities.maximumNumberOfSimultaneousRenderTargets = D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT; // Maximum texture dimension mCapabilities.maximumTextureDimension = 8192; // Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0) mCapabilities.maximumNumberOf1DTextureArraySlices = 512; // Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0) mCapabilities.maximumNumberOf2DTextureArraySlices = 512; // Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0) mCapabilities.maximumNumberOfCubeTextureArraySlices = 0; // Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0) mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 128 * 1024 * 1024; // TODO(co) http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx does not mention the texture buffer? Currently the OpenGL 3 minimum is used: 128 MiB. // Maximum indirect buffer size in bytes mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB // Maximum number of multisamples (always at least 1, usually 8) mCapabilities.maximumNumberOfMultisamples = 8; // Maximum anisotropy (always at least 1, usually 16) mCapabilities.maximumAnisotropy = 16; // Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex) mCapabilities.instancedArrays = true; // Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID) mCapabilities.drawInstanced = true; // Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch) mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 10 has no tessellation support // Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024) mCapabilities.maximumNumberOfGsOutputVertices = 1024; break; case D3D_FEATURE_LEVEL_10_1: // Maximum number of viewports (always at least 1) mCapabilities.maximumNumberOfViewports = D3D10_VIEWPORT_AND_SCISSORRECT_MAX_INDEX + 1; // Maximum number of simultaneous render targets (if <1 render to texture is not supported) mCapabilities.maximumNumberOfSimultaneousRenderTargets = D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT; // Maximum texture dimension mCapabilities.maximumTextureDimension = 8192; // Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0) mCapabilities.maximumNumberOf1DTextureArraySlices = 512; // Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0) mCapabilities.maximumNumberOf2DTextureArraySlices = 512; // Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0) mCapabilities.maximumNumberOfCubeTextureArraySlices = 512; // Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0) mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 128 * 1024 * 1024; // TODO(co) http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx does not mention the texture buffer? Currently the OpenGL 3 minimum is used: 128 MiB. // Maximum indirect buffer size in bytes mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB // Maximum number of multisamples (always at least 1, usually 8) mCapabilities.maximumNumberOfMultisamples = 8; // Maximum anisotropy (always at least 1, usually 16) mCapabilities.maximumAnisotropy = 16; // Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex) mCapabilities.instancedArrays = true; // Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID) mCapabilities.drawInstanced = true; // Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch) mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 10.1 has no tessellation support // Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024) mCapabilities.maximumNumberOfGsOutputVertices = 1024; break; case D3D_FEATURE_LEVEL_11_0: case D3D_FEATURE_LEVEL_11_1: // Maximum number of viewports (always at least 1) mCapabilities.maximumNumberOfViewports = D3D11_VIEWPORT_AND_SCISSORRECT_MAX_INDEX + 1; // Maximum number of simultaneous render targets (if <1 render to texture is not supported) mCapabilities.maximumNumberOfSimultaneousRenderTargets = D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; // Maximum texture dimension mCapabilities.maximumTextureDimension = 16384; // Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0) mCapabilities.maximumNumberOf1DTextureArraySlices = 512; // Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0) mCapabilities.maximumNumberOf2DTextureArraySlices = 512; // Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0) mCapabilities.maximumNumberOfCubeTextureArraySlices = 512; // Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0) mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 128 * 1024 * 1024; // TODO(co) http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx does not mention the texture buffer? Currently the OpenGL 3 minimum is used: 128 MiB. // Maximum indirect buffer size in bytes mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB // Maximum number of multisamples (always at least 1, usually 8) mCapabilities.maximumNumberOfMultisamples = 8; // Maximum anisotropy (always at least 1, usually 16) mCapabilities.maximumAnisotropy = 16; // Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex) mCapabilities.instancedArrays = true; // Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID) mCapabilities.drawInstanced = true; // Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch) mCapabilities.maximumNumberOfPatchVertices = 32; // Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024) mCapabilities.maximumNumberOfGsOutputVertices = 1024; // TODO(co) http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx does not mention it, so I assume it's 1024 break; } // The rest is the same for all feature levels // Maximum uniform buffer (UBO) size in bytes (usually at least 4096 * 16 bytes, in case there's no support for uniform buffer it's 0) // -> See https://msdn.microsoft.com/en-us/library/windows/desktop/ff819065(v=vs.85).aspx - "Resource Limits (Direct3D 11)" - "Number of elements in a constant buffer D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT (4096)" // -> One element = float4 = 16 bytes mCapabilities.maximumUniformBufferSize = 4096 * 16; // Left-handed coordinate system with clip space depth value range 0..1 mCapabilities.upperLeftOrigin = mCapabilities.zeroToOneClipZ = true; // Individual uniforms ("constants" in Direct3D terminology) supported? If not, only uniform buffer objects are supported. mCapabilities.individualUniforms = false; // Base vertex supported for draw calls? mCapabilities.baseVertex = true; // Direct3D 11 has native multithreading mCapabilities.nativeMultithreading = true; // Direct3D 11 has shader bytecode support mCapabilities.shaderBytecode = true; // Is there support for vertex shaders (VS)? mCapabilities.vertexShader = true; // Is there support for fragment shaders (FS)? mCapabilities.fragmentShader = true; // Is there support for compute shaders (CS)? mCapabilities.computeShader = true; } void Direct3D11Rhi::setGraphicsProgram(Rhi::IGraphicsProgram* graphicsProgram) { // Begin debug event RHI_BEGIN_DEBUG_EVENT_FUNCTION(this) if (nullptr != graphicsProgram) { // Sanity check RHI_MATCH_CHECK(*this, *graphicsProgram) // Get shaders const GraphicsProgramHlsl* graphicsProgramHlsl = static_cast<GraphicsProgramHlsl*>(graphicsProgram); const VertexShaderHlsl* vertexShaderHlsl = graphicsProgramHlsl->getVertexShaderHlsl(); const TessellationControlShaderHlsl* tessellationControlShaderHlsl = graphicsProgramHlsl->getTessellationControlShaderHlsl(); const TessellationEvaluationShaderHlsl* tessellationEvaluationShaderHlsl = graphicsProgramHlsl->getTessellationEvaluationShaderHlsl(); const GeometryShaderHlsl* geometryShaderHlsl = graphicsProgramHlsl->getGeometryShaderHlsl(); const FragmentShaderHlsl* fragmentShaderHlsl = graphicsProgramHlsl->getFragmentShaderHlsl(); ID3D11VertexShader* d3d11VertexShader = (nullptr != vertexShaderHlsl) ? vertexShaderHlsl->getD3D11VertexShader() : nullptr; ID3D11HullShader* d3d11HullShader = (nullptr != tessellationControlShaderHlsl) ? tessellationControlShaderHlsl->getD3D11HullShader() : nullptr; ID3D11DomainShader* d3d11DomainShader = (nullptr != tessellationEvaluationShaderHlsl) ? tessellationEvaluationShaderHlsl->getD3D11DomainShader() : nullptr; ID3D11GeometryShader* d3d11GeometryShader = (nullptr != geometryShaderHlsl) ? geometryShaderHlsl->getD3D11GeometryShader() : nullptr; ID3D11PixelShader* d3d11PixelShader = (nullptr != fragmentShaderHlsl) ? fragmentShaderHlsl->getD3D11PixelShader() : nullptr; // Set shaders if (mD3d11VertexShader != d3d11VertexShader) { mD3d11VertexShader = d3d11VertexShader; mD3D11DeviceContext->VSSetShader(mD3d11VertexShader, nullptr, 0); } if (mD3d11HullShader != d3d11HullShader) { mD3d11HullShader = d3d11HullShader; mD3D11DeviceContext->HSSetShader(mD3d11HullShader, nullptr, 0); } if (mD3d11DomainShader != d3d11DomainShader) { mD3d11DomainShader = d3d11DomainShader; mD3D11DeviceContext->DSSetShader(mD3d11DomainShader, nullptr, 0); } if (mD3d11GeometryShader != d3d11GeometryShader) { mD3d11GeometryShader = d3d11GeometryShader; mD3D11DeviceContext->GSSetShader(mD3d11GeometryShader, nullptr, 0); } if (mD3d11PixelShader != d3d11PixelShader) { mD3d11PixelShader = d3d11PixelShader; mD3D11DeviceContext->PSSetShader(mD3d11PixelShader, nullptr, 0); } } else { if (nullptr != mD3d11VertexShader) { mD3D11DeviceContext->VSSetShader(nullptr, nullptr, 0); mD3d11VertexShader = nullptr; } if (nullptr != mD3d11HullShader) { mD3D11DeviceContext->HSSetShader(nullptr, nullptr, 0); mD3d11HullShader = nullptr; } if (nullptr != mD3d11DomainShader) { mD3D11DeviceContext->DSSetShader(nullptr, nullptr, 0); mD3d11DomainShader = nullptr; } if (nullptr != mD3d11GeometryShader) { mD3D11DeviceContext->GSSetShader(nullptr, nullptr, 0); mD3d11GeometryShader = nullptr; } if (nullptr != mD3d11PixelShader) { mD3D11DeviceContext->PSSetShader(nullptr, nullptr, 0); mD3d11PixelShader = nullptr; } } // End debug event RHI_END_DEBUG_EVENT(this) } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Direct3D11Rhi //[-------------------------------------------------------] //[ Global functions ] //[-------------------------------------------------------] // Export the instance creation function #ifdef RHI_DIRECT3D11_EXPORTS #define DIRECT3D11RHI_FUNCTION_EXPORT GENERIC_FUNCTION_EXPORT #else #define DIRECT3D11RHI_FUNCTION_EXPORT #endif DIRECT3D11RHI_FUNCTION_EXPORT Rhi::IRhi* createDirect3D11RhiInstance(const Rhi::Context& context) { return RHI_NEW(context, Direct3D11Rhi::Direct3D11Rhi)(context); } #undef DIRECT3D11RHI_FUNCTION_EXPORT
[ "cofenberg@gmail.com" ]
cofenberg@gmail.com
9510d13de9dabcc59ba5b23af7824a5ed6bcb749
e3c1509da264714272ff431b351c538909d0b7d5
/chapter 4/5.cpp
23a7422f65c2c00c9ec09a6216a955a629298963
[]
no_license
61jing/C---Primer-Plus-Exercises-Solutions
dfec0878685a72f9301e9a8fe0b1158062c99222
aca58ac30ed7c7aad1751a84e2f690dfb1d1221e
refs/heads/master
2020-07-12T23:40:12.943799
2013-07-02T14:16:04
2013-07-02T14:16:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
#include <iostream> #include <string> using namespace std; int main () { /* The CandyBar structure contains three members: The first member holds the brand name of a candy bar. The second member holds the weight (which may have a fractional part) of the candy bar, and the third member holds the number of calories (an integer value) in the candy bar. Write a program that declares such a structure and creates a CandyBar variable called snack, initializing its members to "Mocha Munch", 2.3, and 350, respectively. The initialization should be part of the declaration for snack. Finally, the program should display the contents of the snack variable. */ struct CandyBar { string name; float weight; int calories; }; CandyBar Mocha_Munch = { "Mocha Munch", 2.3, 350 }; cout << "CandyBar name = " << Mocha_Munch.name << endl << "CandyBar weight = " << Mocha_Munch.weight << endl << "CandyBar calories = " << Mocha_Munch.calories << endl; system ("pause"); }
[ "oleksii.savochkin@globallogic.com" ]
oleksii.savochkin@globallogic.com
69c536faa9a0d29eef68bbc7433d49196e2a1578
6e626b730274c1b222ddc2c7e9691fa00cc0267f
/myPhysics/myPhysics.cpp
a3f59b03b1ab3316442f692a0c5eb87904c7fc2d
[]
no_license
shalin1st/Physics2_Proj2_Bullet_Collision
a2b946ff8d33b934daf85c3d53624f4cbe0de62a
9d0c29e7f0a8a2be71c99d2dc07f635a4bc331b3
refs/heads/master
2021-04-03T05:03:10.726871
2020-06-11T04:50:54
2020-06-11T04:50:54
124,465,100
0
0
null
null
null
null
UTF-8
C++
false
false
6,603
cpp
#include"myPhysics.h" void myPhysics::ReadFileToToken(std::ifstream &file, std::string token) { bool bKeepReading = true; std::string garbage; do { file >> garbage; // Title_End?? if (garbage == token) { return; } } while (bKeepReading); return; } std::vector<myPhysics::object1> myPhysics::InitializePhysics(std::string file) { std::vector <object1> myvec; object1 myobj; std::ifstream plyFile(file.c_str()); if (!plyFile.is_open()) { // Didn't open file, so return } ReadFileToToken(plyFile, "models"); int count; plyFile >> count; for (int i = 1; i <= count; i++) { ReadFileToToken(plyFile, std::to_string(i)); ReadFileToToken(plyFile, "position"); plyFile >> myobj.pos.x; plyFile >> myobj.pos.y; plyFile >> myobj.pos.z; ReadFileToToken(plyFile, "orientation"); plyFile >> myobj.ori.x; plyFile >> myobj.ori.y; plyFile >> myobj.ori.z; ReadFileToToken(plyFile, "orientation2"); plyFile >> myobj.or2.x; plyFile >> myobj.or2.y; plyFile >> myobj.or2.z; ReadFileToToken(plyFile, "scale"); plyFile >> myobj.scale; ReadFileToToken(plyFile, "color"); plyFile >> myobj.color.a; plyFile >> myobj.color.r; plyFile >> myobj.color.g; plyFile >> myobj.color.b; ReadFileToToken(plyFile, "name"); plyFile >> myobj.name; ReadFileToToken(plyFile, "type"); plyFile >> myobj.typer; if (myobj.typer == "sphere") { myobj.type = eTypeOfObject::SPHERE; } else { myobj.type = eTypeOfObject::PLANE; } ReadFileToToken(plyFile, "physics"); plyFile >> myobj.phys; myvec.push_back(myobj); } return myvec; } void myPhysics::PhysicsStep(double deltaTime, force &wforce, force &sforce, force &leftforce, force &rightforce, force &upforce, std::vector<glm::vec3> &disp, std::vector<glm::vec3> &rot, std::vector<object1> &my, std::vector<int> &collision) { if (collision.size() != my.size()) { for (int i = 0; i < my.size(); i++) { collision.push_back(0); } } const glm::vec3 GRAVITY = glm::vec3(0.0f, -5.0f, 0.0f); for (int index = 0; index < my.size(); index++) { // Is this object to be updated? object1 pCurGo = my[index]; if (!pCurGo.phys) { continue; } glm::vec3 a; a = (GRAVITY); glm::vec3 deltaVelocity = ((a*(float)deltaTime / 4.0f) + ((a*(float)deltaTime / 2.0f)) + (3.0f*(a*(float)deltaTime / 2.0f)) + (a*(float)deltaTime)) / 4.0f; glm::vec3 deltaVelocity2 = ((float)deltaTime * a); switch (pCurGo.type) { case eTypeOfObject::SPHERE: const float SURFACEOFGROUND = -1.5f; const float LEFTSIDEWALL = 14.5f; const float RIGHTSIDEWALL = -13.5f; const float BACKWALL = -13.5f; const float FRONTWALL = 14.5f; // if (index == 1) { if (wforce.on == 1) { a = (wforce.direction * wforce.strength * glm::vec3(1, 0, 1)) * 15.0f; deltaVelocity = ((a*(float)deltaTime / 4.0f) + ((a*(float)deltaTime / 2.0f)) + (3.0f*(a*(float)deltaTime / 4.0f)) + (a*(float)deltaTime)) / 6.0f; pCurGo.vel += deltaVelocity; } else { if (abs(pCurGo.vel.x) > 0 || abs(pCurGo.vel.z) >0) pCurGo.vel -= pCurGo.vel * glm::vec3(1, 0, 1) / 20.0f; } if (sforce.on == 1) { a = (-wforce.direction * wforce.strength * glm::vec3(1, 0, 1)) * 15.0f; deltaVelocity = ((a*(float)deltaTime / 4.0f) + ((a*(float)deltaTime / 2.0f)) + (3.0f*(a*(float)deltaTime / 4.0f)) + (a*(float)deltaTime)) / 6.0f; pCurGo.vel += deltaVelocity; } else { if (abs(pCurGo.vel.x) > 0 || abs(pCurGo.vel.z) >0) pCurGo.vel -= pCurGo.vel * glm::vec3(1, 0, 1) / 20.0f; } if (leftforce.on == 1) { a = (leftforce.direction * leftforce.strength * glm::vec3(1, 0, 1)) * 15.0f; deltaVelocity = ((a*(float)deltaTime / 4.0f) + ((a*(float)deltaTime / 2.0f)) + (3.0f*(a*(float)deltaTime / 4.0f)) + (a*(float)deltaTime)) / 4.0f; pCurGo.vel += deltaVelocity; } else { if (abs(pCurGo.vel.x) > 0 || abs(pCurGo.vel.z) >0) pCurGo.vel -= pCurGo.vel * glm::vec3(1, 0, 1) / 20.0f; } if (rightforce.on == 1) { a = (rightforce.direction * rightforce.strength * glm::vec3(1, 0, 1)) * 15.0f; deltaVelocity = ((a*(float)deltaTime / 4.0f) + ((a*(float)deltaTime / 2.0f)) + (3.0f*(a*(float)deltaTime / 4.0f)) + (a*(float)deltaTime)) / 4.0f; pCurGo.vel += deltaVelocity; } else { if (abs(pCurGo.vel.x) > 0 || abs(pCurGo.vel.z) >0) pCurGo.vel -= pCurGo.vel * glm::vec3(1, 0, 1) / 20.0f; } if (upforce.on == 1) { deltaVelocity += upforce.direction * upforce.strength; pCurGo.vel += deltaVelocity; } else { if ((pCurGo.vel.y) > 0) pCurGo.vel.y -= pCurGo.vel.y / 2.0f; } } for (int j = 0; j < my.size(); j++) { if (my[j].type == eTypeOfObject::SPHERE && index != j) { if (glm::distance(my[index].pos, my[j].pos) <= my[index].scale + my[j].scale) { my[j].vel += (my[j].pos - my[index].pos)*(float)deltaTime / 2.0f + my[index].vel*(float)deltaTime; collision[index] = 1; collision[j] = 1; } else { if (j != 1) { if (abs(my[j].vel.x) > 0 || abs(my[j].vel.z) > 0) { my[j].vel -= my[j].vel * glm::vec3(1, 0, 1) * my[j].scale / 600.0f; collision[j] = 2; } } } } } if ((pCurGo.pos.y - pCurGo.scale / 2.0f) <= SURFACEOFGROUND && upforce.on == 0) { pCurGo.vel.y = 0; deltaVelocity.y = 0; } if ((pCurGo.pos.x - pCurGo.scale / 2.0f) <= RIGHTSIDEWALL && (float)deltaTime*pCurGo.vel.x<0) { pCurGo.vel.x = 0; deltaVelocity.x = 0; } if ((pCurGo.pos.x - pCurGo.scale / 2.0f) >= LEFTSIDEWALL && (float)deltaTime*pCurGo.vel.x>0) { pCurGo.vel.x = 0; deltaVelocity.x = 0; } if ((pCurGo.pos.z - pCurGo.scale / 2.0f) <= BACKWALL && (float)deltaTime*pCurGo.vel.z<0) { pCurGo.vel.z = 0; deltaVelocity.z = 0; } if ((pCurGo.pos.z - pCurGo.scale / 2.0f) >= FRONTWALL && (float)deltaTime*pCurGo.vel.z>0) { pCurGo.vel.z = 0; deltaVelocity.z = 0; } pCurGo.vel = pCurGo.vel + deltaVelocity; glm::vec3 deltaPosition = (float)deltaTime * pCurGo.vel; rot[index] = (glm::cross(glm::vec3(0, 1, 0), deltaPosition) / 2.0f); disp[index] = (deltaPosition); my[index].vel = pCurGo.vel; my[index].pos += deltaPosition; my[index].or2 += ((glm::cross(glm::vec3(0, 1, 0), deltaPosition) / 2.0f)); if (deltaPosition.x <= 0.001f && deltaPosition.z <= 0.001f) { collision[index] = 0; } break; }; } return; }
[ "s_momin58801@fanshaweonline.ca" ]
s_momin58801@fanshaweonline.ca
f2b6f16f3246388e7decd089ad2bd13f2ca850bc
0e7c1dc20191ac6a0ed00f219fc8ebb609654694
/DeathEngine/Export/IRenderer.h
8034f7d3823d9c6c58790fced9d73da141cea88f
[]
no_license
seblef/DeathChase
99a061773b6541e20ab949451beb575e86d0ea7e
bb24f9adce681f3833c4c6a415c6b3beecd098b1
refs/heads/master
2021-08-24T11:57:19.064199
2017-12-09T15:57:31
2017-12-09T15:57:31
113,684,828
0
0
null
null
null
null
UTF-8
C++
false
false
2,994
h
#ifndef _IRENDERER_H_ #define _IRENDERER_H_ #include <d3d9.h> #include "../Core/Vertex.h" #include "../Core/Handles.h" #include "../Core/RenderingOp.h" #include "../Exec/Materials/Shaders/ShadersDefs.h" enum TransformationType { TRANS_VIEWPROJ=0, TRANS_MODEL, TRANS_COUNT }; #define TRANSFORMATIONTYPE_DEFINED class IRenderingCommandBlock; class IRenderer { public: IRenderer() {} ~IRenderer() {} virtual bool Initialize(HWND hWnd, HINSTANCE hInst, int iHeight, int iWidth)=0; virtual void EndScene(bool bForceExecute=true)=0; virtual void BeginScene()=0; virtual IDirect3DVertexBuffer9 *CreateVertexBuffer(void *pVertices,uint32 dwCount,Core::VertexType _Type)=0; virtual IDirect3DIndexBuffer9 *CreateIndexBuffer(void *pIndices,uint32 dwCount,D3DFORMAT _Format)=0; virtual const Core::Vector2i& GetScreenSize() const=0; virtual const Core::Vector2i& GetViewportPos() const=0; virtual const Core::Vector2i& GetViewportSize() const=0; virtual void SetViewport(const Core::Vector2i& vViewportPos, const Core::Vector2i& vViewportSize)=0; virtual IDirect3DDevice9 *GetDevice()=0; virtual IDirect3DVertexDeclaration9 *GetVertexDeclaration(Core::VertexType _Type)=0; virtual void Shutdown()=0; // Gestion des vues virtual bool AddView(HWND hWnd, int iWidth, int iHeight)=0; virtual bool RemoveView(HWND hWnd)=0; virtual bool SetView(HWND hWnd)=0; virtual HWND GetCurrentView() const=0; virtual bool ResizeView(HWND hWnd, int iWidth, int iHeight)=0; virtual bool DrawImageInView(Core::HTexture hTex, HWND hWnd)=0; // Queue virtual bool StartCommandBlock()=0; virtual IRenderingCommandBlock *EndCommandBlock()=0; virtual void ReleaseCommandBlock(IRenderingCommandBlock *pBlock)=0; virtual bool AddCommandBlock(IRenderingCommandBlock *pBlock)=0; virtual bool AddOp(const Core::RenderingOp& op)=0; // Commandes virtual bool SetStateBlock(IDirect3DStateBlock9 *pStateBlock)=0; virtual bool SetRenderState(D3DRENDERSTATETYPE type, DWORD dwValue)=0; virtual bool SetTransformation(TransformationType type, const Core::Matrix4& mTrans, const Core::Matrix4 *pInverse=0, bool bInverse=true)=0; virtual bool SetVertexShaderConstant(uint32 dwReg, const float *fConstant, int iCount=1)=0; virtual bool SetVertexDeclaration(Core::VertexType _Type)=0; virtual bool ClearBuffer(uint32 dwBufferFlags, uint32 dwValue)=0; virtual bool SetVertexBuffer(IDirect3DVertexBuffer9 *pVBuffer,uint32 dwVertCount, uint32 dwVertSize)=0; virtual bool SetIndexBuffer(IDirect3DIndexBuffer9 *pIBuffer)=0; virtual bool RenderStaticBuffers(D3DPRIMITIVETYPE type, uint32 dwOffset, uint32 dwCount)=0; virtual bool RenderDynamicBuffers(D3DPRIMITIVETYPE type, int iVertCount, void *pVertBuffer, Core::VertexType VertType, int iIndCount, void *pInd, D3DFORMAT IndFormat)=0; virtual bool SetMaterial(D3DMATERIAL9 *pMat)=0; }; #endif
[ "sebast.lefort@gmail.com" ]
sebast.lefort@gmail.com
7b07b31cb63696106f65d80dc0798116602d3b80
138127182d375dcbd22ef16766ac5a5ea00727e3
/Single Number.cpp
31a7045d689a247b4b395ba3573ee32213b7d309
[]
no_license
sudhir5595/LeetCode_30Days
ebdc940b19b7b433d2d88a4565a356e4fd841666
f73f03ecd4b4773432a34f6a34fe9e8a8bef7b41
refs/heads/master
2022-09-06T23:48:28.868170
2020-05-14T05:08:23
2020-05-14T05:08:23
255,612,745
0
0
null
null
null
null
UTF-8
C++
false
false
272
cpp
class Solution { public: int singleNumber(vector<int>& nums) { // unordered_map <int, int> mp; int res = 0; for(int i = 0; i<nums.size(); i++){ // mp[nums[i]]++; res = nums[i]^res; } return res; } };
[ "noreply@github.com" ]
noreply@github.com
5fdcaae396b498a18a34d1bcc981eaa5561d9963
460f981dfe1a05f14d2a4cdc6cc71e9ad798b785
/3/amd64/envs/navigator/include/qt/Qt3DCore/5.9.7/Qt3DCore/private/qsysteminformationservice_p.h
01e976b77928e24774defe9e766d409da1f87f51
[ "LicenseRef-scancode-proprietary-license", "BSD-3-Clause", "Intel", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "GPL-1.0-or-later", "LGPL-2.0-or-later", "LicenseRef-scancode-mit-old-style", "dtoa", "LicenseRef-scancode-public-domain-disclaimer", "Zlib", "LicenseRef-scancod...
permissive
DFO-Ocean-Navigator/navigator-toolchain
d8c7351b477e66d674b50da54ec6ddc0f3a325ee
930d26886fdf8591b51da9d53e2aca743bf128ba
refs/heads/master
2022-11-05T18:57:30.938372
2021-04-22T02:02:45
2021-04-22T02:02:45
234,445,230
0
1
BSD-3-Clause
2022-10-25T06:46:23
2020-01-17T01:26:49
C++
UTF-8
C++
false
false
2,944
h
/**************************************************************************** ** ** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt3D module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QT3DCORE_QSYSTEMINFORMATIONSERVICE_P_H #define QT3DCORE_QSYSTEMINFORMATIONSERVICE_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of other Qt classes. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <Qt3DCore/qt3dcore_global.h> #include <QtCore/qstringlist.h> #include <Qt3DCore/private/qservicelocator_p.h> QT_BEGIN_NAMESPACE namespace Qt3DCore { class QSystemInformationServicePrivate; class QT3DCORESHARED_EXPORT QSystemInformationService : public QAbstractServiceProvider { Q_OBJECT public: virtual QStringList aspectNames() const = 0; virtual int threadPoolThreadCount() const = 0; protected: QSystemInformationService(const QString &description = QString()); QSystemInformationService(QSystemInformationServicePrivate &dd); }; } // namespace Qt3DCore QT_END_NAMESPACE #endif // QT3DCORE_QSYSTEMINFORMATIONSERVICE_P_H
[ "dwayne.hart@gmail.com" ]
dwayne.hart@gmail.com
8eb52cd5ff73e44055c12eef8874e24f6cab7d19
ab1c643f224197ca8c44ebd562953f0984df321e
/wmi/wbem/tools/locstudioparser/inc/mit/mitutil/cowblob.h
066ad58195eccfeb49bdf5c2e5b068218f69ed00
[]
no_license
KernelPanic-OpenSource/Win2K3_NT_admin
e162e0452fb2067f0675745f2273d5c569798709
d36e522f16bd866384bec440517f954a1a5c4a4d
refs/heads/master
2023-04-12T13:25:45.807158
2021-04-13T16:33:59
2021-04-13T16:33:59
357,613,696
0
1
null
null
null
null
UTF-8
C++
false
false
1,717
h
/*++ Copyright (C) 1996-1999 Microsoft Corporation Module Name: COWBLOB.H History: --*/ #ifndef COWBLOB_H #define COWBLOB_H class LTAPIENTRY CLocCOWBlob { public: CLocCOWBlob(); CLocCOWBlob(const CLocCOWBlob &); void AssertValid(void) const; LTASSERTONLY(UINT GetWriteCount(void) const); UINT GetBlobSize(void) const; void SetBlobSize(UINT); void ReallocBlob(UINT); void SetGrowSize(UINT); void *GetPointer(void); void ReleasePointer(void); void SetBuffer(const void *, size_t); operator const void *(void) const; const CLocCOWBlob &operator=(const CLocCOWBlob &); void Serialize(CArchive &ar); void Load(CArchive &ar); void Store(CArchive &ar) const; ~CLocCOWBlob(); // Comparison operators // NOTHROW int operator==(const CLocCOWBlob &) const; NOTHROW int operator!=(const CLocCOWBlob &) const; protected: private: typedef struct { DWORD RefCount; DWORD AllocSize; DWORD RequestedSize; } BlobHeader; NOTHROW void Attach(const CLocCOWBlob &); NOTHROW void Detach(void); NOTHROW void MakeWritable(void); NOTHROW BYTE * DataPointer(void) const; NOTHROW BlobHeader * GetBlobHeader(void); NOTHROW const BlobHeader * GetBlobHeader(void) const; NOTHROW DWORD & GetRefCount(void); NOTHROW DWORD GetAllocatedSize(void) const; NOTHROW DWORD GetRequestedSize(void) const; NOTHROW DWORD CalcNewSize(DWORD) const; BOOL Compare(const CLocCOWBlob &) const; BYTE *m_pBuffer; DWORD m_WriteCount; UINT m_uiGrowSize; static const UINT m_uiDefaultGrowSize; #ifdef _DEBUG static CCounter m_UsageCounter; void FillEndZone(void); void CheckEndZone(); #endif }; #if !defined(_DEBUG) || defined(IMPLEMENT) #include "cowblob.inl" #endif #endif // COWBLOB_H
[ "polarisdp@gmail.com" ]
polarisdp@gmail.com
4f6d732b67c825e6554a64bff6790bc8d29aaaa5
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_1/processor20/60/phi
cbd3443641ab560fe41e7db56a1d211646715ecc
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
3,154
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "60"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 -1 0 0 0 0]; internalField nonuniform List<scalar> 29 ( 0.000842371 0.000969357 0.000828546 0.00034353 9.24121e-05 0.00537385 0.00034353 0.000484443 0.000969357 0.000828546 0.000842371 0.000455368 0.000198697 2.60213e-05 -7.44103e-05 -0.000134103 -0.000162516 -0.000167562 -0.000154795 -0.000128528 -9.21819e-05 -4.86468e-05 0.000455368 0.000198697 2.60213e-05 -7.44103e-05 -0.000134103 -0.000162516 -0.000167562 ) ; boundaryField { inlet { type calculated; value nonuniform 0(); } outlet { type calculated; value nonuniform 0(); } cylinder { type calculated; value uniform 0; } top { type symmetryPlane; value uniform 0; } bottom { type symmetryPlane; value nonuniform 0(); } defaultFaces { type empty; value nonuniform 0(); } procBoundary20to18 { type processor; value nonuniform List<scalar> 12 ( -0.013684 -0.013684 -0.0249803 -0.0247308 -0.0245588 -0.024407 -0.0242578 -0.0241217 -0.0249803 -0.0247308 -0.0245588 -0.024407 ) ; } procBoundary20to19 { type processor; value nonuniform List<scalar> 29 ( -0.0169776 -0.0114865 -0.0126943 0.000560878 -0.00537385 0.000484443 -0.00795224 9.24121e-05 -0.00223881 -0.00223881 -0.00546873 0.000187292 -0.00795224 -0.00989695 0.000479331 -0.0114865 -0.0126943 0.000560878 -0.0169776 -0.0240009 -0.0238981 -0.0238151 -0.0237531 -0.023713 -0.023695 -0.0242578 -0.0241217 -0.0240009 -0.0238981 ) ; } procBoundary20to21 { type processor; value nonuniform List<scalar> 24 ( 0.0114702 0.0128352 0.0139516 -0.00114176 0.00516728 0.00781133 -0.000953057 -0.000136958 0.00214639 0.00214639 -0.000136958 0.00516728 0.00781133 0.00990206 -0.000953057 0.0114702 0.0128352 0.0139516 -0.00114176 0.0253673 0.0249875 0.0247315 0.0245075 -0.000154795 ) ; } procBoundary20to22 { type processor; value nonuniform List<scalar> 18 ( 0.017277 0.017277 0.0243174 0.0241501 0.0240059 0.0238853 0.0237888 0.0237168 0.0236694 0.0236464 0.0253673 0.0249875 0.0247315 0.0245075 0.0243174 0.0241501 0.0240059 0.0238853 ) ; } } // ************************************************************************* //
[ "chaseguy15" ]
chaseguy15
3101c87bb06bf08ce012bdd3ea556afb6479dc87
348517397b884c6f12a3fe74f870fde1a14b7b07
/1-9/problem_4.cpp
12df52d37974cd1aa139e5093ac67d9208369fc1
[]
no_license
xiaff/sword-offer-practice
899f7d9a15fdfaac0b5f0dd62faff525e9035f60
ce6bc52cb313c81aa68ca31d22d11f7036e22209
refs/heads/master
2021-01-10T01:19:50.562527
2015-10-26T15:40:09
2015-10-26T15:40:09
43,377,065
0
1
null
null
null
null
UTF-8
C++
false
false
925
cpp
/* 面试题4:替换空格 请实现一个函数,把字符串中的每个空格替换成“%20”。 例如输入“We are happy.”,则输出“We%20are%20happy.”。 */ class Soultion { public: void replaceBlank(char sentence[],int length){ if(sentence==NULL&&length<=0){ return; } int originnalLength=0; int numberOfBlanks=0; char c; for(int i=0;(c=sentence[i])!='\0';i++){ originnalLength++; if(c==' '){ numberOfBlanks++; } } int newLength=originnalLength+2*numberOfBlanks; if(newLength>length){ return; } int indexOfOriginal=originnalLength; int indexOfNew=newLength; while(indexOfOriginal>=0&&indexOfNew>indexOfOriginal){ if(sentence[indexOfOriginal]==' '){ sentence[indexOfNew--]='0'; sentence[indexOfNew--]='2'; sentence[indexOfNew--]='%'; }else{ sentence[indexOfNew--]=sentence[indexOfOriginal]; } indexOfOriginal--; } } };
[ "loochenwei@gmail.com" ]
loochenwei@gmail.com
453df1df836fa1c7e7fc20da7f1eaf81c7ba88e3
87a9b7ee6bc7678906c4383973e319ed0cdfcf75
/c,c++/geeksForGeeks/heap.cpp
1e98ec8450a2ce0812902c7731afaa70840c85d2
[]
no_license
poojagarg/Coding
9dceabab3adab492012c5844e0392f8b02d8421f
48c6cf47f3a246913765c7223e1d487a6a581734
refs/heads/master
2020-06-06T07:42:44.560270
2014-09-13T04:34:51
2014-09-13T04:34:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
999
cpp
#include <iostream> #include <algorithm> using namespace std; int minIndex(int i, int j, int A[]){ return A[i]<A[j]?i:j; } void percolateDown(int *h,int n, int i){ int k1=2*i+1; int k2=2*i+2; if(k1>n-1) return; int minI=k1; if(k1!=n-1){ minI=minIndex(k1, k2, h); } if(h[minI]<h[i]){ swap(h[minI],h[i]); percolateDown(h,n,minI); } } void heapify(int *h, int n){ int s=(n-2)/2; for(; s>=0; s--){ percolateDown(h,n,s); } } int deleteMin(int *h, int n){ int d=h[0]; h[0]=h[n-1]; percolateDown(h,n-1,0); return d; } void percolateUp(int *h, int n, int e){ h[n]=e; int p=(n-1)/2; while(p>=0&&h[p]>h[n]){ swap(h[n],h[p]); n=p; p=(n-1)/2; } } int top(int *h){ return h[0]; } int main(){ int n; cin>>n; int h[n]; for(int i=0; i<n/2; i++){ cin>>h[i]; } n=n/2; heapify(h,n); int t; do{ cin>>t; percolateUp(h,n,t ); n++; }while(t!=-1); while(n!=0){ cout<<deleteMin(h,n)<<endl; n--; } }
[ "poojagarg.04@gmail.com" ]
poojagarg.04@gmail.com
a5dbdf4dcb222752c00a5e10bef57e348faf7578
cb80a8562d90eb969272a7ff2cf52c1fa7aeb084
/inletTest7/0.046/isentropic(p)
36dcf3c06f182f27e14de6c2ba505b2d7a339002
[]
no_license
mahoep/inletCFD
eb516145fad17408f018f51e32aa0604871eaa95
0df91e3fbfa60d5db9d52739e212ca6d3f0a28b2
refs/heads/main
2023-08-30T22:07:41.314690
2021-10-14T19:23:51
2021-10-14T19:23:51
314,657,843
0
0
null
null
null
null
UTF-8
C++
false
false
78,108
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2006 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.046"; object isentropic(p); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -2 0 0 0 0]; internalField nonuniform List<scalar> 10108 ( 150033 150037 150032 150039 150033 150036 150037 150039 150040 150039 150038 150037 150036 150035 150035 150034 150034 150033 150033 150033 150032 150032 150032 150031 150031 150030 150030 150029 150029 150029 150028 150028 150027 150027 150026 150026 150026 150025 150025 150024 150024 150024 150023 150023 150022 150022 150022 150021 150021 150020 150020 150020 150019 150018 150017 150016 150014 150013 150014 150017 150019 150021 150023 150023 150021 150024 150025 150026 150036 150050 150044 149952 149859 150034 150062 150060 150016 149779 149699 149995 150052 150041 149971 149630 149565 149945 150028 150015 149921 149509 149457 149897 150002 149989 149875 149411 149370 149854 149976 149964 149833 149332 149297 149813 149952 149939 149794 149265 149236 149776 149928 149915 149758 149209 149184 149741 149904 149892 149724 149160 149138 149708 149882 149871 149693 149117 149098 149678 149861 149850 149664 149079 149062 149650 149841 149830 149637 149046 149031 149624 149822 149812 149612 149016 149003 149600 149803 149794 149589 148990 148978 149578 149786 149777 149567 148966 148956 149557 149770 149761 149546 148945 148936 149537 149754 149746 149527 148926 148918 149518 149740 149732 149509 148910 148902 149501 149725 149718 149493 148895 148889 149485 149712 149705 149477 148882 148877 149470 149699 149692 149463 148871 148867 149456 149687 149680 149449 148862 148858 149443 149675 149669 149436 148854 148851 149430 149664 149658 149424 148848 148845 149419 149654 149648 149413 148843 148841 149408 149644 149638 149403 148840 148839 149398 149634 149629 149394 148838 148838 149389 149625 149620 149385 148837 148838 149381 149616 149611 149377 148838 148839 149374 149608 149603 149370 148841 148842 149367 149600 149595 149363 148844 148847 149361 149592 149588 149358 148849 148853 149355 149585 149581 149353 148856 148860 149351 149578 149574 149348 148864 148868 149347 149572 149568 149345 148873 148879 149343 149566 149562 149342 148884 148890 149341 149560 149557 149340 148896 148903 149339 149555 149552 149338 148910 148917 149338 149550 149547 149338 148925 148933 149338 149545 149543 149338 148942 148951 149339 149542 149539 149340 148960 148969 149341 149538 149536 149342 148979 148990 149344 149535 149534 149345 149000 149011 149348 149533 149532 149350 149022 149034 149353 149532 149531 149356 149046 149058 149359 149532 149532 149363 149070 149083 149367 149533 149533 149371 149096 149109 149376 149535 149536 149382 149122 149135 149387 149539 149540 149393 149149 149162 149400 149544 149546 149406 149175 149189 149413 149550 149553 149420 149202 149215 149428 149558 149562 149436 149228 149241 149444 149567 149572 149452 149253 149265 149460 149578 149583 149468 149277 149289 149477 149588 149594 149484 149299 149310 149493 149600 149605 149500 149320 149330 149508 149612 149617 149516 149339 149348 149524 149624 149629 149531 149355 149363 149538 149635 149640 149544 149370 149377 149551 149646 149651 149557 149383 149389 149564 149656 149661 149569 149394 149399 149575 149666 149670 149579 149403 149408 149585 149675 149679 149589 149412 149416 149594 149683 149687 149598 149419 149422 149602 149691 149695 149606 149425 149428 149610 149699 149702 149613 149431 149433 149617 149705 149708 149620 149436 149439 149624 149712 149717 149628 149442 149447 149633 149722 149726 149638 149450 149452 149641 149729 149736 149648 149459 149464 149654 149741 149834 149893 149934 149962 149983 150009 150028 150048 150062 150077 150089 150101 150111 150120 150128 150135 150141 150145 150148 150146 150136 150126 150113 150074 149987 149897 149668 149659 149884 149973 149784 149753 149319 149452 149749 149907 149915 149765 149435 149442 149774 149925 149921 149769 149434 149441 149776 149927 149924 149771 149436 149443 149779 149930 149928 149778 149439 149446 149786 149935 149934 149784 149446 149454 149792 149941 149940 149791 149454 149462 149800 149948 149947 149799 149462 149470 149808 149954 149953 149808 149471 149479 149817 149961 149961 149816 149480 149488 149825 149968 149968 149825 149489 149497 149834 149975 149975 149835 149499 149507 149844 149983 149983 149845 149509 149518 149854 149991 149992 149855 149520 149529 149865 150000 150001 149866 149531 149540 149876 150009 150010 149878 149543 149553 149888 150019 150021 149890 149556 149566 149901 150029 150032 149904 149570 149581 149916 150041 150044 149920 149586 149598 149932 150053 150057 149937 149604 149618 149950 150067 150071 149956 149626 149641 149971 150082 150086 149977 149653 149670 149993 150096 150101 150000 149682 149707 150021 150115 150129 150038 149732 149764 150064 150148 150167 150086 149800 149830 150106 150183 150196 150123 149858 149890 150142 150212 150225 150160 149921 149949 150178 150238 150249 150192 149977 150004 150208 150262 150274 150223 150034 150065 150240 150286 150297 150254 150095 150132 150274 150314 150316 150293 150166 150136 150132 150339 150331 150294 150137 150172 150314 150349 150365 150336 150207 150236 150355 150380 150397 150376 150272 150311 150401 150415 150414 150404 150351 150249 150470 150394 150451 150437 150375 150397 150460 150469 150483 150488 150447 150484 150501 150470 150562 150462 150564 150573 150572 150536 150523 150592 150627 150763 150666 150566 150516 150614 150707 150907 150723 150611 150895 150740 151453 149877 150240 150260 149554 149369 148757 148036 148677 149004 149001 148779 148215 148128 148645 148885 148646 148427 147933 148253 148702 148891 148842 148636 148188 148148 148336 148729 148915 148777 148343 148301 148682 148881 148694 148673 148092 148445 148807 148975 148932 148765 148389 148326 148568 148831 149018 148894 148532 148488 148828 148987 148859 148716 148364 148623 148948 149073 149038 148893 148569 148468 148768 148929 149118 149003 148687 148632 148945 149085 148985 148834 148540 148750 149056 149165 149136 149002 148698 148600 148888 149034 149208 149101 148798 148752 149050 149181 149077 148933 148647 148844 149144 149248 149220 149091 148791 148698 148977 149122 149287 149188 148885 148841 149112 149254 149057 149261 148548 148955 149155 149344 149216 149107 148790 148989 149282 149378 149354 149237 148952 148832 149095 149245 149396 149298 148990 148980 149244 149376 149174 149373 148659 149047 149262 149451 149322 149209 148882 149107 149395 149483 149460 149343 149055 148915 149191 149334 149494 149392 149071 148994 149290 149416 149556 149466 149168 149111 149405 149526 149395 149257 148961 149158 149467 149560 149483 149359 149062 149223 149522 149610 149577 149458 149159 149023 149315 149453 149619 149531 149227 149111 149412 149536 149659 149571 149263 149194 149503 149624 149504 149365 149063 149253 149572 149658 149574 149447 149130 149294 149607 149693 149657 149541 149202 149232 149201 149603 149638 149729 149185 149164 149430 149617 149717 149641 149287 149169 149486 149624 149750 149662 149322 149292 149590 149720 149505 149713 148935 149389 149468 149806 149606 149545 149106 149304 149653 149759 149666 149540 149182 149363 149705 149788 149754 149623 149307 148910 149738 149521 149852 149439 149422 149084 149581 149618 149798 149685 149351 149182 149564 149686 149809 149711 149353 149209 149576 149706 149819 149729 149367 149299 149632 149775 149546 149805 148911 149483 149422 149905 149642 149639 149082 149323 149684 149814 149685 149564 149147 149316 149718 149819 149727 149587 149196 149373 149754 149841 149799 149660 149294 148913 149731 149568 149888 149464 149413 149053 149598 149648 149826 149702 149311 149142 149572 149710 149837 149731 149325 149150 149570 149713 149835 149734 149324 149177 149586 149732 149848 149753 149345 149264 149657 149804 149577 149686 148910 149376 149493 149881 149646 149588 149027 149262 149682 149820 149677 149541 149057 149243 149696 149813 149690 149539 149069 149270 149718 149823 149708 149552 149087 149291 149732 149828 149788 149637 149170 149040 149317 149635 149724 149747 149084 148994 149430 149657 149778 149695 149148 148995 149461 149659 149783 149690 149160 148973 149455 149647 149778 149677 149159 148994 149486 149666 149791 149691 149194 149082 149562 149736 149461 149575 148648 149219 149341 149821 149526 149476 148766 149066 149565 149741 149567 149408 148812 149062 149589 149727 149565 149391 148803 149047 149585 149718 149576 149393 148816 149070 149602 149717 149671 149491 148909 148825 149022 149520 149565 149714 148789 148716 149195 149514 149637 149549 148863 148673 149247 149493 149647 149543 148886 148673 149255 149495 149646 149539 148903 148685 149274 149502 149647 149534 148933 148768 149384 149590 149378 148927 148566 148610 149563 149470 149402 149063 148506 148701 149465 149545 149403 149124 148497 148735 149446 149550 149365 149102 148457 148683 149397 149528 149362 149110 148448 148722 149399 149532 149502 149273 148588 148248 148900 149209 149420 149334 148482 148297 148969 149286 149437 149298 148504 148170 148930 149209 149408 149245 148463 148211 148978 149246 149433 149283 148532 148360 149133 149385 149055 148758 147962 148362 149024 149312 149060 148819 147896 148277 149076 149296 149061 148800 147909 148301 149099 149300 149108 148837 147964 148350 149143 149305 149280 149031 148190 147702 148486 148878 149108 148951 147955 147673 148539 148905 149147 148989 148012 147737 148620 148963 149181 149025 148119 147943 148844 149144 148726 148362 147439 147740 148751 148970 148685 148320 147289 147737 148755 148970 148795 148444 147429 147888 148851 149031 148982 148660 147657 147196 148171 148568 148805 148565 147477 146990 148106 148506 148799 148558 147473 147246 148411 148761 148463 147638 146972 147198 148649 148637 148535 147983 147033 147219 148444 148640 148517 148106 146873 146234 147608 148003 148476 148067 146985 146455 147856 148232 148539 148294 147185 146883 148186 148550 147841 147025 146011 146396 147904 148142 147908 147377 146033 146659 148045 148267 148295 147800 146475 145815 147398 147730 147962 147614 146094 145407 146966 147522 147937 147595 146127 145889 147454 147929 147539 146818 145430 146428 147660 147825 147707 147182 145617 144601 146258 146924 147429 147044 145482 145148 146994 147459 147227 145967 144896 145585 147198 147325 147147 146492 144584 143658 145559 146342 146880 146572 144682 144673 146368 147080 146196 146249 143299 143862 145991 146662 146453 145719 143376 142721 144949 145860 146363 146180 144683 143136 145554 146282 145736 144893 142310 141598 144158 145146 145667 145494 143713 141921 144804 145567 145158 144349 141186 141331 144388 145183 143668 142348 138483 140422 143499 144342 144357 143432 139983 138397 142685 143989 143584 142356 137508 136051 141556 143056 142249 140565 134317 133176 139636 141509 141827 139778 133133 133004 139685 142004 141973 139432 132697 132390 139056 141807 141719 138801 132165 131981 138482 141546 141445 138260 131847 131724 137962 141235 141114 137765 131640 131559 137499 140896 140776 137337 131521 131477 137109 140556 140444 136987 131473 131458 136797 140236 140136 136708 131477 131481 136549 139936 139848 136490 131520 131539 136359 139664 139592 136324 131591 131622 136216 139420 139360 136200 131685 131725 136112 139206 139161 136109 131802 131848 136038 139019 138988 136047 131936 131985 135990 138864 138851 136015 132080 132131 135969 138738 138742 136002 132229 132279 135966 138644 138663 136011 132379 132428 135983 138576 138608 136033 132526 132573 136014 138533 138576 136071 132669 132714 136058 138509 138562 136118 132807 132850 136110 138504 138564 136176 132940 132981 136172 138513 138579 136239 133068 133106 136239 138535 138607 136311 133190 133226 136313 138566 138641 136385 133307 133340 136389 138606 138685 136464 133419 133450 136470 138653 138733 136543 133526 133555 136551 138704 138789 136627 133628 133656 136636 138762 138843 136709 133726 133751 136718 138820 138902 136793 133820 133845 136804 138879 138960 136875 133910 133933 136886 138940 139021 136958 133996 134018 136969 139001 139080 137038 134079 134099 137049 139062 139141 137119 134158 134177 137129 139123 139199 137196 134234 134251 137205 139183 139258 137272 134306 134323 137281 139241 139315 137344 134376 134390 137351 139298 139371 137414 134441 134454 137421 139353 139424 137481 134503 134515 137485 139407 139476 137545 134562 134573 137549 139459 139526 137605 134617 134626 137608 139509 139574 137664 134669 134677 137665 139556 139620 137718 134717 134724 137717 139602 139664 137770 134763 134769 137769 139645 139706 137819 134805 134810 137816 139688 139747 137866 134845 134848 137862 139727 139785 137909 134882 134884 137904 139766 139823 137951 134917 134918 137946 139802 139857 137990 134949 134949 137984 139837 139891 138028 134979 134978 138021 139870 139923 138062 135007 135005 138054 139902 139954 138097 135033 135031 138088 139931 139982 138127 135057 135054 138117 139960 140010 138158 135080 135076 138147 139987 140036 138185 135101 135097 138174 140013 140061 138212 135121 135116 138200 140037 140084 138237 135139 135134 138224 140060 140107 138261 135157 135151 138248 140082 140128 138282 135173 135166 138268 140103 140148 138304 135188 135181 138290 140122 140167 138323 135202 135194 138308 140141 140185 138342 135215 135207 138327 140158 140201 138359 135227 135219 138343 140175 140218 138376 135238 135230 138360 140191 140233 138391 135249 135240 138374 140206 140248 138406 135259 135249 138389 140220 140261 138419 135268 135258 138401 140233 140274 138433 135276 135266 138415 140245 140286 138444 135284 135274 138426 140258 140298 138456 135291 135281 138437 140268 140308 138466 135298 135287 138447 140280 140318 138477 135304 135293 138457 140289 140328 138486 135310 135299 138466 140299 140337 138495 135315 135304 138475 140307 140345 138503 135320 135308 138482 140316 140353 138511 135324 135313 138490 140323 140360 138517 135328 135317 138496 140331 140368 138525 135332 135320 138504 140337 140374 138530 135335 135323 138509 140344 140380 138537 135338 135326 138515 140349 140386 138541 135341 135329 138520 140355 140391 138547 135344 135331 138525 140360 140396 138551 135346 135333 138529 140365 140401 138556 135348 135335 138534 140369 140405 138559 135349 135336 138537 140374 140409 138564 135351 135338 138541 140377 140413 138566 135352 135339 138543 140382 140417 138570 135353 135340 138547 140384 140419 138572 135354 135341 138549 140388 140423 138576 135355 135341 138553 140391 140425 138578 135355 135342 138554 140394 140429 138581 135355 135342 138557 140396 140431 138582 135355 135341 138558 140399 140433 138584 135355 135341 138561 140400 140434 138585 135354 135340 138561 140403 140437 138587 135353 135339 138563 140404 140438 138588 135352 135338 138564 140406 140440 138588 135354 135339 138564 140408 140445 138590 135352 135337 138568 140414 140456 138599 135356 135341 138580 140428 140481 138616 135364 135351 138604 140458 140517 138641 135374 135388 138665 140553 140778 138812 135508 135714 139067 141107 141346 139299 135911 143606 145043 145434 145645 146484 146920 147137 147355 147912 148282 148666 148955 149176 149350 149481 149580 149654 149709 149751 149783 149807 149826 149841 149852 149861 149868 149872 149875 149876 149878 149878 149878 149890 149895 149899 149905 149911 149919 149929 149940 149953 149968 149985 150004 150024 150044 150061 150073 150076 150073 150067 150061 150055 150050 150045 150041 150037 150032 150027 150022 150018 150013 150009 150004 150001 149997 149994 149992 149990 149988 149987 149987 149988 149989 149991 149993 149997 150000 150004 150008 150012 150017 150021 150024 150028 150030 150032 150034 150034 150034 150033 150032 150030 150027 150024 150021 150017 150013 150008 150004 150000 149995 149991 149987 149983 149979 149975 149971 149968 149965 149962 149959 149957 149954 149952 149950 149949 149947 149946 149945 149944 149943 149943 149943 149942 149942 149943 149943 149943 149944 149944 149945 149946 149947 149948 149949 149951 149952 149953 149955 149956 149958 149960 149961 149963 149965 149967 149969 149971 149973 149975 149977 149979 149981 149984 149986 149988 149991 149993 149996 149998 150001 150004 150009 150019 150029 150034 150036 150034 150036 150034 150044 150058 150070 150071 150069 150066 150062 150058 150055 150053 150050 150048 150046 150045 150043 150042 150040 150039 150038 150037 150036 150035 150034 150033 150032 150031 150030 150029 150029 150028 150027 150026 150025 150025 150024 150023 150022 150021 150020 150019 150018 150017 150016 150015 150013 150012 150010 150008 150006 150003 150000 149997 149997 150002 150008 150013 150018 150026 150045 150060 150065 150063 150057 150051 150045 150039 150033 150027 150021 150016 150010 150004 149998 149992 149986 149981 149975 149970 149964 149959 149954 149949 149944 149939 149934 149930 149925 149920 149916 149911 149907 149903 149898 149894 149890 149886 149882 149878 149874 149871 149867 149863 149859 149856 149852 149849 149845 149842 149838 149835 149832 149829 149825 149822 149819 149816 149813 149810 149807 149804 149801 149798 149795 149792 149789 149786 149783 149780 149777 149775 149772 149769 149766 149763 149760 149758 149755 149752 149750 149747 149745 149742 149740 149737 149735 149733 149731 149729 149728 149726 149725 149724 149723 149723 149722 149722 149723 149723 149724 149726 149727 149729 149730 149733 149735 149738 149740 149744 149746 149750 149752 149756 149758 149762 149765 149768 149771 149775 149777 149781 149783 149787 149789 149792 149795 149798 149800 149803 149805 149809 149812 149816 149820 149823 149827 149891 149933 149934 149889 149888 149934 149932 149885 149879 149924 149961 149960 149961 149961 149980 149976 149972 150013 150012 150010 150026 150025 150025 150019 150017 149958 149928 149879 149875 149921 149925 149875 149872 149918 149956 149955 149923 149872 149868 149916 149921 149869 149865 149914 149953 149952 149919 149865 149861 149912 149918 149862 149858 149910 149951 149950 149916 149858 149855 149909 149914 149855 149851 149907 149950 149950 149913 149852 149848 149906 149912 149849 149845 149905 149951 149951 149912 149846 149842 149904 149911 149843 149839 149903 149953 149955 149911 149840 149836 149903 149912 149838 149835 149904 149957 149960 149913 149836 149833 149905 149914 149835 149833 149907 149963 149966 149917 149835 149834 149910 149920 149836 149836 149913 149969 149973 149924 149838 149839 149916 149928 149841 149842 149920 149977 149981 149932 149844 149846 149924 149936 149848 149850 149928 149984 149988 149940 149853 149855 149932 149945 149857 149859 149936 149991 149994 149948 149862 149864 149940 149952 149867 149869 149943 149997 149999 149955 149872 149874 149947 149958 149876 149878 149950 150001 150003 149961 149881 149883 149953 149964 149886 149887 149956 150005 150007 149966 149890 149892 149958 149969 149895 149896 149961 150008 150010 149971 149899 149900 149964 149973 149903 149904 149966 150011 150012 149976 149908 149908 149968 149978 149912 149912 149971 150014 150015 149980 149916 149917 149973 149982 149920 149921 149975 150016 150017 149984 149924 149925 149978 149986 149928 149929 149980 150018 150019 149988 149932 149933 149982 149990 149937 149937 149985 150020 150022 149992 149941 149941 149987 149994 149945 149946 149989 150023 150024 149996 149949 149950 149992 149998 149954 149955 149994 150025 150026 150001 149958 149959 149997 150003 149963 149964 149999 150027 150028 150005 149968 149969 150002 150008 149973 149974 150005 150029 150030 150010 149978 149979 150008 150013 149983 149984 150011 150032 150033 150016 149988 149990 150014 150019 149993 149995 150017 150034 150036 150022 149999 150001 150021 150025 150005 150007 150024 150037 150039 150028 150011 150014 150028 150032 150017 150020 150032 150041 150042 150035 150024 150027 150036 150039 150030 150034 150041 150044 150047 150044 150037 150041 150046 150048 150044 150048 150050 150049 150050 150053 150052 150055 150055 150058 150059 150062 150060 150049 150033 150040 150044 150045 150045 150045 150046 150046 150046 150046 150047 150047 150048 150048 150049 150049 150050 150051 150051 150052 150053 150054 150054 150055 150055 150056 150056 150057 150057 150057 150057 150057 150057 150056 150055 150054 150053 150051 150049 150047 150045 150042 150039 150036 150032 150029 150025 150021 150018 150015 150013 150012 150011 150011 150011 150012 150012 150013 150014 150015 150015 150016 150017 150057 150057 150057 150051 150050 150048 150062 150061 150061 150081 150080 150078 150089 150089 150089 150086 150087 150112 150110 150105 150104 150102 150111 150111 150112 150125 150124 150122 150129 150130 150130 150129 150132 150134 150113 150088 150089 150057 150058 150058 150091 150090 150117 150115 150137 150139 150142 150118 150120 150091 150057 150057 150092 150092 150057 150057 150093 150126 150124 150122 150147 150144 150165 150161 150158 150155 150151 150148 150145 150141 150139 150137 150142 150144 150144 150152 150150 150148 150150 150152 150153 150156 150161 150155 150152 150151 150149 150147 150145 150127 150126 150117 150071 149996 150033 150099 150099 150046 150054 150108 150129 150130 150110 150104 150051 150056 150053 150105 150112 150132 150134 150138 150141 150157 150160 150165 150169 150173 150178 150175 150173 150170 150167 150165 150162 150148 150144 150126 150119 150122 150115 150119 150111 150115 150108 150057 150059 150062 150061 150067 150065 150071 150070 150076 150074 150122 150130 150127 150080 150081 150086 150134 150152 150155 150138 150131 150085 150091 150090 150135 150142 150159 150163 150167 150171 150178 150180 150182 150187 150169 150175 150151 150156 150162 150128 150093 150057 150056 150094 150095 150055 150056 150092 150135 150136 150131 150169 150178 150186 150248 150226 150208 150194 150183 150204 150193 150192 150190 150186 150184 150179 150175 150160 150154 150155 150149 150151 150144 150146 150139 150096 150096 150102 150102 150108 150108 150114 150115 150121 150122 150159 150165 150164 150129 150128 150136 150170 150184 150189 150176 150170 150137 150143 150145 150176 150181 150193 150199 150197 150200 150214 150219 150206 150192 150187 150187 150181 150153 150151 150160 150162 150168 150170 150194 150201 150209 150190 150181 150205 150218 150235 150222 150220 150239 150262 150284 150304 150294 150279 150270 150251 150242 150253 150270 150284 150278 150273 150261 150254 150240 150233 150219 150232 150243 150255 150265 150276 150284 150290 150296 150298 150311 150325 150330 150306 150310 150281 150237 150180 150131 150093 150057 150058 150093 150092 150060 150063 150090 150108 150122 150131 150172 150150 150123 150110 150100 150087 150066 150067 150086 150087 150069 150070 150088 150100 150098 150098 150107 150106 150108 150109 150102 150091 150073 150075 150093 150095 150077 150079 150096 150105 150104 150103 150110 150110 150111 150110 150106 150097 150081 150082 150098 150098 150084 150085 150098 150105 150105 150106 150110 150109 150107 150107 150109 150110 150112 150113 150113 150113 150112 150111 150111 150111 150117 150137 150180 150213 150245 150224 150148 150113 150250 150218 150266 150283 150337 150337 150354 150349 150343 150337 150330 150323 150312 150306 150303 150294 150313 150322 150333 150339 150353 150361 150365 150352 150331 150376 150369 150374 150356 150358 150347 150380 150381 150400 150387 150412 150414 150384 150351 150362 150365 150417 150340 150398 150427 150449 150432 150463 150435 150424 150460 150434 150431 150372 150268 150397 150398 150432 150421 150384 150324 150317 150218 150145 150066 150165 150215 150297 150338 150317 150340 150454 150475 150482 150577 150383 150376 150281 150214 150152 150304 150467 150503 150605 150433 150447 150406 149986 150171 150354 150166 150156 150124 149866 149385 149553 149227 149006 149262 149127 148998 149200 149125 149033 149191 149144 149069 149215 149180 149112 149246 149219 149158 149281 149259 149202 149320 149302 149246 149358 149341 149285 149397 149380 149325 149430 149411 149354 149457 149412 149508 149495 149436 149541 149526 149466 149560 149515 149619 149603 149535 149631 149594 149676 149659 149593 149682 149650 149736 149716 149652 149736 149702 149772 149753 149691 149769 149734 149812 149792 149725 149806 149761 149834 149789 149852 149839 149778 149850 149797 149863 149825 149891 149876 149800 149876 149826 149894 149851 149901 149859 149913 149897 149828 149897 149847 149917 149861 149919 149882 149940 149924 149841 149915 149860 149927 149882 149928 149877 149932 149893 149937 149923 149840 149914 149858 149916 149857 149922 149868 149919 149874 149929 149911 149816 149894 149835 149901 149841 149893 149829 149889 149843 149888 149868 149764 149850 149780 149851 149780 149850 149776 149836 149775 149846 149824 149707 149802 149713 149803 149718 149786 149713 149782 149719 149776 149744 149607 149720 149625 149720 149637 149718 149612 149694 149608 149694 149675 149523 149631 149548 149630 149493 149600 149520 149598 149571 149393 149525 149392 149521 149395 149496 149409 149501 149473 149248 149406 149258 149403 149305 149395 149362 149127 149300 149088 149275 149170 149290 149250 149000 149176 148945 149143 149102 148846 149068 148902 149084 148920 148604 148870 148744 148908 148845 148404 148718 148468 148757 148725 148379 148611 148205 148511 148451 148143 148472 148239 147736 148156 148103 147752 148165 147813 147256 147774 147738 147297 147813 147384 146909 147508 147173 146748 146252 147081 146654 146264 146068 145272 146147 145604 145170 144944 144528 144072 143511 143712 143923 144015 143991 144040 144001 144045 143978 144011 143929 143962 143871 143913 143815 143859 143753 143802 143689 143740 143622 143677 143556 143614 143491 143551 143425 143487 143360 143422 143295 143358 143231 143294 143171 143233 143113 143174 143057 143119 143006 143067 142956 143019 142912 142975 142870 142935 142834 142898 142800 142867 142772 142837 142744 142813 142724 142791 142703 142773 142689 142757 142674 142745 142666 142734 142656 142727 142652 142722 142647 142719 142647 142717 142646 142718 142650 142719 142652 142724 142658 142728 142663 142734 142671 142740 142677 142748 142686 142755 142694 142764 142704 142772 142712 142781 142723 142790 142731 142799 142742 142808 142750 142817 142761 142826 142769 142835 142779 142843 142787 142852 142797 142860 142805 142868 142814 142876 142821 142884 142830 142891 142837 142898 142845 142905 142851 142912 142859 142918 142864 142924 142871 142930 142877 142936 142883 142941 142888 142946 142894 142951 142898 142956 142903 142960 142907 142965 142912 142968 142916 142972 142920 142976 142923 142979 142927 142982 142929 142985 142933 142988 142935 142991 142938 142993 142940 142995 142943 142997 142945 142999 142947 143001 142949 143003 142951 143004 142952 143006 142954 143007 142955 143009 142957 143010 142957 143012 142960 143012 142960 143015 142964 143020 142969 143031 142986 143056 143014 143092 143055 143235 143436 144980 144889 145407 144653 144706 145178 144516 144607 144956 144467 144558 144894 144430 144525 144804 144429 144526 144829 144418 144516 144790 144423 144521 144816 144417 144516 144790 144423 144522 144816 144419 144518 144792 144425 144524 144819 144421 144520 144795 144427 144526 144822 144422 144522 144798 144428 144528 144825 144424 144524 144802 144431 144531 144829 144427 144527 144806 144433 144533 144833 144429 144530 144810 144435 144536 144837 144431 144533 144814 144438 144539 144842 144434 144536 144818 144440 144543 144846 144436 144539 144823 144443 144546 144852 144439 144542 144828 144446 144550 144857 144442 144546 144834 144449 144554 144863 144446 144551 144840 144453 144559 144870 144450 144555 144846 144457 144564 144877 144454 144561 144854 144462 144570 144885 144459 144567 144862 144467 144576 144894 144465 144574 144871 144474 144584 144904 144472 144582 144881 144481 144593 144915 144479 144591 144893 144489 144603 144927 144488 144602 144905 144499 144614 144940 144499 144614 144919 144510 144627 144955 144511 144627 144935 144523 144641 144972 144524 144643 144952 144538 144658 144990 144540 144660 144970 144554 144676 145010 144558 144680 144991 144573 144697 145032 144577 144702 145013 144595 144720 145056 144600 144726 145037 144618 144746 145081 144625 144753 145062 144645 144774 145107 144653 144782 145089 144674 144805 145134 144683 144814 145117 144707 144838 145162 144716 144848 145145 144742 144874 145191 144751 144885 145173 144778 144911 145219 144788 144922 145202 144816 144949 145248 144827 144961 145231 144855 144988 145275 144868 145001 145258 144895 145027 145300 144909 145041 145284 144935 145066 145324 144949 145081 145308 144975 145104 145346 144989 145119 145330 145012 145140 145365 145027 145154 145348 145047 145172 145380 145064 145185 145364 145081 145199 145393 145096 145210 145376 145108 145219 145399 145120 145227 145383 145125 145226 145404 145127 145222 145398 145113 145198 145413 145097 145177 145396 145049 145122 145411 144998 145070 145419 144903 144975 145451 144763 144811 145366 144543 144498 145028 144274 144138 145364 144067 144796 146274 144980 145449 146600 145884 146340 147047 146778 147199 146665 146862 147363 147497 148014 148327 147590 147077 147874 146647 145847 147295 145590 145649 146582 145844 145851 146699 146049 145996 146882 146229 146154 146953 146294 146235 146950 146391 146331 146937 146470 146405 146930 146529 146461 146928 146573 146502 146928 146604 146530 146928 146626 146551 146928 146641 146564 146928 146649 146572 146927 146655 146576 146926 146657 146577 146923 146656 146576 146920 146653 146574 146916 146648 146569 146911 146641 146563 146906 146634 146556 146899 146625 146548 146892 146616 146539 146885 146606 146530 146877 146596 146520 146868 146586 146510 146860 146575 146500 146850 146565 146489 146841 146554 146479 146831 146543 146468 146822 146532 146457 146812 146522 146447 146802 146512 146437 146792 146502 146427 146782 146492 146417 146772 146482 146407 146762 146472 146398 146752 146462 146388 146742 146453 146379 146732 146443 146370 146722 146434 146361 146713 146425 146352 146704 146416 146344 146695 146408 146336 146687 146400 146328 146682 146393 146322 146678 146389 146319 146687 146390 146326 146731 146411 146371 146853 146494 146465 147106 146684 146781 147097 147139 148059 148561 148903 148876 148510 147953 147892 147863 147854 148463 148467 148482 148863 148857 148855 149128 149129 149131 149136 149150 149334 149471 149573 149571 149468 149328 149325 149324 149324 149467 149467 149467 149571 149571 149571 149648 149648 149647 149647 149648 149704 149747 149779 149779 149746 149703 149704 149705 149705 149749 149748 149748 149781 149782 149783 149809 149808 149806 149804 149804 149824 149839 149851 149853 149840 149824 149827 149829 149831 149847 149845 149843 149856 149858 149861 149873 149869 149866 149863 149861 149869 149876 149881 149885 149879 149872 149875 149879 149883 149891 149886 149882 149888 149893 149898 149904 149898 149893 149889 149885 149887 149889 149894 149892 149896 149902 149908 149910 149904 149898 149918 149915 149910 149904 149896 149887 149876 149864 149850 149832 149811 149784 149750 149706 149648 149571 149467 149325 149128 148855 148462 147854 147857 147861 147863 148468 148466 148464 148856 148858 148859 148861 148470 147866 147869 147872 147875 148475 148473 148471 148862 148863 148864 149136 149135 149134 149133 149132 149131 149130 149325 149326 149327 149468 149468 149467 149571 149572 149572 149572 149468 149328 149328 149329 149330 149469 149469 149469 149572 149572 149571 149571 149470 149330 149138 148866 148477 147878 147881 147883 147886 148483 148481 148479 148868 148870 148871 148873 148484 147888 147890 147891 147893 148489 148488 148486 148875 148878 148880 149153 149150 149147 149145 149143 149141 149139 149331 149333 149334 149471 149470 149470 149571 149571 149571 149571 149472 149336 149338 149340 149343 149476 149474 149473 149571 149572 149573 149574 149478 149346 149156 148883 148491 147894 147894 147894 147894 148496 148494 148493 148886 148889 148892 148895 148498 147894 147893 147891 147889 148503 148501 148499 148899 148903 148907 149193 149186 149180 149174 149169 149164 149160 149349 149353 149358 149488 149484 149481 149576 149578 149581 149585 149493 149363 149369 149376 149384 149514 149505 149499 149590 149597 149605 149615 149523 149393 149200 148912 148504 147886 147883 147879 147875 148510 148508 148506 148917 148922 148928 148935 148512 147870 147864 147858 147851 148522 148518 148515 148942 148950 148959 149278 149263 149249 149238 149227 149217 149208 149403 149414 149426 149561 149546 149534 149627 149642 149660 149680 149578 149440 149455 149472 149492 149642 149618 149597 149702 149723 149743 149803 149791 149776 149760 149742 149722 149706 149691 149679 149669 149662 149656 149653 149650 149648 149647 149646 149646 149646 149646 149646 149647 149647 149648 149648 149648 149649 149649 149649 149649 149648 149706 149707 149707 149752 149751 149751 149785 149786 149787 149788 149752 149707 149707 149707 149707 149753 149753 149753 149789 149789 149790 149821 149820 149818 149817 149815 149814 149813 149834 149836 149838 149858 149855 149852 149867 149871 149874 149878 149861 149841 149843 149845 149847 149870 149867 149864 149882 149887 149892 149897 149874 149850 149822 149791 149753 149706 149706 149706 149705 149753 149753 149753 149791 149792 149793 149794 149753 149705 149705 149705 149706 149755 149754 149754 149795 149797 149800 149840 149836 149832 149830 149827 149825 149824 149852 149855 149859 149888 149883 149878 149903 149910 149917 149926 149894 149862 149867 149873 149880 149919 149909 149901 149935 149945 149957 149991 149980 149968 149957 149947 149937 149928 149920 149913 149906 149899 149894 149889 149884 149880 149891 149896 149902 149915 149908 149901 149910 149918 149927 149937 149923 149909 149916 149924 149933 149955 149943 149932 149948 149961 149976 149995 149978 149963 149949 149937 149927 149918 149924 149934 149945 149951 149938 149927 149965 149959 149974 149991 150010 150019 150000 149982 150039 150028 150012 149991 149967 149943 149954 149965 149977 150006 149993 149980 150006 150020 150032 150041 150017 149988 150000 150010 150019 150038 150034 150027 150047 150049 150049 150054 150057 150059 150057 150052 150042 150028 150045 150058 150066 150073 150068 150056 150072 150067 150064 150060 150055 150055 150061 150066 150050 150050 150050 150047 150040 150025 150002 149969 149930 149888 149846 149803 149757 149706 149708 149710 149714 149769 149764 149760 149807 149814 149822 149832 149776 149718 149725 149734 149747 149812 149798 149785 149845 149860 149873 149919 149913 149902 149888 149874 149863 149853 149899 149911 149924 149967 149955 149942 149981 149990 149997 149998 149974 149937 149947 149951 149951 149975 149977 149977 149997 149994 149990 149986 149972 149951 149921 149881 149828 149763 149778 149791 149804 149852 149846 149838 149885 149887 149890 149892 149857 149816 149824 149833 149840 149869 149866 149862 149894 149896 149897 149922 149922 149922 149922 149922 149921 149921 149949 149948 149947 149964 149967 149969 149982 149979 149976 149974 149962 149945 149944 149943 149944 149960 149960 149961 149973 149972 149972 149981 149981 149982 149983 149985 149988 149991 149995 150000 150004 150009 150013 150015 150014 150010 150028 150028 150025 150030 150035 150039 150043 150038 150032 150027 150025 150021 150016 150010 150005 150010 150014 150019 150022 150018 150013 150016 150020 150024 150029 150034 150039 150044 150045 150040 150035 150036 150041 150045 150032 150031 150026 150021 150017 150017 150022 150027 150013 150012 150011 150009 150006 150001 149997 149994 149992 149996 149999 150002 150005 150002 149999 149996 149994 149990 149988 149987 149986 149989 149990 149992 149994 149992 149991 149991 149992 149994 149997 150000 150003 150007 150008 150004 150000 150001 150004 150008 149997 149997 149994 149992 149990 149990 149992 149994 149988 149989 149990 149990 149989 149987 149981 149973 149961 149944 149923 149899 149872 149845 149813 149761 149666 149514 149295 148970 148526 147843 147835 147826 147816 148546 148538 148532 148982 148996 149014 149038 148557 147806 147800 147805 147820 148635 148612 148578 149074 149110 149100 149411 149448 149434 149398 149364 149336 149314 149539 149566 149595 149734 149712 149689 149778 149791 149798 149794 149748 149625 149645 149632 149610 149779 149727 149742 149796 149821 149841 149854 149824 149706 149417 149018 148572 147795 147631 147517 147995 148998 148673 148423 149116 149357 149530 149632 149228 148431 148728 149253 149736 148925 148368 147926 147619 147151 147363 147736 147946 147543 147495 147737 147676 148719 148142 148218 148516 148748 148509 148547 148811 148095 147942 147748 148035 147872 148087 148101 148127 148812 148279 148138 148366 148518 148404 148429 149106 148470 148804 148391 148979 149644 149012 148878 149445 149973 150229 150059 150258 150084 149798 149426 149826 150046 150207 150224 150127 149997 149860 149769 149700 149577 149786 149828 149881 149938 149886 149847 149886 149923 149966 150015 149999 149962 150053 150137 150202 150176 150126 150065 150067 150115 150155 150185 150211 150244 150282 150301 150338 150334 150350 150282 150040 149581 148937 149112 149164 149141 148665 148638 148471 148557 148757 148685 148719 149166 148830 148772 148912 148826 148894 148972 149327 148915 149157 148897 149201 149860 149276 148991 150045 150026 149702 149261 149362 149391 149377 149373 149036 148994 149083 148951 148966 149009 149110 149055 149193 149080 149167 149220 149216 149312 149227 149257 149508 149227 149553 149257 149204 149395 149188 149518 149886 149556 149507 149516 149376 149400 149325 149372 149438 149601 149361 149419 149419 149512 149422 149489 149441 149489 149508 149665 149436 149641 149667 149637 149566 149791 149517 149913 149611 149662 149547 149572 149502 149583 149529 149620 149534 149574 149614 149603 149677 149599 149650 149640 149717 149638 149657 149805 149706 149685 149758 149696 149755 149719 149786 149725 149753 149784 149780 149837 149778 149818 149809 149874 149796 149840 149804 149839 149855 149940 149814 149887 149771 149874 149818 149745 149842 149796 149711 149799 149741 149767 149973 149830 149801 149654 149613 149782 149663 149601 149718 149609 149621 149525 149697 149922 149653 149731 149574 149953 149999 149949 149963 149896 149799 149867 149895 149862 149850 149905 149935 149904 149882 149937 149877 149891 149843 149894 149857 149915 149857 149904 149871 149924 149874 149903 149936 149918 149974 149903 149935 149923 149975 149912 149950 149917 149943 149964 150025 149930 150035 149938 149995 149954 149895 150001 149956 149899 149956 149913 149925 149851 149919 149989 149839 150004 150010 149957 149888 150042 150049 150000 149977 149989 149939 149981 149950 149997 149949 149990 149958 150005 149952 149976 149991 149987 150023 149976 149999 149987 150031 149969 149998 149968 149988 150010 150070 149999 150046 149981 150043 150026 149976 150027 150021 149959 150021 149984 150012 149957 149989 149970 150041 150046 150033 149997 150061 150061 150055 150010 150074 150024 150027 149983 150022 149986 150028 149977 150015 149979 150020 149971 149994 150018 149996 150041 149975 149998 149976 150017 149948 149966 150056 149998 149963 150007 149951 149991 149947 149991 149930 149955 150015 150042 149998 150057 150006 150034 150014 150046 150019 150069 150081 150088 150003 150026 150074 150046 150016 150096 150026 150063 150032 150075 150035 150054 150015 150067 150036 149941 150030 149920 150023 149901 149987 150003 150012 150016 150001 150016 149991 149975 149803 149966 149773 149967 149735 149983 150015 149981 150022 150042 150063 150055 150026 150069 150054 150026 149978 150065 149962 149922 149881 149343 149358 149238 150072 150183 150176 150060 150092 150180 150172 150131 150130 150087 150096 150099 150119 150126 150145 150157 150172 150198 150222 150228 150214 150209 150170 150314 150346 150326 150340 150306 150305 150265 150270 150265 150295 150276 150301 150317 150299 150264 150235 150222 150219 150251 150285 150274 150247 150220 150215 150235 150256 150238 150253 150231 150238 150239 150231 150204 150213 150215 150213 150206 150221 150209 150222 150205 150196 150187 150197 150186 150192 150197 150197 150193 150183 150166 150141 150108 150069 150027 149985 149948 149916 149888 149867 149848 149843 149835 149827 149827 149822 149850 149853 149855 149881 149877 149875 149901 149903 149908 149914 149886 149860 149867 149878 149896 149923 149907 149895 149923 149934 149949 149970 149957 149947 149939 149933 149928 149925 149946 149949 149953 149969 149965 149963 149975 149977 149980 149985 149974 149959 149966 149976 149987 149999 149989 149981 149991 149998 150006 150015 150010 150000 149985 149966 149942 149916 149941 149970 150002 150017 149990 149964 149985 150007 150030 150054 150046 150037 150071 150103 150131 150124 150101 150075 150078 150099 150118 150112 150097 150079 150060 150040 150020 150002 150014 150030 150046 150049 150035 150022 150026 150037 150048 150059 150062 150062 150078 150093 150105 150097 150087 150075 150070 150080 150089 150079 150072 150064 150055 150045 150036 150026 150018 150010 150003 149996 149991 149987 149985 149983 149987 149989 149991 149993 149991 149990 149990 149991 149992 149994 149995 149995 149999 150004 150010 150009 150003 149999 149997 150001 150006 150002 149998 149995 149993 149991 149990 149989 149988 149989 149989 149988 149988 149988 149989 149991 149993 149996 149999 149997 149994 149991 150001 150003 150007 150011 150014 150017 150025 150032 150040 150034 150027 150021 150016 150022 150027 150033 150041 150048 150056 150062 150068 150057 150052 150047 150038 150043 150047 150039 150035 150031 150026 150021 150016 150011 150007 150012 150016 150013 150009 150005 150018 150021 150025 150029 150032 150029 150025 150022 150031 150035 150042 150051 150061 150073 150084 150096 150106 150116 150125 150133 150142 150152 150168 150178 150182 150169 150164 150156 150145 150152 150157 150158 150170 150183 150180 150175 150169 150178 150169 150176 150183 150189 150194 150196 150199 150209 150181 150161 150155 150140 150132 150121 150111 150098 150080 150080 150094 150088 150078 150065 150050 150035 150015 150030 150042 150054 150066 150075 150083 150090 150096 150103 150111 150102 150095 150100 150107 150116 150127 150132 150145 150148 150164 150188 150181 150167 150150 150137 150135 150124 150121 150111 150103 150107 150115 150117 150127 150128 150138 150150 150165 150176 150173 150159 150151 150148 150158 150170 150165 150155 150144 150136 150137 150138 150129 150120 150119 150111 150109 150102 150100 150097 150093 150089 150084 150079 150072 150065 150055 150045 150035 150026 150029 150019 150030 150023 150014 150025 150019 150027 150024 150029 150029 150047 150037 149984 150078 149961 150026 150034 150020 150016 150022 150063 150055 150046 150035 149944 149898 149923 149965 149990 149968 149904 149946 149889 149938 149860 149888 149916 149869 149916 149824 149845 149963 149883 149828 149876 149793 149823 149857 149797 149850 149739 149764 149899 149873 149954 149914 149925 149973 149917 150026 149979 149987 149973 149992 149932 149853 149795 149690 149723 149842 149893 149874 149764 149690 149746 149618 149644 149801 149690 149607 149647 149708 149570 149615 149522 149560 149655 149778 149757 149836 149730 149956 149870 149900 149826 149700 149618 149490 149519 149563 149462 149498 149602 149721 149660 149715 149760 149649 149558 149423 149454 149502 149390 149429 149543 149675 149603 149669 149797 149921 149860 149909 149970 149991 150023 150004 149990 149993 149967 149998 150010 150015 150032 150012 150011 149927 149973 149975 150027 149969 149999 149987 150043 150045 149981 150034 149970 150024 150019 150023 150021 150025 150028 150032 150028 150025 150029 150029 150028 150031 150030 150030 150031 150030 150032 150030 150034 150039 150035 150042 150038 150047 150050 150051 150045 150047 150041 150036 150038 150034 150036 150032 150035 150039 150043 150041 150045 150043 150048 150052 150052 150056 150056 150057 150056 150064 150062 150061 150060 150059 150056 150056 150053 150049 150050 150047 150049 150046 150042 150038 150035 150031 150035 150039 150043 150039 150035 150031 150026 150019 150022 150029 150037 150028 150017 150002 150011 150027 150040 150025 150044 150059 150066 150050 150038 150046 150057 150069 150068 150059 150051 150042 150036 150040 150044 150047 150051 150049 150047 150053 150060 150066 150063 150059 150054 150055 150058 150060 150057 150056 150055 150052 150049 150046 150042 150045 150048 150051 150052 150050 150048 150050 150051 150052 150053 150053 150053 150054 150055 150055 150054 150054 150054 150053 150054 150053 150053 150054 150055 150057 150060 150065 150070 150075 150081 150085 150084 150075 150059 150032 149965 149840 149734 149596 149490 149352 149391 149447 149326 149372 149497 149632 149537 149624 149708 149560 149442 149299 149358 149432 149299 149378 149515 149647 149505 149613 149787 149919 149794 149877 150028 150131 150071 149891 149826 149612 149495 149345 149484 149649 149492 149731 149848 149888 149613 149747 149986 149947 149942 149853 149931 150060 150184 150013 150170 150021 150131 149982 149986 150173 150149 150136 150155 150141 150113 150109 150110 150117 150103 150112 150112 150111 150110 150109 150110 150112 150116 150128 150117 150117 150119 150124 150108 150099 150107 150109 150109 150110 150112 150113 150113 150113 150112 150109 150110 150112 150109 150107 150104 150101 150106 150110 150108 150106 150103 150097 150101 150104 150097 150094 150090 150080 150085 150089 150094 150098 150102 150106 150102 150096 150091 150082 150089 150097 150090 150080 150072 150065 150075 150085 150080 150075 150070 150058 150064 150069 150059 150053 150048 150039 150044 150049 150056 150063 150071 150079 150089 150104 150125 150150 150174 150180 150187 150174 150158 150087 150113 150153 150152 150127 150147 150164 150135 150115 150098 150087 150101 150120 150106 150089 150076 150068 150079 150092 150109 150128 150135 150113 150108 150117 150108 150091 150100 150098 150088 150086 150079 150071 150080 150093 150080 150070 150062 150058 150064 150071 150064 150059 150054 150050 150052 150055 150060 150066 150076 150082 150069 150061 150055 150047 150053 150063 150059 150050 150043 150039 150043 150048 150042 150037 150033 150030 150034 150038 150035 150032 150029 150030 150032 150034 150037 150042 150048 150053 150050 150045 150041 150041 150044 150048 150047 150044 150041 150039 150038 150039 150035 150032 150031 150032 150034 150036 150037 150035 150034 150035 150036 150038 150040 150042 150044 150046 150049 150052 150055 150059 150064 150070 150075 150078 150070 150067 150063 150058 150061 150064 150059 150058 150055 150054 150056 150059 150056 150053 150050 150049 150051 150053 150052 150050 150049 150049 150050 150051 150052 150054 150055 150056 150054 150053 150052 150052 150053 150053 150053 150052 150052 150051 150051 150052 150051 150050 150049 150049 150050 150051 150051 150050 150050 150049 150048 150048 150048 150048 150048 150048 150046 150044 150042 150043 150044 150046 150046 150045 150044 150042 150041 150041 150039 150038 150036 150038 150039 150040 150041 150040 150039 150041 150041 150042 150043 150044 150045 150047 150047 150046 150045 150046 150047 150048 150048 150048 150047 150047 150045 150044 150044 150043 150042 150043 150044 150045 150046 150045 150045 150044 150043 150041 150040 150038 150037 150035 150034 150032 150030 150029 150028 150027 150027 150030 150035 150043 150054 150065 150076 150086 150094 150101 150105 150106 150104 150098 150085 150086 150098 150098 150086 150086 150097 150100 150101 150103 150104 150102 150101 150099 150099 150096 150086 150085 150096 150095 150084 150083 150094 150095 150096 150097 150097 150095 150093 150090 150093 150093 150082 150082 150092 150091 150081 150079 150090 150089 150091 150092 150088 150086 150084 150082 150087 150088 150078 150077 150087 150085 150075 150074 150084 150082 150084 150086 150079 150077 150074 150065 150068 150071 150074 150077 150079 150082 150085 150087 150090 150093 150095 150098 150100 150102 150098 150095 150092 150084 150087 150091 150082 150078 150074 150070 150080 150089 150086 150083 150080 150070 150074 150077 150067 150063 150059 150047 150051 150055 150059 150063 150067 150072 150060 150056 150051 150040 150044 150049 150039 150035 150031 150027 150036 150047 150043 150039 150035 150025 150028 150032 150024 150021 150018 150015 150021 150031 150043 150055 150067 150077 150074 150070 150067 150056 150060 150063 150051 150048 150044 150040 150053 150064 150061 150058 150055 150042 150045 150049 150036 150032 150028 150015 150019 150023 150027 150031 150035 150039 150027 150024 150020 150012 150015 150018 150012 150010 150008 150006 150009 150016 150013 150009 150006 150002 150004 150006 150004 150003 150001 150000 150000 150003 150011 150023 150038 150051 150063 150072 150080 150082 150072 150070 150080 150078 150068 150066 150076 150074 150076 150078 150070 150068 150065 150063 150072 150073 150064 150062 150071 150068 150060 150058 150066 150065 150068 150070 150060 150057 150054 150051 150062 150063 150056 150054 150059 150056 150052 150050 150053 150051 150055 150058 150047 150043 150039 150033 150047 150050 150049 150047 150047 150043 150045 150042 150038 150029 150036 150041 150027 150020 150012 149997 150002 150007 150012 150018 150024 150029 150034 150039 150043 150047 150050 150054 150057 150060 150048 150044 150040 150025 150029 150033 150019 150015 150010 150006 150020 150036 150031 150026 150021 150005 150010 150015 150002 149998 149994 149990 149992 149994 149997 150000 150003 150007 150000 149998 149996 149996 149997 149998 149999 149999 149998 149998 149995 149994 149993 149992 149991 149994 149994 149994 149997 149997 149997 149997 149994 149991 149989 149991 150000 150016 150010 150005 150000 149990 149992 149996 149989 149988 149987 149987 149988 149996 149992 149990 149989 149988 149987 149987 149988 149989 149990 149994 149992 149991 149990 149989 149989 149989 149991 149992 149992 149995 149995 149994 149997 149997 149998 149998 149996 149993 149994 149996 149996 149999 149998 149997 149999 150000 150001 150002 150002 150001 150000 150000 149999 149999 149999 149999 150000 150000 150000 150001 150001 150002 150002 150003 150004 150005 150006 150007 150009 150010 150012 150014 150016 150019 150021 150024 150028 150031 150026 150024 150021 150021 150022 150025 150025 150023 150022 150020 150019 150019 150017 150015 150014 150015 150016 150017 150019 150018 150017 150019 150020 150021 150022 150023 150025 150026 150028 150026 150025 150027 150028 150029 150031 150029 150029 150027 150026 150024 150023 150022 150021 150023 150024 150025 150026 150025 150024 150024 150022 150020 150018 150016 150014 150012 150011 150010 150009 150011 150012 150013 150015 150014 150013 150012 150010 150008 150007 150006 150006 150008 150009 150009 150012 150011 150010 150012 150013 150013 150014 150015 150016 150017 150019 150018 150017 150019 150020 150021 150023 150022 150021 150020 150018 150016 150015 150015 150014 150016 150017 150017 150020 150019 150018 150021 150021 150022 150023 150023 150024 150025 150026 150026 150027 150028 150029 150030 150032 150032 150034 150033 150032 150034 150035 150036 150037 150036 150036 150035 150033 150031 150030 150029 150028 150031 150031 150032 150034 150033 150033 150035 150035 150036 150037 150037 150038 150039 150041 150040 150039 150041 150042 150042 150044 150043 150043 150043 150041 150039 150038 150038 150037 150039 150040 150040 150042 150042 150041 150041 150039 150037 150034 150032 150030 150028 150027 150026 150026 150028 150028 150029 150032 150031 150030 150030 150027 150025 150024 150024 150023 150026 150026 150027 150029 150029 150028 150031 150031 150032 150032 150033 150033 150034 150036 150036 150035 150038 150038 150038 150041 150040 150040 150040 150037 150035 150034 150034 150033 150036 150036 150037 150039 150039 150039 150038 150036 150033 150030 150028 150025 150023 150020 150018 150015 150013 150011 150009 150007 150005 150004 150004 150003 150005 150006 150006 150008 150008 150007 150007 150005 150003 150002 150002 150001 150003 150004 150004 150006 150006 150005 150007 150008 150008 150009 150009 150010 150010 150012 150012 150011 150014 150014 150015 150017 150017 150016 150016 150013 150011 150010 150010 150010 150012 150012 150013 150015 150015 150015 150014 150012 150010 150007 150005 150003 150001 150001 150001 150002 150003 150003 150003 150005 150005 150005 150006 150004 150002 150003 150004 150004 150006 150005 150005 150007 150007 150008 150010 150009 150009 150008 150008 150007 150007 150009 150010 150010 150012 150012 150012 150014 150014 150014 150015 150012 150010 150011 150011 150012 150014 150013 150013 150015 150015 150016 150018 150017 150017 150017 150017 150017 150017 150017 150017 150017 150018 150018 150019 150019 150020 150022 150022 150021 150024 150024 150025 150027 150027 150026 150026 150023 150021 150020 150020 150020 150022 150023 150023 150026 150025 150025 150028 150028 150028 150029 150029 150030 150030 150033 150032 150032 150035 150035 150035 150038 150038 150037 150037 150034 150031 150031 150031 150030 150033 150033 150034 150037 150036 150036 150035 150033 150030 150027 150025 150022 150019 150019 150019 150019 150021 150022 150022 150024 150024 150024 150024 150021 150019 150019 150019 150020 150022 150021 150021 150024 150023 150023 150025 150026 150026 150026 150026 150027 150027 150029 150029 150029 150031 150032 150032 150035 150034 150034 150033 150031 150028 150028 150028 150027 150029 150030 150030 150032 150032 150031 150030 150028 150027 150025 150024 150022 150020 150019 150017 150015 150013 150012 150010 150008 150006 150004 150002 150000 149998 149995 149991 149989 149988 149994 150006 150020 150031 150038 150030 150020 150015 150022 150008 150012 150001 150000 149994 149993 149990 149993 149996 149992 149995 149999 150002 149998 150001 150005 150007 150003 150005 150008 150010 150007 150009 150012 150013 150010 150012 150015 150016 150014 150015 150017 150019 150017 150018 150020 150021 150020 150021 150022 150023 150023 150024 150024 150025 150025 150027 150026 150027 150028 150029 150029 150030 150031 150032 150033 150034 150035 150035 150036 150037 150037 150038 150038 150039 150039 150040 150040 150040 150041 150041 150041 150042 150042 150042 150042 150043 150043 150043 150044 150044 150044 150044 150045 150045 150046 150046 150046 150047 150047 150048 150048 150049 150049 150050 150050 150051 150051 150052 150052 150052 150053 150053 150053 150053 150053 150053 150053 150053 150052 150051 150053 150053 150056 150058 150058 150061 150062 150064 150065 150067 150070 150075 150072 150069 150073 150076 150080 150084 150080 150076 150073 150070 150067 150065 150063 150062 150060 150059 150057 150055 150055 150054 150054 150054 150055 150055 150056 150057 150058 150060 150061 150063 150064 150066 150068 150070 150068 150066 150064 150063 150061 150060 150059 150058 150057 150056 150055 150055 150054 150054 150054 150053 150054 150054 150054 150055 150055 150054 150055 150055 150056 150056 150057 150058 150059 150060 150061 150063 150064 150066 150068 150070 150073 150075 150079 150083 150088 150091 150086 150082 150084 150089 150094 150096 150091 150086 150082 150080 150078 150075 150072 150069 150071 150073 150076 150078 150075 150072 150073 150076 150079 150083 150087 150092 150098 150104 150105 150112 150112 150120 150128 150127 150119 150111 150109 150116 150124 150133 150141 150150 150160 150153 150161 150152 150159 150164 150168 150157 150153 150149 150138 150142 150145 150146 150145 150141 150134 150124 150129 150132 150120 150117 150113 150101 150105 150107 150107 150120 150133 150132 150130 150126 150114 150117 150119 150106 150104 150100 150096 150109 150121 150133 150143 150137 150145 150138 150144 150136 150130 150122 150130 150120 150127 150116 150110 150103 150114 150107 150115 150122 150128 150120 150113 150105 150101 150108 150115 150108 150101 150094 150087 150093 150100 150090 150097 150086 150092 150098 150104 150092 150086 150080 150074 150069 150080 150074 150084 150078 150068 150057 150063 150051 150057 150063 150068 150074 150079 150083 150087 150090 150092 150093 150093 150092 150089 150076 150079 150080 150067 150066 150064 150053 150055 150055 150055 150067 150080 150079 150077 150074 150061 150064 150066 150054 150052 150049 150040 150042 150044 150045 150046 150045 150044 150037 150038 150039 150035 150034 150033 150035 150038 150038 150036 150034 150030 150032 150034 150027 150031 150037 150046 150057 150070 150066 150061 150056 150044 150049 150053 150042 150038 150034 150029 150039 150051 150045 150040 150035 150046 150040 150051 150062 150071 150080 150088 150094 150099 150102 150104 150105 150099 150099 150093 150088 150088 150093 150092 150098 150096 150093 150087 150090 150085 150087 150082 150083 150083 150079 150076 150073 150072 150075 150079 150078 150074 150071 150068 150069 150070 150070 150069 150068 150067 150065 150064 150062 150061 150060 150059 150058 150058 150057 150056 150056 150057 150057 150058 150059 150059 150060 150061 150062 150063 150065 150066 150067 150065 150064 150062 150061 150061 150060 150059 150059 150058 150057 150057 150056 150056 150055 150054 150054 150053 150053 150053 150052 150053 150053 150053 150054 150054 150053 150053 150052 150052 150052 150051 150051 150052 150052 150052 150053 150053 150052 150053 150053 150054 150054 150054 150054 150054 150055 150055 150055 150055 150056 150056 150056 150056 150056 150056 150055 150054 150054 150054 150054 150054 150055 150055 150055 150055 150055 150055 150054 150054 150053 150052 150051 150050 150050 150050 150049 150050 150051 150051 150052 150052 150051 150051 150050 150049 150048 150048 150048 150049 150049 150050 150051 150051 150051 150052 150052 150052 150052 150052 150053 150053 150054 150053 150053 150054 150054 150054 150055 150055 150055 150055 150054 150053 150053 150053 150053 150054 150054 150054 150055 150055 150055 150056 150056 150056 150056 150056 150055 150055 150055 150056 150056 150056 150056 150056 150057 150057 150057 150058 150059 150059 150059 150060 150060 150061 150062 150064 150066 150068 150067 150065 150063 150062 150064 150067 150065 150062 150060 150058 150060 150062 150060 150059 150058 150059 150058 150058 150058 150058 150057 150057 150057 150057 150057 150057 150058 150057 150056 150057 150055 150056 150058 150059 150057 150055 150054 150053 150052 150055 150054 150056 150057 150056 150057 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150055 150055 150054 150051 150051 150047 150048 150049 150050 150052 150053 150055 150057 150059 150062 150065 150068 150072 150076 150080 150077 150082 150077 150082 150088 150082 150076 150071 150066 150072 150067 150072 150068 150064 150059 150063 150057 150061 150053 150058 150063 150069 150074 150066 150060 150055 150045 150050 150056 150045 150040 150035 150030 150040 150050 150045 150040 150049 150045 150053 150049 150056 150061 150058 150055 150053 150047 150049 150052 150046 150043 150040 150037 150044 150050 150048 150047 150045 150039 150040 150042 150035 150033 150031 150023 150025 150027 150029 150032 150035 150038 150041 150032 150036 150027 150031 150035 150025 150021 150017 150013 150023 150019 150029 150026 150023 150013 150016 150006 150009 150000 150003 150007 150011 150015 150020 150024 150029 150035 150024 150029 150019 150024 150029 150034 150024 150019 150015 150007 150012 150016 150021 150025 150030 150033 150027 150024 150020 150017 150021 150024 150013 150016 150011 150007 150002 150000 150004 150009 149995 149998 150003 150010 150005 150014 150009 150019 150014 150005 149996 150000 149994 149998 149993 149989 149985 149989 149985 149992 150000 150010 150005 150001 149997 149988 149992 149996 149988 149984 149980 149974 149978 149981 149977 149981 149979 149983 149987 149991 149975 149972 149974 149970 149968 149965 149967 149971 149977 149985 149994 149990 149987 149997 149994 150003 150001 150010 150020 150018 150015 150013 150004 150006 150008 149998 149996 149994 149985 149987 149989 149991 149982 149984 149976 149979 149982 149974 149971 149969 149966 149974 149971 149980 149978 149976 149968 149969 149962 149964 149958 149960 149963 149965 149968 149964 149961 149959 149957 149959 149962 149955 149957 149955 149953 149956 149955 149960 149959 149966 149974 149983 149992 150002 150012 150021 150030 150037 150044 150043 150042 150041 150047 150046 150050 150053 150053 150055 150055 150055 150053 150053 150050 150050 150046 150040 150041 150034 150034 150035 150036 150028 150027 150026 150026 150025 150033 150033 150040 150046 150046 150050 150050 150053 150055 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150056 150057 150056 150056 150056 150056 150057 150057 150057 150057 150057 150057 150058 150058 150057 150057 150056 150056 150056 150056 150055 150055 150056 150054 150054 150053 150051 150051 150052 150052 150055 150056 150056 150057 150057 150057 150056 150055 150053 150054 150055 150051 150050 150049 150048 150047 150047 150046 150046 150040 150040 150033 150025 150025 150016 150016 150017 150018 150019 150020 150010 150009 150008 149998 149999 150001 149991 149990 149989 149988 149997 150007 150007 150006 150006 150016 150016 150025 150033 150033 150041 150041 150042 150034 150034 150025 150025 150016 150006 150006 149996 149996 149996 149997 149987 149987 149986 149986 149986 149996 149996 150006 150016 150016 150026 150026 150035 150042 150043 150044 150046 150038 150037 150036 150027 150028 150029 150020 150019 150018 150017 150007 150007 149997 149987 149986 149977 149977 149977 149977 149977 149978 149978 149979 149980 149982 149973 149972 149970 149963 149964 149965 149958 149957 149956 149955 149962 149970 149969 149969 149968 149961 149961 149961 149955 149954 149954 149949 149949 149949 149950 149950 149951 149952 149953 149950 149951 149949 149951 149953 149948 149947 149949 149948 149947 149945 149946 149944 149946 149946 149945 149945 149943 149943 149944 149943 149945 149949 149954 149961 149968 149968 149969 149969 149978 149978 149987 149997 149998 150008 150009 150010 150000 149999 149989 149988 149979 149970 149970 149962 149961 149961 149961 149954 149954 149955 149955 149956 149963 149963 149971 149979 149980 149990 149991 150001 150011 150021 150031 150040 150047 150052 150056 150057 150058 150058 150058 150058 150057 150056 150055 150054 150053 150052 150050 150049 150047 150047 150047 150047 150048 150049 150049 150050 150050 150050 150050 150048 150046 150046 150046 150046 150048 150048 150048 150050 150050 150050 150052 150052 150052 150052 150052 150052 150052 150053 150053 150053 150055 150054 150054 150056 150056 150056 150056 150055 150053 150053 150053 150053 150055 150055 150055 150056 150056 150057 150057 150055 150053 150052 150050 150048 150045 150045 150045 150045 150047 150047 150047 150049 150049 150049 150049 150047 150045 150044 150044 150044 150046 150047 150047 150049 150049 150049 150051 150051 150051 150051 150051 150052 150052 150054 150054 150054 150056 150055 150055 150057 150057 150057 150058 150056 150054 150054 150054 150054 150056 150056 150056 150058 150058 150058 150060 150060 150060 150059 150059 150059 150059 150058 150058 150058 150058 150057 150057 150057 150057 150057 150058 150058 150059 150058 150058 150058 150059 150059 150060 150059 150058 150059 150059 150059 150060 150060 150060 150060 150061 150061 150062 150061 150061 150060 150060 150059 150059 150059 150059 150060 150060 150059 150058 150057 150058 150059 150060 150060 150060 150061 150062 150062 150063 150062 150061 150061 150062 150063 150064 150064 150063 150062 150062 150061 150060 150060 150060 150061 150062 150062 150061 150062 150063 150063 150064 150063 150061 150061 150062 150062 150064 150063 150063 150064 150065 150065 150066 150066 150065 150065 150064 150064 150063 150064 150064 150065 150066 150065 150064 150065 150066 150066 150067 150066 150066 150066 150067 150067 150068 150068 150067 150068 150069 150069 150070 150069 150068 150067 150065 150064 150062 150060 150058 150056 150053 150051 150049 150046 150044 150043 150043 150043 150045 150046 150046 150048 150048 150048 150048 150045 150042 150042 150041 150041 150044 150044 150045 150047 150047 150046 150049 150049 150050 150050 150050 150051 150051 150053 150053 150053 150055 150056 150056 150058 150058 150058 150058 150055 150053 150052 150052 150051 150054 150054 150055 150057 150057 150056 150056 150053 150051 150048 150046 150043 150040 150040 150039 150038 150041 150042 150042 150045 150044 150043 150042 150040 150038 150037 150036 150035 150036 150038 150039 150041 150040 150038 150040 150042 150043 150045 150046 150047 150048 150050 150049 150048 150051 150052 150053 150055 150054 150053 150052 150049 150047 150046 150045 150042 150044 150047 150048 150050 150049 150047 150049 150051 150053 150054 150055 150056 150057 150058 150059 150059 150060 150060 150060 150060 150060 150062 150062 150062 150064 150064 150064 150066 150066 150066 150066 150064 150062 150062 150061 150061 150063 150064 150064 150066 150066 150065 150067 150068 150068 150068 150068 150067 150067 150068 150069 150069 150070 150070 150069 150070 150071 150071 150072 150070 150069 150069 150069 150069 150071 150071 150071 150072 150072 150072 150072 150070 150069 150067 150065 150063 150060 150060 150059 150058 150060 150061 150062 150064 150063 150062 150061 150059 150056 150055 150054 150051 150053 150056 150057 150059 150058 150055 150058 150060 150062 150063 150064 150066 150066 150068 150068 150067 150069 150069 150070 150072 150071 150070 150069 150067 150065 150064 150063 150060 150063 150065 150066 150068 150067 150065 150067 150069 150070 150071 150072 150073 150073 150073 150073 150073 150073 150073 150073 150072 150072 150071 150070 150070 150069 150068 150067 150066 150064 150063 150062 150060 150059 150057 150056 150055 150053 150048 150050 150051 150044 150043 150041 150032 150034 150036 150038 150046 150053 150055 150057 150058 150053 150050 150048 150040 150042 150044 150034 150032 150030 150028 150026 150024 150022 150012 150014 150015 150005 150003 150002 149992 149993 149995 149996 150006 150017 150019 150021 150023 150012 150010 150008 149998 150000 150002 150004 150014 150026 150037 150047 150055 150060 150062 150064 150066 150062 150060 150057 150049 150052 150055 150058 150064 150067 150069 150070 150071 150070 150068 150066 150061 150064 150067 150059 150055 150052 150048 150045 150042 150039 150028 150031 150034 150022 150019 150017 150006 150008 150011 150013 150025 150037 150040 150044 150048 150035 150032 150028 150016 150019 150023 150011 150008 150005 150003 150000 149998 149996 149994 149992 149990 149988 149987 149985 149984 149983 149981 149973 149972 149964 149958 149957 149952 149951 149950 149950 149949 149949 149945 149946 149946 149944 149944 149943 149945 149947 149947 149948 149949 149953 149954 149959 149965 149966 149974 149975 149977 149969 149968 149961 149960 149955 149951 149950 149948 149947 149946 149945 149949 149950 149952 149956 149957 149962 149964 149970 149978 149980 149981 149983 149975 149973 149972 149965 149967 149968 149963 149961 149960 149958 149955 149954 149951 149953 149954 149956 149958 149959 149957 149956 149959 149961 149965 149970 149977 149985 149987 149989 149991 149983 149981 149979 149972 149974 149976 149978 149985 149993 149996 149998 150001 149992 149989 149987 149980 149982 149984 149978 149976 149974 149972 149970 149968 149967 149963 149965 149966 149964 149962 149961 149966 149968 149970 149972 149974 149972 149970 149968 149974 149976 149981 149987 149994 150003 150014 150026 150039 150052 150063 150069 150072 150072 150073 150073 150074 150075 150074 150073 150072 150074 150075 150077 150076 150074 150075 150075 150075 150077 150077 150076 150078 150078 150079 150080 150079 150077 150075 150072 150069 150066 150056 150060 150065 150053 150048 150044 150030 150034 150039 150044 150058 150069 150072 150076 150078 150072 150068 150063 150049 150055 150060 150066 150076 150080 150081 150079 150077 150075 150075 150074 150074 150076 150076 150076 150079 150078 150078 150077 150075 150073 150072 150071 150069 150072 150073 150074 150076 150075 150074 150077 150077 150079 150080 150080 150081 150081 150082 150083 150083 150083 150082 150079 150071 150076 150080 150082 150084 150082 150082 150080 150080 150083 150084 150084 150084 150085 150086 150086 150083 150079 150075 150070 150064 150058 150051 150045 150040 150034 150029 150025 150021 150017 150006 150009 150013 150002 150000 149997 149989 149991 149994 149997 150006 150016 150020 150025 150030 150017 150013 150009 150000 150003 150006 149998 149995 149993 149990 149988 149985 149983 149979 149981 149983 149980 149978 149976 149983 149985 149988 149990 149993 149990 149987 149985 149992 149995 150001 150010 150021 150036 150042 150048 150055 150039 150032 150026 150014 150019 150024 150030 150046 150062 150069 150075 150081 150069 150061 150053 150037 150045 150054 150039 150030 150023 150018 150013 150008 150004 149998 150001 150005 150000 149997 149995 150003 150009 150013 150019 150027 150021 150012 150007 150029 150032 150045 150062 150076 150084 150086 150084 150081 150077 150074 150071 150068 150066 150063 150061 150059 150056 150054 150052 150050 150047 150045 150044 150042 150040 150038 150036 150035 150033 150032 150031 150032 150033 150035 150033 150034 150036 150038 150035 150037 150039 150041 150038 150039 150042 150044 150041 150042 150046 150048 150044 150046 150050 150052 150047 150050 150054 150056 150052 150054 150058 150061 150056 150059 150063 150066 150061 150064 150069 150072 150067 150071 150076 150080 150075 150078 150083 150083 150080 150076 150078 150065 150065 150047 150047 150034 150035 150033 150032 150023 149986 149944 149942 149928 149785 149739 149810 149916 149990 149948 149979 149988 150041 149995 149918 149805 149771 149299 149329 148693 148232 145412 145378 150068 150068 150059 150054 150066 150073 150070 150062 150044 150059 150044 150031 150025 150035 150028 150022 150018 150016 150012 150005 150003 150004 150007 150010 150012 150014 150015 150016 150017 150018 150019 150020 150020 150021 150022 150022 150023 150023 150024 150025 150025 150026 150026 150027 150028 150028 150029 150029 150030 150031 150031 150032 150033 150033 150034 150035 150035 150036 150037 150038 150039 150040 150041 150043 150044 150046 150049 150052 150054 150056 150055 150046 150038 150036 ) ; boundaryField { bottomEmptyFaces { type empty; } topEmptyFaces { type empty; } inlet { type calculated; value nonuniform List<scalar> 70 ( 150035 150035 150035 150035 150035 150034 150034 150034 150034 150033 150033 150033 150033 150032 150032 150032 150032 150031 150031 150031 150030 150030 150029 150029 150029 150028 150028 150028 150027 150027 150027 150026 150026 150026 150025 150025 150024 150024 150024 150024 150023 150023 150023 150022 150022 150022 150022 150021 150021 150021 150021 150020 150020 150020 150020 150020 150020 150020 150020 150020 150020 150020 150020 150020 150020 150019 150035 150017 150019 150019 ) ; } outlet { type calculated; value nonuniform List<scalar> 35 ( 149886 149884 149881 149878 149872 149865 149857 149846 149833 149817 149798 149772 149740 149698 149642 149567 149465 149330 149148 148913 148596 148196 147351 147867 147097 146815 145664 146429 145408 144964 143532 135838 139223 141271 149886 ) ; } walls { type calculated; value nonuniform List<scalar> 681 ( 129200 129241 129263 129303 129323 129359 129377 129411 129428 129459 129474 129503 129517 129544 129556 129582 129593 129617 129627 129649 129659 129679 129688 129707 129715 129732 129739 129756 129762 129778 129783 129798 129803 129817 129821 129834 129838 129850 129853 129865 129868 129878 129881 129891 129893 129902 129904 129913 129915 129923 129924 129932 129933 129941 129941 129948 129949 129955 129955 129962 129962 129968 129968 129974 129973 129979 129978 129983 129982 129988 129987 129992 129990 129995 129994 129999 129997 130002 130000 130004 130002 130006 130004 130008 130006 130010 130008 130011 130009 130013 130010 130014 130011 130014 130011 130015 130012 130015 130012 130015 130012 130015 130012 130015 130012 130015 130011 130014 130011 130014 130010 130013 130010 130012 130009 130011 130007 130010 130006 130008 130004 130006 130002 130004 130000 130001 129997 129998 129993 129995 129990 129991 129986 129987 129982 129984 129979 129980 129975 129976 129971 129972 129966 129968 129964 129966 129962 129962 129960 129979 130037 143803 143807 143915 143976 144757 144720 144967 145021 145036 144981 144707 144294 144532 144538 144400 144406 144060 144126 144126 144258 144637 144628 147096 147145 147136 146896 147154 147075 147122 147125 147082 147174 146923 147132 147121 147076 146905 146997 147010 146929 146952 146955 146799 146802 146755 146660 146567 146605 146587 146776 146726 146720 146843 146841 146923 146854 147074 147049 147039 147057 147001 147129 147044 145520 145924 146019 145635 145672 145647 145588 145612 145753 145686 146267 146156 146062 146315 145954 146371 146312 146528 146536 146505 146527 146241 146319 146310 145952 145943 146035 146028 138771 138765 145122 145117 145235 145256 138227 145370 145291 145553 145227 137615 137682 137765 137844 138464 138532 130750 129120 128970 129291 130038 128975 128024 128602 126933 126688 126404 146180 126454 125081 126191 123948 123735 123606 123532 121171 122072 120966 120021 120595 146864 146613 146435 146391 146300 146589 146358 146757 146742 146663 146868 146739 145838 147431 135767 145807 145694 145347 146123 145843 134912 134839 150254 135078 135376 150738 150652 150668 150379 150264 150035 150198 133182 131991 131265 131301 132562 132759 133114 132897 134768 134205 134657 133440 134015 136386 136308 137080 149949 149856 137321 137453 136516 136670 149791 149651 149652 136063 136216 131024 131183 149587 149527 149477 149435 118137 117778 115146 117039 117589 113116 115028 114863 113310 112832 112312 112497 112584 113398 115403 118041 119637 120612 121380 122095 122691 123219 123651 124062 124410 124756 147015 146948 146951 146858 147024 146948 147064 147068 147001 147107 147040 149392 149348 149293 149381 125050 125347 149260 125593 149224 125844 149195 149164 126050 149133 126266 126440 126628 149110 149084 149059 149033 126778 126945 149009 148989 127076 148970 127224 148948 127338 127472 127572 127693 148942 148946 127782 127892 148956 148971 127971 148977 128071 148983 148985 128142 148989 128233 128297 128380 148990 148993 148993 148995 128437 128513 148995 148997 128564 148997 128635 148998 128681 128745 128786 128847 148997 148999 128884 128939 148998 148999 128973 148998 129025 149000 148998 129055 149000 129103 129130 129175 148998 149000 148998 148999 148998 148999 148998 148999 148997 148998 148997 148998 148996 148997 148996 148997 148995 148996 148994 148995 148990 148994 149028 148905 142728 141385 141482 141704 141859 141913 141462 141646 142061 142109 142236 142288 142374 142479 142463 142753 139707 139760 139883 139846 140631 140897 140947 140755 140778 140045 140239 140338 140417 139532 139266 139263 138982 138957 141148 141265 143338 143283 143010 143001 142865 142864 143179 143178 143584 143675 143710 143622 143277 130069 149014 147241 147229 147217 147205 147195 147188 147183 147178 147175 147172 147171 147170 147170 147170 147170 147172 147175 147177 147181 147184 147189 147193 147198 147204 147210 147216 147223 147230 147238 147246 147255 147263 147273 147282 147293 147303 147314 147326 147337 147350 147362 147375 147389 147403 147418 147433 147448 147464 147480 147497 147515 147532 147551 147570 147589 147609 147630 147651 147673 147695 147718 147741 147765 147790 147815 147841 147867 147894 147922 147950 147978 148008 148037 148067 148098 148129 148161 148193 148225 148258 148291 148324 148357 148390 148424 148457 148490 148522 148555 148586 148617 148648 148677 148706 148734 148760 148785 148809 148832 148852 148872 148890 148906 148921 148934 148946 148957 148966 148974 148981 148987 148992 148996 148999 149002 149004 149006 149007 149008 149009 149010 149010 149010 149010 149010 149010 149009 149009 149009 149008 149008 149007 149007 149006 149006 149006 149004 149004 147265 149004 ) ; } rightWall { type calculated; value nonuniform List<scalar> 30 ( 150075 150116 150129 150139 150147 150149 150147 150142 150137 150129 150121 150111 150101 150089 150077 150062 150047 150027 150008 149982 149960 149932 149891 149831 149654 149887 149979 149461 149650 149738 ) ; } symmetryLine { type symmetryPlane; } } // ************************************************************************* //
[ "mhoeper3234@gmail.com" ]
mhoeper3234@gmail.com
8d6a8fa5d2651c1cfa73cdd6a9a62eabf9c70c92
7d46e8745a7c6d7c369a9e212cabb6b8b6dd0334
/addons/Webm/include/webm/IVFReader.h
1487404cb72edc76452d6d74f8215b42a05cea96
[]
no_license
eighteight/roxlu_experimental2
02166ccab0322061b3ed4269dcfd2453f2fea537
5a4d3f81a5abcac415adfa107c4d4bc7d4fb173c
refs/heads/master
2021-01-22T09:51:01.638125
2013-10-10T15:33:49
2013-10-10T15:33:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,637
h
#ifndef ROXLU_WEBM_IVF_READER_H #define ROXLU_WEBM_IVF_READER_H #include <string> #include <vector> #include <deque> #include <roxlu/io/RingBuffer.h> #include <roxlu/core/Utils.h> #include <webm/VPXEncoder.h> /* for the VPXSettings */ #include <webm/VPXDecoder.h> #define IVF_ERR_FOPEN "Cannot open the file: %s" #define IVF_ERR_READ_HEADER "Cannot read the ivf-header" #define IVF_ERR_INVALID_FILE "Not a correct ivf-file" #define IVF_ERR_INVALID_SIZE "The ivf-header contains an invalid width or height (%d, %d)" #define IVF_ERR_FRAME_TOO_BIG "The current frame size is too big to handle" #define IVF_ERR_READ_FRAME "Cannot read the frame" #define IVF_ERR_FRAME_READ_HDR "Cannot read frame header.. at the end the file?" #define IVF_ERR_FRAME_STATE "Cannot read a frame because the current state is not IVF_STATE_PLAY" #define IVF_ERR_DECODER_SETUP "Cannot setup the decoder" #define IVF_ERR_ALREADY_OPEN "We've already opened a ivf file" #define IVF_ERR_CLOSE "Cannot close ivf as we haven't opened a file yet" #define IVF_ERR_ALREADY_PLAYING "We're already playing. First call stop, then play again to restart" #define IVF_ERR_HDR_FILE "Cannot read the IVF header because the file pointer is invalid" #define IVF_ERR_HDR_SEEK "Cannot set the file pointer to the beginning of the file" #define IVF_V_ALREADY_PAUSED "We're already paused... not pausing again :) " #define IVF_FILE_HDR_SIZE 32 #define IVF_FRAME_HDR_SIZE 12 struct IVFFrame { IVFFrame(); size_t offset; /* offset in the buffer */ uint64_t pts; /* presentation timestamp from the ivf file */ uint64_t millis; /* time in millis when this frame should be played back */ size_t size; /* number of bytes */ }; #define IVF_STATE_NONE 0 #define IVF_STATE_PLAY 1 #define IVF_STATE_PAUSE 2 class IVFReader { public: IVFReader(vpx_read_cb readCB, void* readUser = NULL); ~IVFReader(); bool open(std::string filename, bool datapath = false); /* open a file for reading */ bool close(); /* close the current file and reset everythin */ void print(); /* print some verbose info */ void play(); /* start playing back */ void stop(); /* stop the current playback */ void pause(); /* pause the current playback */ void update(); /* call this as often as possible */ void setFPS(double fps); /* force this FPS, when you use this function we assume you're using `avconv` as described in the README.md because somehow the timebase with avconv is always 1/90000 and it's not setting the correct fps. */ private: bool readHeader(); /* read the file header, once the file has been opened, this can be called any time after you've opened a file.. it will reset the read pointer to the start of the file. see stop() of all other house keeping you need to do when you want to restart a stream */ void reset(); /* resets all members used while decoding (does not reset the state, width/height etc..) */ bool shutdown(); /* destructor; resets everything to the same state as when the object was created */ bool readFrame(); /* reads a raw encoded frame and adds a new IVFFrame to the "frames" buffer that is used when playing back */ void updateBuffer(); /* updates the buffer with read (encoded) frames */ public: /* playback */ int state; /* current state ... */ uint64_t time_started; /* time the playback started, in millis */ uint64_t time_paused; double time_base; /* used to convert pts (presentation time stamps) to current playback time */ size_t frame_dx; /* current read frame is reset to 0 after decoding, in update() */ ssize_t last_frame_dx; /* last frame dx we showed */ /* buffer */ RingBuffer rbuffer; int num_frames_to_buffer; /* number of frames we need to pre-buffer so we have a smooth playback */ size_t num_read_frames; /* how many raw frames have been read */ std::deque<IVFFrame> frames; /* contains IVFFrame information that is used to synchronize the IVF timestamps when playing back the file*/ /* decoder */ VPXDecoder* decoder; /* the decoder wrapper */ vpx_read_cb cb_read; /* function that gets called by the VPXDecoder when it has decoded a frame */ void* cb_user; /* internally used by the VPXDecoder */ /* reading IVF */ FILE* fp; /* the file pointer of the currenet ivf file, see IVF::open() */ uint16_t width; /* width of the video */ uint16_t height; /* height of the video */ uint32_t rate; /* time base, rate: used in combination with the pts values (presentation time stamps) while playing back, a value like 90000 is used by the avconv util when converting a 29.97 fps video to ivf */ uint32_t scale; /* time base, scale: probably something like 1 */ uint32_t num_frames; /* number of frames in the ivf file.. might be 0 when the encoder doesn't store this value.. it's not used for playback */ unsigned char frame_hdr[IVF_FRAME_HDR_SIZE]; /* each frame contains a small header */ unsigned char frame_data[256 * 1024]; /* buffer for one frame */ }; #endif
[ "info@roxlu.com" ]
info@roxlu.com
4e4459cdba72e15c99aa62311478f85c636f7021
175dea377eb9384e2a33a830acf76be26d3a9b48
/libraries/chain/include/myeosio/chain/wasm_myeosio_validation.hpp
a208542839e97922c4922589ddaf4427189ee6fe
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
bithacks-tech/myeosio
f0c6d38ef2d820b5384e4c30903ff33e51285022
577f6830e72fa764497c20a6b9200ba02b80ab2e
refs/heads/myeosio
2020-03-22T02:35:39.761883
2018-08-13T05:26:23
2018-08-13T05:26:23
139,381,083
0
0
MIT
2018-07-16T12:15:56
2018-07-02T02:26:28
WebAssembly
UTF-8
C++
false
false
22,716
hpp
#pragma once #include <fc/exception/exception.hpp> #include <myeosio/chain/exceptions.hpp> #include <myeosio/chain/controller.hpp> #include <myeosio/chain/wasm_myeosio_binary_ops.hpp> #include <functional> #include <vector> #include <iostream> #include "IR/Module.h" #include "IR/Operators.h" #include "WASM/WASM.h" namespace myeosio { namespace chain { namespace wasm_validations { // module validators // effectively do nothing and pass struct noop_validation_visitor { static void validate( const IR::Module& m ); }; struct memories_validation_visitor { static void validate( const IR::Module& m ); }; struct data_segments_validation_visitor { static void validate( const IR::Module& m ); }; struct tables_validation_visitor { static void validate( const IR::Module& m ); }; struct globals_validation_visitor { static void validate( const IR::Module& m ); }; struct maximum_function_stack_visitor { static void validate( const IR::Module& m ); }; struct ensure_apply_exported_visitor { static void validate( const IR::Module& m ); }; using wasm_validate_func = std::function<void(IR::Module&)>; // just pass struct no_constraints_validators { static void validate( const IR::Module& m ) {} }; // instruction validators // simple mutator that doesn't actually mutate anything // used to verify that a given instruction is valid for execution on our platform // for validators set kills to true, this eliminates the extraneous building // of new code that is going to get thrown away any way struct whitelist_validator { static constexpr bool kills = true; static constexpr bool post = false; static void accept( wasm_ops::instr* inst, wasm_ops::visitor_arg& arg ) { // just pass } }; template <typename T> struct large_offset_validator { static constexpr bool kills = true; static constexpr bool post = false; static void accept( wasm_ops::instr* inst, wasm_ops::visitor_arg& arg ) { // cast to a type that has a memarg field T* memarg_instr = reinterpret_cast<T*>(inst); if(memarg_instr->field.o >= wasm_constraints::maximum_linear_memory) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract used an invalid large memory store/load offset"); } }; struct debug_printer { static constexpr bool kills = false; static constexpr bool post = false; static void init() {} static void accept( wasm_ops::instr* inst, wasm_ops::visitor_arg& arg ) { std::cout << "INSTRUCTION : " << inst->to_string() << "\n"; } }; struct wasm_opcode_no_disposition_exception { std::string opcode_name; }; struct blacklist_validator { static constexpr bool kills = true; static constexpr bool post = false; static void accept( wasm_ops::instr* inst, wasm_ops::visitor_arg& arg ) { FC_THROW_EXCEPTION(wasm_execution_error, "Error, blacklisted opcode ${op} ", ("op", inst->to_string())); } }; struct nested_validator { static constexpr bool kills = false; static constexpr bool post = false; static bool disabled; static uint16_t depth; static void init(bool disable) { disabled = disable; depth = 0; } static void accept( wasm_ops::instr* inst, wasm_ops::visitor_arg& arg ) { if (!disabled) { if ( inst->get_code() == wasm_ops::end_code && depth > 0 ) { depth--; return; } depth++; MES_ASSERT(depth < 1024, wasm_execution_error, "Nested depth exceeded"); } } }; // add opcode specific constraints here // so far we only black list struct op_constrainers : wasm_ops::op_types<blacklist_validator> { using block_t = wasm_ops::block <whitelist_validator, nested_validator>; using loop_t = wasm_ops::loop <whitelist_validator, nested_validator>; using if__t = wasm_ops::if_ <whitelist_validator, nested_validator>; using else__t = wasm_ops::else_ <whitelist_validator, nested_validator>; using end_t = wasm_ops::end <whitelist_validator, nested_validator>; using unreachable_t = wasm_ops::unreachable <whitelist_validator>; using br_t = wasm_ops::br <whitelist_validator>; using br_if_t = wasm_ops::br_if <whitelist_validator>; using br_table_t = wasm_ops::br_table <whitelist_validator>; using return__t = wasm_ops::return_ <whitelist_validator>; using call_t = wasm_ops::call <whitelist_validator>; using call_indirect_t = wasm_ops::call_indirect <whitelist_validator>; using drop_t = wasm_ops::drop <whitelist_validator>; using select_t = wasm_ops::select <whitelist_validator>; using get_local_t = wasm_ops::get_local <whitelist_validator>; using set_local_t = wasm_ops::set_local <whitelist_validator>; using tee_local_t = wasm_ops::tee_local <whitelist_validator>; using get_global_t = wasm_ops::get_global <whitelist_validator>; using set_global_t = wasm_ops::set_global <whitelist_validator>; using grow_memory_t = wasm_ops::grow_memory <whitelist_validator>; using current_memory_t = wasm_ops::current_memory <whitelist_validator>; using nop_t = wasm_ops::nop <whitelist_validator>; using i32_load_t = wasm_ops::i32_load <large_offset_validator<wasm_ops::op_types<>::i32_load_t>, whitelist_validator>; using i64_load_t = wasm_ops::i64_load <large_offset_validator<wasm_ops::op_types<>::i64_load_t>, whitelist_validator>; using f32_load_t = wasm_ops::f32_load <large_offset_validator<wasm_ops::op_types<>::f32_load_t>, whitelist_validator>; using f64_load_t = wasm_ops::f64_load <large_offset_validator<wasm_ops::op_types<>::f64_load_t>, whitelist_validator>; using i32_load8_s_t = wasm_ops::i32_load8_s <large_offset_validator<wasm_ops::op_types<>::i32_load8_s_t>, whitelist_validator>; using i32_load8_u_t = wasm_ops::i32_load8_u <large_offset_validator<wasm_ops::op_types<>::i32_load8_u_t>, whitelist_validator>; using i32_load16_s_t = wasm_ops::i32_load16_s <large_offset_validator<wasm_ops::op_types<>::i32_load16_s_t>, whitelist_validator>; using i32_load16_u_t = wasm_ops::i32_load16_u <large_offset_validator<wasm_ops::op_types<>::i32_load16_u_t>, whitelist_validator>; using i64_load8_s_t = wasm_ops::i64_load8_s <large_offset_validator<wasm_ops::op_types<>::i64_load8_s_t>, whitelist_validator>; using i64_load8_u_t = wasm_ops::i64_load8_u <large_offset_validator<wasm_ops::op_types<>::i64_load8_u_t>, whitelist_validator>; using i64_load16_s_t = wasm_ops::i64_load16_s <large_offset_validator<wasm_ops::op_types<>::i64_load16_s_t>, whitelist_validator>; using i64_load16_u_t = wasm_ops::i64_load16_u <large_offset_validator<wasm_ops::op_types<>::i64_load16_u_t>, whitelist_validator>; using i64_load32_s_t = wasm_ops::i64_load32_s <large_offset_validator<wasm_ops::op_types<>::i64_load32_s_t>, whitelist_validator>; using i64_load32_u_t = wasm_ops::i64_load32_u <large_offset_validator<wasm_ops::op_types<>::i64_load32_u_t>, whitelist_validator>; using i32_store_t = wasm_ops::i32_store <large_offset_validator<wasm_ops::op_types<>::i32_store_t>, whitelist_validator>; using i64_store_t = wasm_ops::i64_store <large_offset_validator<wasm_ops::op_types<>::i64_store_t>, whitelist_validator>; using f32_store_t = wasm_ops::f32_store <large_offset_validator<wasm_ops::op_types<>::f32_store_t>, whitelist_validator>; using f64_store_t = wasm_ops::f64_store <large_offset_validator<wasm_ops::op_types<>::f64_store_t>, whitelist_validator>; using i32_store8_t = wasm_ops::i32_store8 <large_offset_validator<wasm_ops::op_types<>::i32_store8_t>, whitelist_validator>; using i32_store16_t = wasm_ops::i32_store16 <large_offset_validator<wasm_ops::op_types<>::i32_store16_t>, whitelist_validator>; using i64_store8_t = wasm_ops::i64_store8 <large_offset_validator<wasm_ops::op_types<>::i64_store8_t>, whitelist_validator>; using i64_store16_t = wasm_ops::i64_store16 <large_offset_validator<wasm_ops::op_types<>::i64_store16_t>, whitelist_validator>; using i64_store32_t = wasm_ops::i64_store32 <large_offset_validator<wasm_ops::op_types<>::i64_store32_t>, whitelist_validator>; using i32_const_t = wasm_ops::i32_const <whitelist_validator>; using i64_const_t = wasm_ops::i64_const <whitelist_validator>; using f32_const_t = wasm_ops::f32_const <whitelist_validator>; using f64_const_t = wasm_ops::f64_const <whitelist_validator>; using i32_eqz_t = wasm_ops::i32_eqz <whitelist_validator>; using i32_eq_t = wasm_ops::i32_eq <whitelist_validator>; using i32_ne_t = wasm_ops::i32_ne <whitelist_validator>; using i32_lt_s_t = wasm_ops::i32_lt_s <whitelist_validator>; using i32_lt_u_t = wasm_ops::i32_lt_u <whitelist_validator>; using i32_gt_s_t = wasm_ops::i32_gt_s <whitelist_validator>; using i32_gt_u_t = wasm_ops::i32_gt_u <whitelist_validator>; using i32_le_s_t = wasm_ops::i32_le_s <whitelist_validator>; using i32_le_u_t = wasm_ops::i32_le_u <whitelist_validator>; using i32_ge_s_t = wasm_ops::i32_ge_s <whitelist_validator>; using i32_ge_u_t = wasm_ops::i32_ge_u <whitelist_validator>; using i32_clz_t = wasm_ops::i32_clz <whitelist_validator>; using i32_ctz_t = wasm_ops::i32_ctz <whitelist_validator>; using i32_popcnt_t = wasm_ops::i32_popcnt <whitelist_validator>; using i32_add_t = wasm_ops::i32_add <whitelist_validator>; using i32_sub_t = wasm_ops::i32_sub <whitelist_validator>; using i32_mul_t = wasm_ops::i32_mul <whitelist_validator>; using i32_div_s_t = wasm_ops::i32_div_s <whitelist_validator>; using i32_div_u_t = wasm_ops::i32_div_u <whitelist_validator>; using i32_rem_s_t = wasm_ops::i32_rem_s <whitelist_validator>; using i32_rem_u_t = wasm_ops::i32_rem_u <whitelist_validator>; using i32_and_t = wasm_ops::i32_and <whitelist_validator>; using i32_or_t = wasm_ops::i32_or <whitelist_validator>; using i32_xor_t = wasm_ops::i32_xor <whitelist_validator>; using i32_shl_t = wasm_ops::i32_shl <whitelist_validator>; using i32_shr_s_t = wasm_ops::i32_shr_s <whitelist_validator>; using i32_shr_u_t = wasm_ops::i32_shr_u <whitelist_validator>; using i32_rotl_t = wasm_ops::i32_rotl <whitelist_validator>; using i32_rotr_t = wasm_ops::i32_rotr <whitelist_validator>; using i64_eqz_t = wasm_ops::i64_eqz <whitelist_validator>; using i64_eq_t = wasm_ops::i64_eq <whitelist_validator>; using i64_ne_t = wasm_ops::i64_ne <whitelist_validator>; using i64_lt_s_t = wasm_ops::i64_lt_s <whitelist_validator>; using i64_lt_u_t = wasm_ops::i64_lt_u <whitelist_validator>; using i64_gt_s_t = wasm_ops::i64_gt_s <whitelist_validator>; using i64_gt_u_t = wasm_ops::i64_gt_u <whitelist_validator>; using i64_le_s_t = wasm_ops::i64_le_s <whitelist_validator>; using i64_le_u_t = wasm_ops::i64_le_u <whitelist_validator>; using i64_ge_s_t = wasm_ops::i64_ge_s <whitelist_validator>; using i64_ge_u_t = wasm_ops::i64_ge_u <whitelist_validator>; using i64_clz_t = wasm_ops::i64_clz <whitelist_validator>; using i64_ctz_t = wasm_ops::i64_ctz <whitelist_validator>; using i64_popcnt_t = wasm_ops::i64_popcnt <whitelist_validator>; using i64_add_t = wasm_ops::i64_add <whitelist_validator>; using i64_sub_t = wasm_ops::i64_sub <whitelist_validator>; using i64_mul_t = wasm_ops::i64_mul <whitelist_validator>; using i64_div_s_t = wasm_ops::i64_div_s <whitelist_validator>; using i64_div_u_t = wasm_ops::i64_div_u <whitelist_validator>; using i64_rem_s_t = wasm_ops::i64_rem_s <whitelist_validator>; using i64_rem_u_t = wasm_ops::i64_rem_u <whitelist_validator>; using i64_and_t = wasm_ops::i64_and <whitelist_validator>; using i64_or_t = wasm_ops::i64_or <whitelist_validator>; using i64_xor_t = wasm_ops::i64_xor <whitelist_validator>; using i64_shl_t = wasm_ops::i64_shl <whitelist_validator>; using i64_shr_s_t = wasm_ops::i64_shr_s <whitelist_validator>; using i64_shr_u_t = wasm_ops::i64_shr_u <whitelist_validator>; using i64_rotl_t = wasm_ops::i64_rotl <whitelist_validator>; using i64_rotr_t = wasm_ops::i64_rotr <whitelist_validator>; using f32_eq_t = wasm_ops::f32_eq <whitelist_validator>; using f32_ne_t = wasm_ops::f32_ne <whitelist_validator>; using f32_lt_t = wasm_ops::f32_lt <whitelist_validator>; using f32_gt_t = wasm_ops::f32_gt <whitelist_validator>; using f32_le_t = wasm_ops::f32_le <whitelist_validator>; using f32_ge_t = wasm_ops::f32_ge <whitelist_validator>; using f64_eq_t = wasm_ops::f64_eq <whitelist_validator>; using f64_ne_t = wasm_ops::f64_ne <whitelist_validator>; using f64_lt_t = wasm_ops::f64_lt <whitelist_validator>; using f64_gt_t = wasm_ops::f64_gt <whitelist_validator>; using f64_le_t = wasm_ops::f64_le <whitelist_validator>; using f64_ge_t = wasm_ops::f64_ge <whitelist_validator>; using f32_abs_t = wasm_ops::f32_abs <whitelist_validator>; using f32_neg_t = wasm_ops::f32_neg <whitelist_validator>; using f32_ceil_t = wasm_ops::f32_ceil <whitelist_validator>; using f32_floor_t = wasm_ops::f32_floor <whitelist_validator>; using f32_trunc_t = wasm_ops::f32_trunc <whitelist_validator>; using f32_nearest_t = wasm_ops::f32_nearest <whitelist_validator>; using f32_sqrt_t = wasm_ops::f32_sqrt <whitelist_validator>; using f32_add_t = wasm_ops::f32_add <whitelist_validator>; using f32_sub_t = wasm_ops::f32_sub <whitelist_validator>; using f32_mul_t = wasm_ops::f32_mul <whitelist_validator>; using f32_div_t = wasm_ops::f32_div <whitelist_validator>; using f32_min_t = wasm_ops::f32_min <whitelist_validator>; using f32_max_t = wasm_ops::f32_max <whitelist_validator>; using f32_copysign_t = wasm_ops::f32_copysign <whitelist_validator>; using f64_abs_t = wasm_ops::f64_abs <whitelist_validator>; using f64_neg_t = wasm_ops::f64_neg <whitelist_validator>; using f64_ceil_t = wasm_ops::f64_ceil <whitelist_validator>; using f64_floor_t = wasm_ops::f64_floor <whitelist_validator>; using f64_trunc_t = wasm_ops::f64_trunc <whitelist_validator>; using f64_nearest_t = wasm_ops::f64_nearest <whitelist_validator>; using f64_sqrt_t = wasm_ops::f64_sqrt <whitelist_validator>; using f64_add_t = wasm_ops::f64_add <whitelist_validator>; using f64_sub_t = wasm_ops::f64_sub <whitelist_validator>; using f64_mul_t = wasm_ops::f64_mul <whitelist_validator>; using f64_div_t = wasm_ops::f64_div <whitelist_validator>; using f64_min_t = wasm_ops::f64_min <whitelist_validator>; using f64_max_t = wasm_ops::f64_max <whitelist_validator>; using f64_copysign_t = wasm_ops::f64_copysign <whitelist_validator>; using i32_trunc_s_f32_t = wasm_ops::i32_trunc_s_f32 <whitelist_validator>; using i32_trunc_u_f32_t = wasm_ops::i32_trunc_u_f32 <whitelist_validator>; using i32_trunc_s_f64_t = wasm_ops::i32_trunc_s_f64 <whitelist_validator>; using i32_trunc_u_f64_t = wasm_ops::i32_trunc_u_f64 <whitelist_validator>; using i64_trunc_s_f32_t = wasm_ops::i64_trunc_s_f32 <whitelist_validator>; using i64_trunc_u_f32_t = wasm_ops::i64_trunc_u_f32 <whitelist_validator>; using i64_trunc_s_f64_t = wasm_ops::i64_trunc_s_f64 <whitelist_validator>; using i64_trunc_u_f64_t = wasm_ops::i64_trunc_u_f64 <whitelist_validator>; using f32_convert_s_i32_t = wasm_ops::f32_convert_s_i32 <whitelist_validator>; using f32_convert_u_i32_t = wasm_ops::f32_convert_u_i32 <whitelist_validator>; using f32_convert_s_i64_t = wasm_ops::f32_convert_s_i64 <whitelist_validator>; using f32_convert_u_i64_t = wasm_ops::f32_convert_u_i64 <whitelist_validator>; using f32_demote_f64_t = wasm_ops::f32_demote_f64 <whitelist_validator>; using f64_convert_s_i32_t = wasm_ops::f64_convert_s_i32 <whitelist_validator>; using f64_convert_u_i32_t = wasm_ops::f64_convert_u_i32 <whitelist_validator>; using f64_convert_s_i64_t = wasm_ops::f64_convert_s_i64 <whitelist_validator>; using f64_convert_u_i64_t = wasm_ops::f64_convert_u_i64 <whitelist_validator>; using f64_promote_f32_t = wasm_ops::f64_promote_f32 <whitelist_validator>; using i32_wrap_i64_t = wasm_ops::i32_wrap_i64 <whitelist_validator>; using i64_extend_s_i32_t = wasm_ops::i64_extend_s_i32 <whitelist_validator>; using i64_extend_u_i32_t = wasm_ops::i64_extend_u_i32 <whitelist_validator>; // TODO, make sure these are just pointer reinterprets using i32_reinterpret_f32_t = wasm_ops::i32_reinterpret_f32 <whitelist_validator>; using f32_reinterpret_i32_t = wasm_ops::f32_reinterpret_i32 <whitelist_validator>; using i64_reinterpret_f64_t = wasm_ops::i64_reinterpret_f64 <whitelist_validator>; using f64_reinterpret_i64_t = wasm_ops::f64_reinterpret_i64 <whitelist_validator>; }; // op_constrainers template <typename ... Visitors> struct constraints_validators { static void validate( const IR::Module& m ) { for ( auto validator : { Visitors::validate... } ) validator( m ); } }; // inherit from this class and define your own validators class wasm_binary_validation { using standard_module_constraints_validators = constraints_validators< memories_validation_visitor, data_segments_validation_visitor, tables_validation_visitor, globals_validation_visitor, maximum_function_stack_visitor, ensure_apply_exported_visitor>; public: wasm_binary_validation( const myeosio::chain::controller& control, IR::Module& mod ) : _module( &mod ) { // initialize validators here nested_validator::init(!control.is_producing_block()); } void validate() { _module_validators.validate( *_module ); for ( auto& fd : _module->functions.defs ) { wasm_ops::MYEOSIO_OperatorDecoderStream<op_constrainers> decoder(fd.code); while ( decoder ) { wasm_ops::instruction_stream new_code(0); auto op = decoder.decodeOp(); op->visit( { _module, &new_code, &fd, decoder.index() } ); } } } private: IR::Module* _module; static standard_module_constraints_validators _module_validators; }; }}} // namespace wasm_constraints, chain, myeosio
[ "jrlees@LAPTOP-D4RPAA0F.localdomain" ]
jrlees@LAPTOP-D4RPAA0F.localdomain
eed28dfb45bffb4afcebf6f4a6f4245f0f6e6254
35be95e5e4ef306a1203a173bed12599f62db7b6
/SlimDXc_Jun2010(VC++2008)/source/direct2d/BezierSegment.h
42ec3feb5d7e45e0e8a7a70fbe81a6c51fd0db04
[ "MIT" ]
permissive
Orz5566/RandomTest
dd0ec2eb7a0db3993409c2a647658a175a3b4027
2884f99d29dda603c646d464a60d7bce3346b74d
refs/heads/master
2021-09-06T01:10:29.460192
2018-02-01T06:56:53
2018-02-01T06:56:53
118,869,777
0
0
null
null
null
null
UTF-8
C++
false
false
1,351
h
/* * Copyright (c) 2007-2012 SlimDX Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once namespace SlimDX { namespace Direct2D { public value class BezierSegment { public: property System::Drawing::PointF Point1; property System::Drawing::PointF Point2; property System::Drawing::PointF Point3; }; } }
[ "32087037+Orz5566@users.noreply.github.com" ]
32087037+Orz5566@users.noreply.github.com
b8203a2010861162efd88185ac11d8806556caf9
1c9496682dfa28ecdc64aa90ea8b34e84e713a1e
/QueryView.cpp
ef9cc268fe8eca6cc0fad882029b9ea6e913b0c5
[]
no_license
radtek/DGG
8ffd2f0fd5dfdfda31bef71cc198e144946537ef
540c5d028cc7cfc906e6bb7e30f5cab2c5b6fe7d
refs/heads/master
2020-06-27T21:12:18.330306
2014-04-26T10:37:59
2014-04-26T10:37:59
200,050,945
1
0
null
2019-08-01T12:57:29
2019-08-01T12:57:28
null
GB18030
C++
false
false
26,533
cpp
// QueryView.cpp : implementation file // #include "stdafx.h" #include "hrs.h" #include "QueryView.h" #include "childfrm.h" #include "mainfrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CQueryView IMPLEMENT_DYNCREATE(CQueryView, CScrollView) CQueryView::CQueryView() { Init(); } CQueryView::~CQueryView() { } BEGIN_MESSAGE_MAP(CQueryView, CScrollView) //{{AFX_MSG_MAP(CQueryView) ON_COMMAND(AFX_ID_PREVIEW_PRINT, OnIdPreviewPrint) ON_WM_CONTEXTMENU() ON_UPDATE_COMMAND_UI(ID_FILE_PRINT_DIRECT, OnUpdateMenuPrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, OnFilePrintDirect) ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CQueryView drawing void CQueryView::OnInitialUpdate() { CScrollView::OnInitialUpdate(); CSize sizeTotal; // TODO: calculate the total size of this view sizeTotal.cx = sizeTotal.cy = 100; //AfxMessageBox("aaa"); SetScrollSizes(MM_TEXT, sizeTotal); } void CQueryView::OnDraw(CDC* pDC) { if(pDC->IsPrinting()) { DrawPrinter(pDC); } else { DrawScreen(pDC); } } ///////////////////////////////////////////////////////////////////////////// // CQueryView diagnostics #ifdef _DEBUG void CQueryView::AssertValid() const { CScrollView::AssertValid(); } void CQueryView::Dump(CDumpContext& dc) const { CScrollView::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CQueryView message handlers void CQueryView::QueryRecordset() { CString sql = m_sQuerySql + m_sFilter; TRACE("sql is: %s\n", sql); if(sql.GetLength()<=0) return; m_wrs.ExecuteSql(sql); QueryFootRecordSet(); } void CQueryView::Init() { m_nRecordCnt = 0; m_cxHeader = 80; m_cyHeader = 30; m_cyCell = 30; m_cxCell = 80; m_sQuerySql = ""; m_sFilter = ""; m_sFootSql = ""; m_sFootFilter = ""; m_nTopMargin = 100; m_nTopLineGap = 20; m_nLeftMargin = 50; m_nRightMargin = 50; m_nBottomMargin = 100; m_nBottomLineGap = 20; m_sTitle = "信息查询"; m_nPageHeigh = 0; m_viewSize = CSize(100,100); m_ftTitle.CreatePointFont(200, "黑体"); m_ftHeader.CreatePointFont(100, "黑体"); m_ftHeaderNote.CreatePointFont(80, "黑体"); m_ftRecord.CreatePointFont(80, "黑体"); m_ftFooter.CreatePointFont(50, "黑体"); m_ftFooterNote.CreatePointFont(50, "黑体"); } void CQueryView::OnIdPreviewPrint() { // TODO: Add your command handler code here //CPreviewView pv; //CScrollView::OnPrint(); } void CQueryView::OnContextMenu(CWnd* pWnd, CPoint point) { // TODO: Add your message handler code here //AfxMessageBox("right clicked"); CMenu menu, *subMenu; menu.LoadMenu(IDR_MENU_PRINT); subMenu = menu.GetSubMenu(0); subMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON, point.x, point.y, this); } void CQueryView::OnUpdateMenuPrint(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here } void CQueryView::OnFilePrintDirect() { // TODO: Add your command handler code here OnFilePrint(); //AfxGetApp()->m_hMainSendMessage(WM_COMMAND, ID_FILE_PRINT_SETUP); } BOOL CQueryView::OnPreparePrinting(CPrintInfo* pInfo) { // TODO: call DoPreparePrinting to invoke the Print dialog box //AfxGetApp() //pInfo->m_pPD->UpdateData(false); if(pInfo->m_pPD->DoModal() != IDOK) return FALSE; SetPrintPara(pInfo); //pInfo->m_pPD->UpdateData(true); return DoPreparePrinting(pInfo); // CScrollView::OnPreparePrinting(pInfo); } void CQueryView::SetPrintPara(CPrintInfo *pInfo) { //CFont *pOldFnt; //int nTitleHeigh, nHeaderHeigh, nFooterHeigh, nRecordHeigh; CDC pdc; pdc.Attach(pInfo->m_pPD->m_pd.hDC); pdc.SetMapMode(MM_LOENGLISH); /*TEXTMETRIC tmHeader, tmFooter, tmTitle, tmRecord; pOldFnt = pdc.SelectObject(&m_ftTitle); pdc.GetTextMetrics(&tmTitle); nTitleHeigh = tmTitle.tmHeight + tmTitle.tmExternalLeading; pdc.SelectObject(&m_ftHeader); pdc.GetTextMetrics(&tmHeader); nHeaderHeigh = tmHeader.tmHeight + tmHeader.tmExternalLeading; pdc.SelectObject(&m_ftFooter); pdc.GetTextMetrics(&tmFooter); nFooterHeigh = tmFooter.tmHeight + tmFooter.tmExternalLeading; pdc.SelectObject(&m_ftRecord); pdc.GetTextMetrics(&tmRecord); nRecordHeigh = tmRecord.tmHeight + tmRecord.tmExternalLeading; pdc.SelectObject(pOldFnt); int totHeight = nTitleHeigh + nHeaderHeigh + nRecordHeigh * m_nRecordCnt + nFooterHeigh;*/ int cxPrint, cyPrint; cxPrint = pdc.GetDeviceCaps(HORZRES); cyPrint = pdc.GetDeviceCaps(VERTRES); /*int cxlog, cylog; cxlog = pdc.GetDeviceCaps(LOGPIXELSX); cylog = pdc.GetDeviceCaps(LOGPIXELSY); int InchPagey = cyPrint/cylog; int InchPagex = cxPrint/cxlog;*/ CSize pageSize=CSize(cxPrint, cyPrint); pdc.DPtoLP(&pageSize); m_nPageHeigh = pageSize.cy; int pages = m_viewSize.cy/m_nPageHeigh; pInfo->m_nCurPage = 1; pInfo->m_pPD->m_pd.nFromPage = 1; pInfo->m_pPD->m_pd.nToPage = pages; pInfo->m_pPD->m_pd.nMinPage = 1; pInfo->m_pPD->m_pd.nMaxPage = pages; pdc.Detach(); } void CQueryView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo) { // TODO: Add your specialized code here and/or call the base class CScrollView::OnBeginPrinting(pDC, pInfo); } void CQueryView::QueryFootRecordSet() { CString sql; if(m_sFootSql.GetLength()<=0) return; sql = m_sFootSql + m_sFootFilter; TRACE("sql is: %s\n", sql); if(sql.GetLength()<=0) return; m_wfootRs.ExecuteSql(sql); } void CQueryView::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo) { // TODO: Add your specialized code here and/or call the base class pDC->SetMapMode(MM_LOENGLISH); pDC->SetViewportOrg(0, 0); if(pDC->IsPrinting()) { int y = (pInfo->m_nCurPage-1)*m_nPageHeigh; CPoint p = CPoint(0, y); pDC->LPtoDP(&p); pDC->SetViewportOrg(0, p.y); pInfo->m_rectDraw.SetRect(0, 0, pDC->GetDeviceCaps(HORZRES), pDC->GetDeviceCaps(VERTRES)); pDC->DPtoLP(&pInfo->m_rectDraw); pInfo->m_rectDraw.bottom += m_nBottomMargin; return; } CScrollView::OnPrepareDC(pDC, pInfo); } void CQueryView::DrawScreen(CDC *pDC) { CDocument* pDoc = GetDocument(); pDC->SetMapMode(MM_LOENGLISH); if(m_wrs.IsOpen()) { m_viewSize = CSize(m_nLeftMargin+m_nRightMargin + m_wrs.GetColumnCount()*m_cxCell, m_nTopMargin + m_nTopLineGap + m_nBottomMargin+m_wrs.GetRecordCount()*m_cyCell+m_cyHeader+m_nBottomLineGap); //pDC->SetWindowExt(m_viewSize.cx, -m_viewSize.cy); SetScrollSizes(MM_LOENGLISH, m_viewSize); DrawTitle(pDC); DrawBody(pDC); DrawFooter(pDC); } } /* ------------------------------- | | |m_nTopMargin | --------------------------- | m_nTopLineGap ---------------------- | |m_cyHeader ------------------ | | |Records . . . ------------------- | m_nBottomLineGap ------------------- | | |m_nBottomMargin ------------------------------------ int scrollpos; scrollpos=this->GetScrollPos(SB_VERT); CString tt; CRecordset *p = NULL; CRect clientrc; GetClientRect(&clientrc); if(m_wrs.IsOpen()) { long i; m_viewSize.cx = (nColNum+1)*m_cxHeader+m_nLeftMargin +m_nRightMargin; m_viewSize.cy = (m_wrs.GetRecordCount())*m_cyCell+m_cyHeader+m_nTopMargin+m_nBottomMargin; CSize page = CSize(0,10 * m_cyCell); CSize line = CSize(0, 1 * m_cyCell); this->SetScrollSizes(MM_TEXT,m_viewSize, page, line); CRect ttr(m_nLeftMargin, m_nTopLineGap- 80, (nColNum+1)*m_cxHeader+m_nLeftMargin, m_nTopLineGap-30); pDC->SelectObject(&m_ftTitle); pDC->SetTextColor(RGB(0,0,0)); pDC->DrawText(m_sTitle, &ttr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); CRect dtr(m_nLeftMargin, m_nTopLineGap- 30, m_nLeftMargin + 150, m_nTopLineGap); CFont datefont; datefont.CreatePointFont(100, "黑体"); pDC->SelectObject(&datefont); pDC->SetTextColor(RGB(0,0,0)); CTime ct = CTime::GetCurrentTime(); CString tstr; tstr.Format("日期: %d年%d月%d日", ct.GetYear(), ct.GetMonth(), ct.GetDay()); pDC->DrawText(tstr, &dtr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); CRect usr((nColNum+1)*m_cxHeader+m_nLeftMargin - 200, m_nTopLineGap- 30, (nColNum+1)*m_cxHeader+m_nLeftMargin, m_nTopLineGap); CFont userfont; userfont.CreatePointFont(100, "黑体"); pDC->SelectObject(&userfont); pDC->SetTextColor(RGB(0,0,0)); CMainFrame *pM = (CMainFrame*)AfxGetApp()->GetMainWnd(); tstr.Format("操作员: %s", pM->m_cLoginUser.m_sUserName); pDC->DrawText(tstr, &usr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); CPoint frm(m_nLeftMargin, m_nTopLineGap); CPoint to(m_viewSize.cx - m_nRightMargin,m_nTopLineGap); pDC->MoveTo(frm); pDC->LineTo(to); frm = CPoint(m_nLeftMargin, m_nTopMargin); to = CPoint(m_viewSize.cx - m_nRightMargin,m_nTopMargin); pDC->MoveTo(frm); pDC->LineTo(to); frm = CPoint(m_nLeftMargin, m_nTopMargin+m_cyHeader); to = CPoint(m_viewSize.cx - m_nRightMargin,m_nTopMargin+m_cyHeader); pDC->MoveTo(frm); pDC->LineTo(to); CBrush brush; brush.CreateStockObject(LTGRAY_BRUSH); pDC->SelectObject(&brush); CODBCFieldInfo cfi; pDC->SetBkMode(TRANSPARENT); CString colname; pDC->SelectObject(&m_ftHeader); pDC->SetTextColor(RGB(0,0,0)); for(i = 0;i<=nColNum; i++) { pDC->MoveTo(m_nLeftMargin+m_cxHeader*i, m_nTopMargin); pDC->LineTo(m_nLeftMargin+m_cxHeader*i, m_viewSize.cy - m_nBottomMargin); CRect rc(m_nLeftMargin+m_cxHeader*i+1, m_nTopMargin+1, m_nLeftMargin+m_cxHeader*i+m_cxHeader, m_nTopMargin+m_cyHeader); pDC->FillRect(rc,&brush); //pDC->Draw3dRect(&rc, RGB(255, 255, 255), RGB(128,128,128)); if(i==0) { colname = "行号"; } else { p->GetODBCFieldInfo(i-1, cfi); colname = cfi.m_strName; } pDC->DrawText(colname, &rc, DT_SINGLELINE|DT_CENTER|DT_VCENTER); } pDC->MoveTo(m_nLeftMargin+m_cxHeader*(nColNum+1), m_nTopMargin); pDC->LineTo(m_nLeftMargin+m_cxHeader*(nColNum+1), m_viewSize.cy - m_nBottomMargin); CPoint lefttop(m_nLeftMargin, m_nTopMargin + m_cyHeader), bottomright; CPoint lt = lefttop; pDC->SelectObject(&m_ftRecord); pDC->SetTextColor(RGB(0,0,255)); i = ((scrollpos - lt.y) / m_cyCell)>0 ? ((scrollpos - lt.y) / m_cyCell): 0 ; nRecordCnt = i+clientrc.Height() / m_cyCell + 1; TRACE("i = %d, cnt = %d\n", i, nRecordCnt); for(int k=0; k<i; k++) p->MoveNext(); for(;i<nRecordCnt && !p->IsEOF(); i++) { lefttop.y = lt.y + m_cyCell*(i+1); bottomright = lefttop; bottomright.x = m_viewSize.cx - m_nRightMargin; pDC->MoveTo(lefttop); pDC->LineTo(bottomright); CRect tr; CDBVariant fdv; CString fv; for(int j=0;j<=nColNum; j++) { tr.SetRect(m_nLeftMargin+m_cxCell * j, lefttop.y - m_cyCell, m_nLeftMargin+m_cxCell*(j+1), lefttop.y); if(j == 0) { fv.Format("%ld", i+1); } else { //p->GetFieldValue(j-1,fdv); CODBCFieldInfo ff; p->GetODBCFieldInfo(j-1, ff); switch(ff.m_nSQLType) { case 11: p->GetFieldValue(j-1,fdv); fv.Format("%d年%d月%d日", fdv.m_pdate->year, fdv.m_pdate->month, fdv.m_pdate->day); break; default: p->GetFieldValue(j-1,fv); break; } } pDC->DrawText(fv, &tr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); } p->MoveNext(); } p->Close(); }*/ void CQueryView::DrawPrinter(CDC *pDC) { CDocument* pDoc = GetDocument(); /*int cxPrint, cyPrint; cxPrint = pDC->GetDeviceCaps(HORZRES); cyPrint = pDC->GetDeviceCaps(VERTRES); int cxlog, cylog; cxlog = pDC->GetDeviceCaps(LOGPIXELSX); cylog = pDC->GetDeviceCaps(LOGPIXELSY); pDC->SetMapMode(MM_ANISOTROPIC); pDC->SetWindowExt(m_viewSize); pDC->SetViewportExt(cxPrint, cyPrint);*/ pDC->SetMapMode(MM_LOENGLISH); if(m_wrs.IsOpen()) { DrawTitle(pDC); DrawBody(pDC); DrawFooter(pDC); } } /* CDocument* pDoc = GetDocument(); this->QueryRecordset(); CString tt; CRecordset *p = NULL;//&m_rs; int nColNum; if(p->IsOpen()) { nColNum = p->GetODBCFieldCount(); long nRecordCnt = m_nRecordCnt, i; m_viewSize.cx = (nColNum+1)*m_cxHeader+m_nLeftMargin +m_nRightMargin; m_viewSize.cy = (nRecordCnt)*m_cyCell+m_cyHeader+m_nTopMargin+m_nBottomMargin; CSize page = CSize(0,10 * m_cyCell); CSize line = CSize(0, 1 * m_cyCell); this->SetScrollSizes(MM_TEXT,m_viewSize, page, line); if(m_bIsFstPage) { CRect ttr(m_nLeftMargin, m_nTopLineGap- 80, (nColNum+1)*m_cxHeader+m_nLeftMargin, m_nTopLineGap-30); pDC->SelectObject(&m_ftTitle); pDC->SetTextColor(RGB(0,0,0)); pDC->DrawText(m_sTitle, &ttr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); CRect dtr(m_nLeftMargin, m_nTopLineGap- 30, m_nLeftMargin + 150, m_nTopLineGap); CFont datefont; datefont.CreatePointFont(100, "黑体"); pDC->SelectObject(&datefont); pDC->SetTextColor(RGB(0,0,0)); CTime ct = CTime::GetCurrentTime(); CString tstr; tstr.Format("日期: %d年%d月%d日", ct.GetYear(), ct.GetMonth(), ct.GetDay()); pDC->DrawText(tstr, &dtr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); CRect usr((nColNum+1)*m_cxHeader+m_nLeftMargin - 200, m_nTopLineGap- 30, (nColNum+1)*m_cxHeader+m_nLeftMargin, m_nTopLineGap); CFont userfont; userfont.CreatePointFont(100, "黑体"); pDC->SelectObject(&userfont); pDC->SetTextColor(RGB(0,0,0)); CMainFrame *pM = (CMainFrame*)AfxGetApp()->GetMainWnd(); tstr.Format("操作员: %s", pM->m_cLoginUser.m_sUserName); pDC->DrawText(tstr, &usr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); } CPoint frm(m_nLeftMargin, m_nTopLineGap); CPoint to(m_viewSize.cx - m_nRightMargin,m_nTopLineGap); pDC->MoveTo(frm); pDC->LineTo(to); frm = CPoint(m_nLeftMargin, m_nTopMargin); to = CPoint(m_viewSize.cx - m_nRightMargin,m_nTopMargin); pDC->MoveTo(frm); pDC->LineTo(to); frm = CPoint(m_nLeftMargin, m_nTopMargin+m_cyHeader); to = CPoint(m_viewSize.cx - m_nRightMargin,m_nTopMargin+m_cyHeader); pDC->MoveTo(frm); pDC->LineTo(to); CBrush brush; brush.CreateStockObject(LTGRAY_BRUSH); pDC->SelectObject(&brush); CODBCFieldInfo cfi; pDC->SetBkMode(TRANSPARENT); CString colname; pDC->SelectObject(&m_ftHeader); pDC->SetTextColor(RGB(0,0,0)); for(i = 0;i<=nColNum; i++) { pDC->MoveTo(m_nLeftMargin+m_cxHeader*i, m_nTopMargin); pDC->LineTo(m_nLeftMargin+m_cxHeader*i, m_viewSize.cy - m_nBottomMargin); CRect rc(m_nLeftMargin+m_cxHeader*i+1, m_nTopMargin+1, m_nLeftMargin+m_cxHeader*i+m_cxHeader, m_nTopMargin+m_cyHeader); pDC->FillRect(rc,&brush); //pDC->Draw3dRect(&rc, RGB(255, 255, 255), RGB(128,128,128)); if(i==0) { colname = "行号"; } else { ASSERT(p->IsOpen()); p->GetODBCFieldInfo(i-1, cfi); colname = cfi.m_strName; } pDC->DrawText(colname, &rc, DT_SINGLELINE|DT_CENTER|DT_VCENTER); } pDC->MoveTo(m_nLeftMargin+m_cxHeader*(nColNum+1), m_nTopMargin); pDC->LineTo(m_nLeftMargin+m_cxHeader*(nColNum+1), m_viewSize.cy - m_nBottomMargin); CPoint lefttop(m_nLeftMargin, m_nTopMargin + m_cyHeader), bottomright; CPoint lt = lefttop; pDC->SelectObject(&m_ftRecord); pDC->SetTextColor(RGB(0,0,255)); i = (m_nCurPgeLastRecord - m_nRecordsPerPage) >= 0 ? (m_nCurPgeLastRecord - m_nRecordsPerPage) : 0; if(i==0) nRecordCnt = m_nCurPgeLastRecord; else nRecordCnt = i + m_nRecordsPerPage; ASSERT(nRecordCnt<m_nRecordCnt); for(int k=0; k<i; k++) { ASSERT(!p->IsEOF()); p->MoveNext(); } TRACE("from %d, to %d, tot %d, perpage %d", i, nRecordCnt, m_nRecordCnt, m_nRecordsPerPage); for(;i<nRecordCnt && !p->IsEOF(); i++) { lefttop.y = lt.y + m_cyCell*(i+1); bottomright = lefttop; bottomright.x = m_viewSize.cx - m_nRightMargin; pDC->MoveTo(lefttop); pDC->LineTo(bottomright); CRect tr; CDBVariant fdv; CString fv; for(int j=0;j<=nColNum; j++) { tr.SetRect(m_nLeftMargin+m_cxCell * j, lefttop.y - m_cyCell, m_nLeftMargin+m_cxCell*(j+1), lefttop.y); if(j == 0) { fv.Format("%ld", i+1); } else { //p->GetFieldValue(j-1,fdv); CODBCFieldInfo ff; p->GetODBCFieldInfo(j-1, ff); switch(ff.m_nSQLType) { case 11: p->GetFieldValue(j-1,fdv); fv.Format("%d年%d月%d日", fdv.m_pdate->year, fdv.m_pdate->month, fdv.m_pdate->day); break; default: p->GetFieldValue(j-1,fv); break; } } pDC->DrawText(fv, &tr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); } p->MoveNext(); } p->Close(); } this->QueryFootRecordSet(); if(m_footRs.IsOpen()) { p = &m_footRs; int nfootColNum = p->GetODBCFieldCount(); CString colname, colvalue, txt; CSize size; CODBCFieldInfo cfi; pDC->MoveTo(m_nLeftMargin, m_nRecordCnt*m_cyCell+m_cyHeader+m_nTopMargin+m_nBottomLineGap); pDC->LineTo(m_nLeftMargin+m_cxHeader*(nColNum+1), m_nRecordCnt*m_cyCell+m_cyHeader+m_nTopMargin+m_nBottomLineGap); for(int i = 0;i<nfootColNum; i++) { pDC->SelectObject(m_ftFooter); int det = (m_cxHeader*(nColNum+1))/nfootColNum; int left = m_nLeftMargin+(nfootColNum-i-1)*det; int top = m_nRecordCnt*m_cyCell+m_cyHeader+m_nTopMargin+m_nBottomLineGap; int right = m_nLeftMargin+m_cxHeader*nColNum; int bottom = (m_nRecordCnt+1)*m_cyCell+m_cyHeader+m_nTopMargin+m_nBottomLineGap; CRect rc(left,top,left+det,bottom); p->GetODBCFieldInfo(i, cfi); colname = cfi.m_strName; p->GetFieldValue(colname, colvalue); txt = colname+": "+colvalue; pDC->DrawText(txt, &rc, DT_SINGLELINE|DT_LEFT|DT_VCENTER); } }*/ void CQueryView::DrawTitle(CDC *pDC) { if(!pDC->IsPrinting() && m_wrs.IsOpen()) { pDC->SelectObject(&m_ftTitle); pDC->SetTextColor(RGB(0,0,0)); CRect tr = CRect(m_nLeftMargin, -(m_nTopMargin - m_cyHeader), m_viewSize.cx-m_nRightMargin, -m_nTopMargin); pDC->DrawText(m_sTitle, &tr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); CRect dtr(m_nLeftMargin, -m_nTopMargin, m_nLeftMargin + 2*m_cxCell, -(m_nTopMargin + m_nTopLineGap)); pDC->SelectObject(&m_ftHeaderNote); pDC->SetTextColor(RGB(0,0,0)); CTime ct = CTime::GetCurrentTime(); CString tstr; tstr.Format("日期: %d年%d月%d日", ct.GetYear(), ct.GetMonth(), ct.GetDay()); pDC->DrawText(tstr, &dtr, DT_SINGLELINE|DT_LEFT|DT_VCENTER); CRect usr((m_wrs.GetColumnCount()+1)*m_cxHeader+m_nLeftMargin - m_cxCell, -m_nTopMargin, (m_wrs.GetColumnCount()+1)*m_cxHeader+m_nLeftMargin, -(m_nTopMargin+m_nTopLineGap)); pDC->SelectObject(&m_ftHeaderNote); pDC->SetTextColor(RGB(0,0,0)); CMainFrame *pM = (CMainFrame*)AfxGetApp()->GetMainWnd(); tstr.Format("操作员: %s", pM->m_cLoginUser.m_sUserName); pDC->DrawText(tstr, &usr, DT_SINGLELINE|DT_RIGHT|DT_VCENTER); pDC->MoveTo(m_nLeftMargin, -(m_nTopMargin + m_nTopLineGap)); pDC->LineTo((m_wrs.GetColumnCount()+1)*m_cxCell+m_nLeftMargin, -(m_nTopMargin + m_nTopLineGap)); } else if(pDC->IsPrinting() && m_wrs.IsOpen()) { pDC->SelectObject(&m_ftTitle); pDC->SetTextColor(RGB(0,0,0)); CRect tr = CRect(m_nLeftMargin, -(m_nTopMargin - m_cyHeader), m_viewSize.cx-m_nRightMargin, -m_nTopMargin); //pDC->Rectangle(&tr); pDC->DrawText(m_sTitle, &tr, DT_SINGLELINE|DT_CENTER|DT_VCENTER); CRect dtr(m_nLeftMargin, -m_nTopMargin, m_nLeftMargin + 2*m_cxCell, -(m_nTopMargin + m_nTopLineGap)); pDC->SelectObject(&m_ftHeaderNote); pDC->SetTextColor(RGB(0,0,0)); CTime ct = CTime::GetCurrentTime(); CString tstr; tstr.Format("日期: %d年%d月%d日", ct.GetYear(), ct.GetMonth(), ct.GetDay()); pDC->DrawText(tstr, &dtr, DT_SINGLELINE|DT_LEFT|DT_VCENTER); CRect usr((m_wrs.GetColumnCount()+1)*m_cxHeader+m_nLeftMargin - 2*m_cxCell, -m_nTopMargin, (m_wrs.GetColumnCount()+1)*m_cxHeader+m_nLeftMargin, -(m_nTopMargin+m_nTopLineGap)); pDC->SelectObject(&m_ftHeaderNote); pDC->SetTextColor(RGB(0,0,0)); CMainFrame *pM = (CMainFrame*)AfxGetApp()->GetMainWnd(); tstr.Format("操作员: %s", pM->m_cLoginUser.m_sUserName); pDC->DrawText(tstr, &usr, DT_SINGLELINE|DT_RIGHT|DT_VCENTER); pDC->MoveTo(m_nLeftMargin, -(m_nTopMargin + m_nTopLineGap)); pDC->LineTo((m_wrs.GetColumnCount()+1)*m_cxCell+m_nLeftMargin, -(m_nTopMargin + m_nTopLineGap)); } } /*------------------------------- | | |m_nTopMargin | --------------------------- | m_nTopLineGap ---------------------- | |m_cyHeader ------------------ | | |Records . . . ------------------- | m_nBottomLineGap ------------------- | | |m_nBottomMargin ------------------------------------*/ void CQueryView::DrawBody(CDC *pDC) { if(!pDC->IsPrinting() && m_wrs.IsOpen()) { //Draw column title. CBrush brush; CODBCFieldInfo cfi; CString colname; CPoint lt = CPoint(m_nLeftMargin, -(m_nTopMargin + m_nTopLineGap)), pt; brush.CreateStockObject(LTGRAY_BRUSH); pDC->SelectObject(&brush); pDC->SetBkMode(TRANSPARENT); pDC->SelectObject(&m_ftHeader); pDC->SetTextColor(RGB(0,0,0)); pt = lt; for(int i = 0;i<=m_wrs.GetColumnCount(); i++) { pDC->MoveTo(pt); pDC->LineTo(pt.x, -(-pt.y + m_cyHeader + m_wrs.GetRecordCount()*m_cyCell)); CRect rc(pt.x+1, -(-pt.y+1), pt.x + m_cxHeader, -(-pt.y + m_cyHeader)); pDC->FillRect(rc,&brush); //pDC->Draw3dRect(&rc, RGB(255, 255, 255), RGB(128,128,128)); if(i==0) { colname = "行号"; } else { m_wrs.GetColHeader(i-1, colname); } pDC->DrawText(colname, &rc, DT_SINGLELINE|DT_CENTER|DT_VCENTER); pt.Offset(m_cxHeader,0); } pDC->MoveTo(lt.x + (m_wrs.GetColumnCount()+1)*m_cxHeader, lt.y); pDC->LineTo(lt.x + (m_wrs.GetColumnCount()+1)*m_cxHeader, -(-lt.y + m_cyHeader + m_wrs.GetRecordCount()*m_cyCell)); pt = lt; pDC->MoveTo(pt); pDC->LineTo(pt.x + (m_wrs.GetColumnCount()+1)*m_cxHeader, pt.y); pt.Offset(0, -m_cyHeader); pDC->MoveTo(pt); pDC->LineTo(pt.x + (m_wrs.GetColumnCount()+1)*m_cxHeader, pt.y); //Draw records. lt.Offset(0, -m_cyHeader); CRect valRt(lt.x, lt.y, lt.x + m_cxCell, -(-lt.y + m_cyCell)); CString value; int cnt = 0; pDC->SelectObject(&m_ftRecord); pDC->SetTextColor(RGB(0,0,255)); for( i=0;i<m_wrs.GetRecordCount();i++) { cnt++; for(int j=0;j<=m_wrs.GetColumnCount();j++) { if(j == 0) { value.Format("%d", cnt); } else { m_wrs.GetValue(i,j-1,value); } pDC->DrawText(value, &valRt, DT_SINGLELINE|DT_CENTER|DT_VCENTER); valRt.OffsetRect(m_cxCell, 0); } valRt.OffsetRect(-m_cxCell*(m_wrs.GetColumnCount() + 1), -m_cyCell); pDC->MoveTo(valRt.left, valRt.top); pDC->LineTo(valRt.left + m_cxCell*(m_wrs.GetColumnCount() + 1), valRt.top); } } else if(pDC->IsPrinting() && m_wrs.IsOpen()) { //Draw column title. CBrush brush; CODBCFieldInfo cfi; CString colname; CPoint lt = CPoint(m_nLeftMargin, -(m_nTopMargin + m_nTopLineGap)), pt; brush.CreateStockObject(LTGRAY_BRUSH); pDC->SelectObject(&brush); pDC->SetBkMode(TRANSPARENT); pDC->SelectObject(&m_ftHeader); pDC->SetTextColor(RGB(0,0,0)); pt = lt; for(int i = 0;i<=m_wrs.GetColumnCount(); i++) { pDC->MoveTo(pt); pDC->LineTo(pt.x, -(-pt.y + m_cyHeader)); CRect rc(pt.x+1, -(-pt.y+1), pt.x + m_cxHeader, -(-pt.y + m_cyHeader)); pDC->FillRect(rc,&brush); //pDC->Draw3dRect(&rc, RGB(255, 255, 255), RGB(128,128,128)); if(i==0) { colname = "行号"; } else { m_wrs.GetColHeader(i-1, colname); } pDC->DrawText(colname, &rc, DT_SINGLELINE|DT_CENTER|DT_VCENTER); pt.Offset(m_cxHeader,0); } pDC->MoveTo(lt.x + (m_wrs.GetColumnCount()+1)*m_cxHeader, lt.y); pDC->LineTo(lt.x + (m_wrs.GetColumnCount()+1)*m_cxHeader, -(-lt.y + m_cyHeader)); pt = lt; pDC->MoveTo(pt); pDC->LineTo(pt.x + (m_wrs.GetColumnCount()+1)*m_cxHeader, pt.y); pt.Offset(0, -m_cyHeader); pDC->MoveTo(pt); pDC->LineTo(pt.x + (m_wrs.GetColumnCount()+1)*m_cxHeader, pt.y); //Draw records. lt.Offset(0, -m_cyHeader); CRect valRt(lt.x, lt.y, lt.x + m_cxCell, -(-lt.y + m_cyCell)); CString value; int cnt = 0; pDC->SelectObject(&m_ftRecord); pDC->SetTextColor(RGB(0,0,255)); for( i=0;i<m_wrs.GetRecordCount();i++) { cnt++; for(int j=0;j<=m_wrs.GetColumnCount();j++) { if(j == 0) { value.Format("%d", cnt); } else { m_wrs.GetValue(i,j-1,value); } pDC->DrawText(value, &valRt, DT_SINGLELINE|DT_CENTER|DT_VCENTER); pDC->MoveTo(valRt.left, valRt.top); pDC->LineTo(valRt.left, valRt.top+(-m_cyCell)); valRt.OffsetRect(m_cxCell, 0); } pDC->MoveTo(valRt.left, valRt.top); pDC->LineTo(valRt.left, valRt.top+(-m_cyCell)); valRt.OffsetRect(-m_cxCell*(m_wrs.GetColumnCount() + 1), -m_cyCell); pDC->MoveTo(valRt.left, valRt.top); pDC->LineTo(valRt.left + m_cxCell*(m_wrs.GetColumnCount() + 1), valRt.top); } } } void CQueryView::DrawFooter(CDC *pDC) { if(!pDC->IsPrinting() && m_wrs.IsOpen()) { CPoint lt = CPoint(m_nLeftMargin, -(m_nTopMargin + m_nTopLineGap +m_cyHeader +m_cyCell *m_wrs.GetRecordCount() + m_nBottomLineGap)); pDC->MoveTo(lt); lt.Offset((m_wrs.GetColumnCount()+1)*m_cxCell, 0); pDC->LineTo(lt); int top = -(m_nTopMargin + m_nTopLineGap +m_cyHeader +m_cyCell *m_wrs.GetRecordCount() + m_nBottomLineGap); CRect valRt(m_nLeftMargin, top, m_cxCell * 2, top-m_cyCell); CString value; for(int j=0;j<m_wfootRs.GetColumnCount();j++) { m_wfootRs.GetColHeader(j, value); pDC->DrawText(value, &valRt, DT_SINGLELINE|DT_LEFT|DT_VCENTER); valRt.OffsetRect(m_cxCell, 0); m_wfootRs.GetValue(0,j,value); pDC->DrawText(value, &valRt, DT_SINGLELINE|DT_LEFT|DT_VCENTER); valRt.OffsetRect(m_cxCell, 0); } } else if(pDC->IsPrinting() && m_wrs.IsOpen()) { CPoint lt = CPoint(m_nLeftMargin, -(m_nTopMargin + m_nTopLineGap +m_cyHeader +m_cyCell *m_wrs.GetRecordCount() + m_nBottomLineGap)); pDC->MoveTo(lt); lt.Offset((m_wrs.GetColumnCount()+1)*m_cxCell, 0); pDC->LineTo(lt); int top = -(m_nTopMargin + m_nTopLineGap +m_cyHeader +m_cyCell *m_wrs.GetRecordCount() + m_nBottomLineGap); CRect valRt(m_nLeftMargin, top, m_cxCell * 2, top-m_cyCell); CString value; for(int j=0;j<m_wfootRs.GetColumnCount();j++) { m_wfootRs.GetColHeader(j, value); pDC->DrawText(value, &valRt, DT_SINGLELINE|DT_LEFT|DT_VCENTER); valRt.OffsetRect(m_cxCell, 0); m_wfootRs.GetValue(0,j,value); pDC->DrawText(value, &valRt, DT_SINGLELINE|DT_LEFT|DT_VCENTER); valRt.OffsetRect(m_cxCell, 0); } } } void CQueryView::OnFilePrintPreview() { // TODO: Add your command handler code here CView::OnFilePrintPreview(); }
[ "sam.ni@bleum.bleum.com" ]
sam.ni@bleum.bleum.com
4d4013f8a8624a2638c30c6445a7269f00ec34dc
3f78a9da3eecc6d8e401f1cce37e054a252930bc
/[Monitoring]Tool/ServerSet.cpp
ae32bd10f9e24a605e918872616c277211bfb14f
[]
no_license
apik1997/Mosiang-Online-Titan-DarkStroy-Azuga-Source-Code
9055aa319c5371afd1ebd504044160234ddbb418
74d6441754efb6da87855ee4916994adb7f838d5
refs/heads/master
2020-06-14T07:46:03.383719
2019-04-09T00:07:28
2019-04-09T00:07:28
194,951,315
0
0
null
2019-07-03T00:14:59
2019-07-03T00:14:59
null
WINDOWS-1252
C++
false
false
14,326
cpp
// ServerSet.cpp: implementation of the CServerSet class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ServerTool.h" #include "ServerSet.h" #include "..\[CC]Header\CommonGameFunc.h" #include "..\[CC]ServerModule\ServerListManager.h" #include "MHNetwork.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CServerSet::CServerSet() { memset( m_sMASIP, 0, 16 ); m_nMASPort = 0; memset( m_sServerInfoFileName, 0, 256 ); memset( m_sClientExeVersion, 0, 256 ); m_nServerSet = 0; memset( m_sServerSetName, 0, 256 ); m_dwTotalUserCount = 0; m_nUserLevel = eUSERLEVEL_SUPERUSER; strcpy( m_sUserLevel, "SuperUser" ); m_bInit = FALSE; m_dwMsgCheckTime = 0; m_dwMaxUser = 5000; } CServerSet::~CServerSet() { Release(); } BOOL CServerSet::Init(int ServerSetNum,char* setName,char* setFileName) { m_nServerSet = ServerSetNum; strcpy(m_sServerSetName,setName); return InitFromFile(setFileName); } BOOL CServerSet::InitFromFile(char* setFileName) { char temp[256]; strcpy( temp, GetDataDirectory() ); strcat( temp, setFileName ); SERVERLISTMGR->Load(temp); SERVERLISTMGR->SetPositionHead(); SERVERINFO* pInfo; CServer* pServer; while(pInfo = SERVERLISTMGR->GetNextServerInfo()) { pServer = new CServer(m_nServerSet,pInfo); if( pInfo->wServerKind == MONITOR_AGENT_SERVER ) { strcpy(m_sMASIP,pInfo->szIPForUser); m_nMASPort = pInfo->wPortForUser; m_vecMSServer.push_back( pServer ); } else if( pInfo->wServerKind == MONITOR_SERVER ) { m_vecMSServer.push_back( pServer ); } else { m_vecServer.push_back(pServer); } } m_bInit = TRUE; ReadClientExeVersion(); CreateUserCountFile(); SERVERLISTMGR->Clear(); return TRUE; } void CServerSet::Release() { memset( m_sMASIP, 0, 16 ); m_nMASPort = 0; memset( m_sServerInfoFileName, 0, 256 ); memset( m_sClientExeVersion, 0, 256 ); m_nServerSet = 0; memset( m_sServerSetName, 0, 256 ); m_dwTotalUserCount = 0; m_nUserLevel = eUSERLEVEL_SUPERUSER; strcpy( m_sUserLevel, "SuperUser" ); m_bInit = FALSE; m_dwMsgCheckTime = 0; m_dwMaxUser = 5000; vector<CServer*>::iterator iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) delete (*iter); m_vecServer.clear(); iter = m_vecMSServer.begin(); for(;iter != m_vecMSServer.end();++iter) delete (*iter); m_vecMSServer.clear(); } CServer* CServerSet::GetServer( WORD serverkind, WORD servernum ) { vector<CServer*>::iterator iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if( (*iter)->m_nServerKind == serverkind && (*iter)->m_nServerNum == servernum ) return (*iter); } return NULL; } CServer* CServerSet::GetServer( SERVERSTATE* pState ) { CServer* pServer = GetServer(pState->ServerType,pState->ServerNum); if(pServer == NULL) return NULL; // ASSERT(strcmp( pState->ServerIP, pServer->m_sIP ) == 0); // ASSERT(pState->ServerPort == pServer->m_nPort); return pServer; } void CServerSet::SetUserLevel( int userlevel ) { m_nUserLevel = userlevel; switch( userlevel ) { case eUSERLEVEL_GOD: strcpy( m_sUserLevel, "God"); break; case eUSERLEVEL_PROGRAMMER: strcpy( m_sUserLevel, "Programmer"); break; case eUSERLEVEL_DEVELOPER: strcpy( m_sUserLevel, "Developer"); break; case eUSERLEVEL_GM: strcpy( m_sUserLevel, "GM"); break; case eUSERLEVEL_SUPERUSER: strcpy( m_sUserLevel, "SuperUser"); break; case eUSERLEVEL_USER: strcpy( m_sUserLevel, "User"); break; case eUSERLEVEL_SUBUSER: strcpy( m_sUserLevel, "SubUser"); break; } } void CServerSet::ReadClientExeVersion() { char temp[256]; strcpy( temp, GetDataDirectory() ); strcat( temp, m_sServerSetName ); strcat( temp, "_ClientExeVersion.ver" ); FILE* fp = fopen( temp, "r" ); if( fp ) { fscanf( fp, "%s", temp ); fclose( fp ); strcpy( m_sClientExeVersion, temp ); return; } strcpy( m_sClientExeVersion, "None!!" ); } void CServerSet::WriteClientExeVersion( char* version ) { if( m_bInit ) { strcpy( m_sClientExeVersion, version ); char temp[256]; strcpy( temp, GetDataDirectory() ); strcat( temp, m_sServerSetName ); strcat( temp, "_ClientExeVersion.ver" ); FILE* fp = fopen( temp, "w" ); if( fp ) { fwrite( version, strlen(version), 1, fp ); fclose( fp ); } } } void CServerSet::CreateUserCountFile() { SYSTEMTIME time; GetLocalTime( &time ); char temp[256]; char filename[256]; strcpy( temp, GetUserCountDirectory() ); sprintf( filename, "%s_%04d%02d%02d_UserCount.txt", m_sServerSetName, time.wYear, time.wMonth, time.wDay ); strcat( temp, filename ); FILE* fp = fopen( temp, "a+" ); if( fp == NULL ) return; fprintf( fp, "Time\tTotal\tDist\tAgent\tMuim\t" ); // map vector<CServer*>::iterator iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != MAP_SERVER) continue; fprintf( fp, "%s\t", (*iter)->m_sName ); } fprintf( fp, "\n" ); fclose( fp ); } void CServerSet::WriteUserCount( SYSTEMTIME time ) { vector<CServer*>::iterator iter = m_vecServer.begin(); if( m_bInit ) if( IsThereOnServer() ) { char temp[256]; char filename[256]; strcpy( temp, GetUserCountDirectory() ); sprintf( filename, "%s_%04d%02d%02d_UserCount.txt", m_sServerSetName, time.wYear, time.wMonth, time.wDay ); strcat( temp, filename ); FILE* fp = fopen( temp, "a+" ); if( fp == NULL ) return; fprintf( fp, "%02d:%02d:%02d\t", time.wHour, time.wMinute, time.wSecond ); DWORD total = 0; DWORD dist = 0; DWORD agent = 0; DWORD murim = 0; // distribute iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != DISTRIBUTE_SERVER) continue; dist += (*iter)->m_dwUserCount; } total += dist; // agent iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != AGENT_SERVER) continue; agent += (*iter)->m_dwUserCount; } total += agent; // murim iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != MURIM_SERVER) continue; agent += (*iter)->m_dwUserCount; } fprintf( fp, "%d\t%d\t%d\t%d\t", total, dist, agent, murim ); // map iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != MAP_SERVER) continue; fprintf( fp, "%d\t", (*iter)->m_dwUserCount ); } fprintf( fp, "\n" ); fclose(fp); } } BOOL CServerSet::IsThereOnServer() { vector<CServer*>::iterator iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nState == eServerState_On) return TRUE; } return FALSE; } DWORD CServerSet::GetTotalUserCount() { DWORD total = 0; DWORD dist = 0; DWORD agent = 0; vector<CServer*>::iterator iter = m_vecServer.begin(); // distribute for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != DISTRIBUTE_SERVER) continue; dist += (*iter)->m_dwUserCount; } total += dist; // agent iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != AGENT_SERVER) continue; agent += (*iter)->m_dwUserCount; } total += agent; m_dwTotalUserCount = total; return m_dwTotalUserCount; } BOOL CServerSet::CheckDisconnectUser() { vector<CServer*>::iterator iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_bDisconnectUser) return FALSE; } return TRUE; } // operate fn---------------------------------------------------------------------------- void CServerSet::DoServerSetOn() { if( m_bInit ) { // on ¼ø¼­ : map, murim -> agent -> distribute vector<CServer*>::iterator iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != MAP_SERVER) continue; (*iter)->DoServerOn(); } iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != MURIM_SERVER) continue; (*iter)->DoServerOn(); } iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != AGENT_SERVER) continue; (*iter)->DoServerOn(); } iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != DISTRIBUTE_SERVER) continue; (*iter)->DoServerOn(); } } } void CServerSet::DoServerSetOff() { if( m_bInit ) { // on ¼ø¼­ : map, murim -> agent -> distribute vector<CServer*>::iterator iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != MAP_SERVER) continue; (*iter)->DoServerOff(); } iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != MURIM_SERVER) continue; (*iter)->DoServerOff(); } iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != AGENT_SERVER) continue; (*iter)->DoServerOff(); } iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if((*iter)->m_nServerKind != DISTRIBUTE_SERVER) continue; (*iter)->DoServerOff(); } } } void CServerSet::DoServerSetRefresh() { if( m_bInit ) { MSGROOT msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_MAPSERVERSTATE_SYN; NETWORK->Send( m_nServerSet, &msg, sizeof(msg) ); } } void CServerSet::DoServerOn( WORD serverkind, WORD servernum ) { if( m_bInit ) { CServer* pServer = GetServer(serverkind,servernum); if(pServer) pServer->DoServerOn(); } } void CServerSet::DoServerOff( WORD serverkind, WORD servernum ) { if( m_bInit ) { CServer* pServer = GetServer(serverkind,servernum); if(pServer) pServer->DoServerOff(); } } void CServerSet::DoQueryClientExeVersion() { if( m_bInit ) { MSGROOT msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_QUERY_VERSION_SYN; NETWORK->Send( m_nServerSet, (MSGROOT*)&msg, sizeof(msg) ); } } void CServerSet::DoChangeClientExeVersion( char* version ) { if( m_bInit ) { MSGNOTICE msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_CHANGE_VERSION_SYN; strcpy( msg.Msg, version ); NETWORK->Send( m_nServerSet, (MSGROOT*)&msg, sizeof(msg) ); } } void CServerSet::DoQueryMaxUser() { if( m_bInit ) { MSGROOT msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_QUERY_MAXUSER_SYN; NETWORK->Send( m_nServerSet, (MSGROOT*)&msg, sizeof(msg) ); } } void CServerSet::DoChangeMaxUser( DWORD maxuser ) { if( m_bInit ) { MSG_DWORD msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_CHANGE_MAXUSER_SYN; msg.dwData = maxuser; NETWORK->Send( m_nServerSet, (MSGROOT*)&msg, sizeof(msg) ); } } void CServerSet::DoQueryUserLevel() { if( m_bInit ) { MSG_DWORD msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_CHANGE_USERLEVEL_SYN; msg.dwData = 0; NETWORK->Send( m_nServerSet, (MSGROOT*)&msg, sizeof(msg) ); } } void CServerSet::DoChangeUserLevel( int userlevel ) { if( m_bInit ) { MSG_DWORD msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_CHANGE_USERLEVEL_SYN; msg.dwData = userlevel; NETWORK->Send( m_nServerSet, (MSGROOT*)&msg, sizeof(msg) ); } } void CServerSet::DoQueryUserCount() { if( m_bInit ) { MSGROOT msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_QUERYUSERCOUNT_SYN; NETWORK->Send( m_nServerSet, &msg, sizeof(msg) ); } } void CServerSet::DoSendMessage( char* pmsg ) { if( m_bInit ) { MSGNOTICE msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_NOTICESEND_SYN; strcpy( msg.Msg, pmsg ); NETWORK->Send( m_nServerSet, (MSGROOT*)&msg, sizeof(msg) ); } } void CServerSet::DoAutoPatch() { if( m_bInit ) { MSGROOT msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_EXECUTE_AUTOPATCH_SYN; NETWORK->Send( m_nServerSet, &msg, sizeof(msg) ); } } void CServerSet::DoAssertMsgBox( BOOL bState ) { if( m_bInit ) { MSG_DWORD msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_ASSERTMSGBOX_SYN; msg.dwData = (DWORD)bState; NETWORK->Send( m_nServerSet, &msg, sizeof(msg) ); } } void CServerSet::DoAllUserDisconnect() { if( m_bInit ) { MSGROOT msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_DISCONNECT_ALLUSER_SYN; NETWORK->Send( m_nServerSet, &msg, sizeof(msg) ); } } void CServerSet::DoServerSetOffAfterUserDiscon() { if( CheckDisconnectUser() ) DoServerSetOff(); } void CServerSet::DoMSStateAll() { if( m_bInit ) { MSGROOT msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_MSSTATEALL_SYN; NETWORK->Send( m_nServerSet, &msg, sizeof(msg) ); } } void CServerSet::DoQueryChannelInfo() { if( m_bInit ) { MSGROOT msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_QUERY_CHANNELINFO_SYN; NETWORK->Send( m_nServerSet, &msg, sizeof(msg) ); } } CServer* CServerSet::GetMSServer( MSSTATE* pState ) { vector<CServer*>::iterator iter = m_vecMSServer.begin(); for(;iter != m_vecMSServer.end();++iter) { if( ( (*iter)->m_nPort == pState->wServerPort ) && ( strcmp((*iter)->m_sIP, pState->sServerIP) == 0 ) ) return (*iter); } return NULL; } CServer* CServerSet::GetServer( char* pServerIp, WORD wServerPort ) { vector<CServer*>::iterator iter = m_vecServer.begin(); for(;iter != m_vecServer.end();++iter) { if( ( (*iter)->m_nPort == wServerPort ) && ( strcmp((*iter)->m_sIP, pServerIp) == 0 ) ) return (*iter); } return NULL; } void CServerSet::ClearMSStateAll() { vector<CServer*>::iterator iter = m_vecMSServer.begin(); for(;iter != m_vecMSServer.end();++iter) { (*iter)->SetState( eServerState_Disconnect ); } } void CServerSet::DoQueryAutoPatchVersion() { if( m_bInit ) { MSGROOT msg; msg.Category = MP_MORNITORTOOL; msg.Protocol = MP_MORNITORTOOL_QUERY_AUTOPATCHVERSION_SYN; NETWORK->Send( m_nServerSet, &msg, sizeof(msg) ); } }
[ "lixeon.lij@gmail.com" ]
lixeon.lij@gmail.com
e5ac64326482dffe164fd6b0b7d70b1180c953d9
6958f8ae5f2f5bfc0573e3785783d4d22e46c649
/src/gl/Mesh.h
464f28150086c12107b59b7d69908cb709884007
[]
no_license
Twometer/chess-3d
a039315daefcb305b2600d03350eef797f10146a
c023705741144087714c5779d821e32d104ee083
refs/heads/master
2020-10-01T21:22:37.065507
2020-01-16T09:24:48
2020-01-16T09:24:48
227,627,382
0
0
null
null
null
null
UTF-8
C++
false
false
575
h
// // Created by Twometer on 15/12/2019. // #ifndef CHESS_3D_MESH_H #define CHESS_3D_MESH_H #include <glad/glad.h> #include <vector> #include <glm/vec3.hpp> #include "Model.h" class Model; class Mesh { private: std::vector<GLfloat> vertices; std::vector<GLfloat> normals; public: void AddVertex(glm::vec3 vertex); std::vector<GLfloat> &GetVertices() { return vertices; } void AddNormal(glm::vec3 normal); std::vector<GLfloat> &GetNormals() { return normals; } Model *CreateModel(); }; #endif //CHESS_3D_MESH_H
[ "twometer@outlook.de" ]
twometer@outlook.de
30a63ed6528bf19ea7b414e869c431cb5492fe7f
8ad612e828151317b16d311ee51563738f0ce418
/src/messagehandlers/simplehandler/SimpleTimeoutHandler.cc
7dfe3bc52382a28de8b3791dd66a079b6fcfbd89
[ "MIT" ]
permissive
deng10622/BSF
37e3da48a1533a50683a042c4052fd4620f491d1
89bccd20359ec794cd19a1211d5e52c751e7405c
refs/heads/master
2022-06-27T15:51:08.188562
2019-10-29T07:16:09
2019-10-29T07:16:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,387
cc
/* * SimpleTimeoutHandler.cc * * Created on: Mar 20, 2017 * Author: xtikka */ #include "SimpleTimeoutHandler.h" #include "../../messages/basicmessages/NetworkTimeoutMsg_m.h" /** * Timeout message handler for simplebot */ SimpleTimeoutHandler::SimpleTimeoutHandler(NodeBase* owner) { node = static_cast<SimpleBot*>(owner); } /** * Destructor */ SimpleTimeoutHandler::~SimpleTimeoutHandler() { } /** * Handler for simplebot timeout messages */ void SimpleTimeoutHandler::handleMessage(BasicNetworkMsg* msg) { if (msg->getType() == TIMEOUT) { NetworkTimeoutMsg* timeout = static_cast<NetworkTimeoutMsg*>(msg); if (timeout->getTimeouttype() == PING) { handlePingTimeout(timeout); } else if (timeout->getTimeouttype() == PONG) { //DO nothing } else if (timeout->getTimeouttype() == NL_REQ) { node->continueMM(); } else if (timeout->getTimeouttype() == NL_RESP) { //DO nothing } } } /** * Removes the timed out node from the neighborlist and * queries for new neighbors if the NL size is below NLMinThreshold */ void SimpleTimeoutHandler::handlePingTimeout(NetworkTimeoutMsg* timeout) { node->removeNeighbor(timeout->getSrcNode()); node->continueMM(); // if(node->NL->getSize() < node->NLMinThreshold){ // node->requestNeighbors(); // } }
[ "leonboeck@gmail.com" ]
leonboeck@gmail.com
845ec32ca5527f5e212cd3ea84783ccb70541bea
148cf64d12b1f7393109739eb51b6ab55360e67a
/DanChoys/Main.cpp
a8bd42e8caf882e67e0fdf8cc6ce1a3d73f19b7a
[]
no_license
DanChoys1/DanChoys
6db32c8f12c8fa96d872d27e8545c4d44afca8f0
ecb2d74aa2e125065f86dd68a7ac0fb54f0e9349
refs/heads/master
2023-05-27T08:00:00.197660
2021-06-08T20:29:03
2021-06-08T20:29:03
365,345,163
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
#include "ImageUploadForm.h" using namespace System; using namespace System::Windows::Forms; [STAThread] int main(void) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); Application::Run(gcnew Upload::ImageUploadForm()); return 0; }
[ "azarov.daniil@inbox.ru" ]
azarov.daniil@inbox.ru
7091df7d1fe797251c2fa9c00baba1d8d142f210
61456f36bc796cd8b4e5ebe489bc6e4c019363ad
/CompuCell3D/core/CompuCell3D/plugins/CellVelocity/CellVelocityPlugin.cpp
3db6ad7a3835d54be1e855e7686576eca18b47e4
[]
no_license
insafbk/CompuCell3D
f3556be82d10e71b6993a68e9a3fee552d10eb16
4c8b3b38f6fb9b96de7b7c13575ef0738f53dbc0
refs/heads/master
2023-01-03T08:55:37.934247
2020-08-22T18:13:13
2020-08-22T18:13:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,100
cpp
#include "CellVelocityPlugin.h" #include <CompuCell3D/Simulator.h> #include <CompuCell3D/Potts3D/Potts3D.h> #include <CompuCell3D/plugins/CenterOfMass/CenterOfMassPlugin.h> #include <Utils/cldeque.h> #include <CompuCell3D/plugins/CellVelocity/CellVelocityData.h> #include <XMLCereal/XMLPullParser.h> #include <XMLCereal/XMLSerializer.h> #include "CellVelocityDataAccessor.h" #include <iostream> using namespace std; namespace CompuCell3D { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CellVelocityPlugin::CellVelocityPlugin() : Plugin(),cellVelocityDataAccessorPtr(0) //, CellGGChangeWatcher() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CellVelocityPlugin::~CellVelocityPlugin() { if(cellVelocityDataAccessorPtr){ delete cellVelocityDataAccessorPtr; cellVelocityDataAccessorPtr=0; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CellVelocityPlugin::init(Simulator *_simulator){ Potts3D *potts = _simulator->getPotts(); simulator=_simulator; /* cellVelocityDataAccessorPtr=new CellVelocityDataAccessor<CellVelocityData>(cldequeCapacity,enoughDataThreshold) ; potts->getCellFactoryGroupPtr()->registerClass(cellVelocityDataAccessorPtr);*/ /* potts->registerCellGChangeWatcher(this); COMPlugin = (CenterOfMassPlugin *)Simulator::pluginManager.get("CenterOfMass"); watchingAllowed=false;*/ } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CellVelocityPlugin::extraInit(Simulator *_simulator){ Potts3D *potts = _simulator->getPotts(); cellVelocityDataAccessorPtr=new CellVelocityDataAccessor<CellVelocityData>(cldequeCapacity,enoughDataThreshold) ; potts->getCellFactoryGroupPtr()->registerClass(cellVelocityDataAccessorPtr); // potts->registerCellGChangeWatcher(this); // COMPlugin = (CenterOfMassPlugin *)Simulator::pluginManager.get("CenterOfMass"); //watchingAllowed=false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // void CellVelocityPlugin::field3DChange(const Point3D &pt, CellG *newCell, CellG *oldCell) { // // // vel = COM(t_n) - COM(t_{n-1}) // // cerr<<"********CELL VELOCITY FIELD CHANGE"<<endl; // // if(!simulator) // return; // // if(simulator->getStep() < 1) // return; // // if(oldCell){ // // if(oldCell->volume > 0 ){ // // cerr<<"cell velocity oldCell->volume="<<oldCell->volume<<endl; // // cerr<<" old x,y,z,CM="<<oldCell->xCM<<" "<<oldCell->yCM<<" "<<oldCell->zCM<<" "<<endl; // // cellVelocityDataAccessorPtr->get(oldCell->extraAttribPtr)->push_front ( // (oldCell->xCM)/(float)(oldCell->volume) -(oldCell->xCM+pt.x)/((float)oldCell->volume+1) , // (oldCell->yCM)/(float)(oldCell->volume) -(oldCell->yCM+pt.y)/((float)oldCell->volume+1) , // (oldCell->zCM)/(float)(oldCell->volume) -(oldCell->zCM+pt.z)/((float)oldCell->volume+1) // ); // } // /* cerr<<" old Cell velocity="<<cellVelocityDataAccessorPtr->get(oldCell->extraAttribPtr)->getInstantenousVelocity().X() // <<cellVelocityDataAccessorPtr->get(oldCell->extraAttribPtr)->getInstantenousVelocity().Y() // <<cellVelocityDataAccessorPtr->get(oldCell->extraAttribPtr)->getInstantenousVelocity().Z() // <<endl;*/ // } // // if(newCell){ // // /* cerr<<"cell velocity newCell->volume="<<newCell->volume<<endl; // cerr<<" new x,y,z,CM="<<newCell->xCM<<" "<<newCell->yCM<<" "<<newCell->zCM<<" "<<endl;*/ // if(newCell->volume > 1 ){ // cellVelocityDataAccessorPtr->get(newCell->extraAttribPtr)->push_front ( // (newCell->xCM)/(float)(newCell->volume) -(newCell->xCM-pt.x)/((float)newCell->volume-1) , // (newCell->yCM)/(float)(newCell->volume) -(newCell->yCM-pt.y)/((float)newCell->volume-1) , // (newCell->zCM)/(float)(newCell->volume) -(newCell->zCM-pt.z)/((float)newCell->volume-1) // ); // // } // // cerr<<" new Cell velocity="<<cellVelocityDataAccessorPtr->get(newCell->extraAttribPtr)->getInstantenousVelocity().X() // // <<cellVelocityDataAccessorPtr->get(newCell->extraAttribPtr)->getInstantenousVelocity().Y() // // <<cellVelocityDataAccessorPtr->get(newCell->extraAttribPtr)->getInstantenousVelocity().Z() // // <<endl; // } // // // // cerr<<"********"<<endl; // // // } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CellVelocityPlugin::readXML(XMLPullParser &in){ in.skip(TEXT); unsigned int size=2; unsigned int enoughData=2; while (in.check(START_ELEMENT)) { if (in.getName() == "VelocityDataHistorySize") { size = BasicString::parseUInteger(in.matchSimple()); } else if (in.getName() == "EnoughDataThreshold") { enoughData= BasicString::parseUInteger(in.matchSimple()); } else { throw BasicException(string("Unexpected element '") + in.getName() + "'!", in.getLocation()); } in.skip(TEXT); } cldequeCapacity=size; enoughDataThreshold=enoughData; ASSERT_OR_THROW("capacity must be at least 2 " , cldequeCapacity >= 2 ); ASSERT_OR_THROW("capacity must be >= enoughDataThreshold " , cldequeCapacity >= enoughDataThreshold ); } };
[ "acosmane@indiana.edu" ]
acosmane@indiana.edu
8869b8f794d4d5decba41f83afb517b86b0792c2
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_DinoSettings_Omnivore_Medium_MoschopsTaming_Item_04_parameters.hpp
b0dfa80cb462bbdbb84dc32053525ecbc32152b3
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
908
hpp
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoSettings_Omnivore_Medium_MoschopsTaming_Item_04_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function DinoSettings_Omnivore_Medium_MoschopsTaming_Item_04.DinoSettings_Omnivore_Medium_MoschopsTaming_Item_04_C.ExecuteUbergraph_DinoSettings_Omnivore_Medium_MoschopsTaming_Item_04 struct UDinoSettings_Omnivore_Medium_MoschopsTaming_Item_04_C_ExecuteUbergraph_DinoSettings_Omnivore_Medium_MoschopsTaming_Item_04_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
b50228d9a591178c0f0db0270c92519cec26b6f0
6edaf7e78c43f822c830043aec786b2be47dd73e
/cpp/acm/cqu_2018_summer_fifteen_day/uva_10801.cpp
2d4d35b2b89593e32ab36ede7712ae36a2f4dd1f
[]
no_license
HBat11233/hbat_code
8d2c8bc0e44775fafa3cb2820e8388e8d3702bc6
2f5de84498660863fd2816f0f8d49442689f88b8
refs/heads/master
2021-07-20T03:54:20.961518
2018-10-11T08:24:50
2018-10-11T08:24:50
112,096,574
0
0
null
null
null
null
UTF-8
C++
false
false
2,567
cpp
#include <bits/stdc++.h> #define mem(a,b) memset(a,b,sizeof(a)) using namespace std; int n,k; int he; int ti[7]; int w[705][705]; int dis[705]; int pk[705]; int spfa(int x) { queue<int>que; mem(pk,0); mem(dis,0x7f); pk[x]=true; que.push(x); dis[x]=0; int len=(he+1)*n; while(!que.empty()) { int h=que.front(); for(int i=1;i<=len;++i) { if(dis[i]>dis[h]+w[h][i]) { dis[i]=dis[h]+w[h][i]; if(!pk[i]) { pk[i]=true; que.push(i); } } } que.pop(); pk[h]=false; } int ans=0x7fffffff; len=k*n; for(int i=1;i<=n;++i) ans=min(ans,dis[len+i]); return ans; } int main() { #ifdef DEBUG freopen("out.txt","w",stdout); #endif // DEBUG while(~scanf("%d%d",&n,&k)) { static int o=0; o++; mem(ti,0); mem(w,0x7f); for(int i=1;i<=n;++i) scanf("%d",ti+i); char ch; int pos=1; int te; int la=-1; he=k; while(pos<=n) { scanf("%d",&te); he=max(he,te); ch=getchar(); if(la!=-1) w[pos+la*n][pos+te*n]=w[pos+te*n][pos+la*n]=(te-la)*ti[pos]; la=te; if(ch=='\n') { pos++; la=-1; } } for(int i=1;i<=he;++i) for(int j=1;j<=n;++j) for(int k=1;k<=n;++k) if(j!=k)w[i*n+j][i*n+k]=w[i*n+k][i*n+j]=60; for(int j=1;j<=n;++j) for(int k=1;k<=n;++k) if(j!=k)w[j][k]=w[k][j]=0; int ans=spfa(1); if(ans>=0x7f7f7f7f)printf("IMPOSSIBLE\n"); else printf("%d\n",ans); } return 0; } /* 4 44 47 9 82 95 0 1 2 3 4 5 9 10 11 13 14 15 16 18 23 25 26 27 29 31 33 34 35 37 38 39 41 43 44 47 49 52 53 54 55 56 57 58 62 63 64 66 68 70 71 73 74 75 76 78 80 81 82 83 84 85 87 89 90 91 92 93 94 95 96 97 99 3 7 22 26 30 34 37 38 47 49 61 62 70 97 1 19 24 33 40 54 70 77 95 3 31 25 63 83 5 7 12 15 22 27 28 29 30 34 35 36 39 46 47 48 51 57 59 69 71 73 75 76 83 90 96 98 0 1 3 4 5 6 9 10 11 12 13 15 16 17 18 19 20 21 23 24 25 26 28 30 32 33 35 36 37 38 39 40 41 43 44 45 49 50 51 52 53 55 56 58 59 60 62 64 65 67 69 70 72 74 77 78 79 80 82 83 84 85 86 89 90 91 93 95 96 98 0 7 8 10 11 13 17 32 34 39 41 43 48 49 54 59 60 63 70 71 73 74 79 82 86 90 92 93 95 96 98 */
[ "33086330+HBat11233@users.noreply.github.com" ]
33086330+HBat11233@users.noreply.github.com
579071109e36be3b4f918721937afdc11259c46c
ee2e457fdd6a4d9bd28f98aa118d56a2ffc5a6ce
/src/abil_stealth.cpp
24d577c6b437936040d4311872aca7a9c5c92398
[]
no_license
seobyeongky/gunscape
a5ba837deb0de6bf9768794ec63ff07ff24e42ca
d35855d0099ebd7ce4ad90f0f20f8616e3679ff0
refs/heads/master
2016-09-05T13:46:54.944484
2015-01-17T04:17:13
2015-01-17T04:17:13
13,535,746
5
0
null
null
null
null
UHC
C++
false
false
1,303
cpp
////////////////////////////////////////////////////////////////////////////////////////////////// // // 파일이름: abil_stealth.cpp // // 내용: 도둑걸음(늦게 발견) // ////////////////////////////////////////////////////////////////////////////////////////////////// #include "abil_stealth.h" #include "player.h" Abil_stealth::Abil_stealth(int level_): Ability("도둑걸음", level_, 3, 100, 1, AT_PASSIVE) { //필요능력. 반대능력은 여기서 판단하기 } Abil_stealth::~Abil_stealth() { } Ability* Abil_stealth::Clone(int level_) { return new Abil_stealth(level_); } const char* Abil_stealth::GetInfor() { switch(level) { case 1: return "정면이 아니면 적에게 곧바로 들키지않음"; case 2: return "정면이 아닐때 적에게 금방은 들키지않는 시간이 증가"; case 3: return "정면이 아닐때 적에게 금방은 들키지않는 시간이 증가"; } return "레벨 에러"; } int Abil_stealth::GetTime() { switch(level) { case 1: return 400; case 2: return 150; case 3: return 90; } return false; } bool Abil_stealth::ActivePlayer(Player* player_) { player_->SetWarningTime(GetTime()); return true; } bool Abil_stealth::UnActivePlayer(Player* player_) { player_->SetWarningTime(1000); return false; }
[ "seobyeongky@naver.com" ]
seobyeongky@naver.com
afbd165614dd8e1c804c5edaf76dc0eceaa371c4
9c028b54ffb83ea187e41e769c49fc40ae7f2ff3
/src/main.cpp
2d8917d9809b4b36e065bc9b1209a2c816146b96
[]
no_license
VasiliiGeneralov/clc
4e72c1343b0a13ae344c992f197532b1ef680206
aed3a478037e54b795695db4547adc756e268394
refs/heads/master
2023-06-09T15:03:02.433417
2021-06-28T00:14:01
2021-06-28T04:43:52
380,487,648
0
0
null
null
null
null
UTF-8
C++
false
false
457
cpp
#include <iostream> #include <string> #include <vector> #include "Tokenizer.hpp" #include "Parser.hpp" #include "Analyzer.hpp" int main() { std::string input; std::getline(std::cin, input); std::vector<std::string> tokens; tokens = Tokenizer::tokenize(input); if (tokens.empty()) { return 1; } tokens = Parser::parse(tokens); if (tokens.empty()) { return 2; } std::cout << Analyzer::analyze(tokens) << std::endl; return 0; }
[ "vasilii.generalov@gmail.com" ]
vasilii.generalov@gmail.com
04386d04f27580721a82a8e6e14edebc32648917
c71d9862169295dd650390ca44f2ebeb2e6740af
/src/corelib/plugin/qplugin.h
42a32a72f44e798a6071e451196b42e79679251c
[]
no_license
maoxingda/qt-src
d23c8d0469f234f89fdcbdbe6f3d50fa16e7a0e3
e01aee06520bf526975b0bedafe78eb003b5ead6
refs/heads/master
2020-04-14T00:05:16.292626
2019-01-05T05:49:42
2019-01-05T05:49:42
163,524,224
1
0
null
null
null
null
UTF-8
C++
false
false
5,251
h
/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QPLUGIN_H #define QPLUGIN_H #include <QtCore/qobject.h> #include <QtCore/qpointer.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Core) #ifndef Q_EXTERN_C # ifdef __cplusplus # define Q_EXTERN_C extern "C" # else # define Q_EXTERN_C extern # endif #endif typedef QObject *(*QtPluginInstanceFunction)(); void Q_CORE_EXPORT qRegisterStaticPluginInstanceFunction(QtPluginInstanceFunction function); #define Q_IMPORT_PLUGIN(PLUGIN) \ extern QT_PREPEND_NAMESPACE(QObject) *qt_plugin_instance_##PLUGIN(); \ class Static##PLUGIN##PluginInstance{ \ public: \ Static##PLUGIN##PluginInstance() { \ qRegisterStaticPluginInstanceFunction(qt_plugin_instance_##PLUGIN); \ } \ }; \ static Static##PLUGIN##PluginInstance static##PLUGIN##Instance; #define Q_PLUGIN_INSTANCE(IMPLEMENTATION) \ { \ static QT_PREPEND_NAMESPACE(QPointer)<QT_PREPEND_NAMESPACE(QObject)> _instance; \ if (!_instance) \ _instance = new IMPLEMENTATION; \ return _instance; \ } # define Q_EXPORT_PLUGIN(PLUGIN) \ Q_EXPORT_PLUGIN2(PLUGIN, PLUGIN) # define Q_EXPORT_STATIC_PLUGIN(PLUGIN) \ Q_EXPORT_STATIC_PLUGIN2(PLUGIN, PLUGIN) #if defined(QT_STATICPLUGIN) # define Q_EXPORT_PLUGIN2(PLUGIN, PLUGINCLASS) \ QT_PREPEND_NAMESPACE(QObject) \ *qt_plugin_instance_##PLUGIN() \ Q_PLUGIN_INSTANCE(PLUGINCLASS) # define Q_EXPORT_STATIC_PLUGIN2(PLUGIN, PLUGINCLASS) \ Q_EXPORT_PLUGIN2(PLUGIN, PLUGINCLASS) #else // NOTE: if you change pattern, you MUST change the pattern in // qlibrary.cpp as well. changing the pattern will break all // backwards compatibility as well (no old plugins will be loaded). // QT5: should probably remove the entire pattern thing and do the section // trick for all platforms. for now, keep it and fallback to scan for it. # ifdef QPLUGIN_DEBUG_STR # undef QPLUGIN_DEBUG_STR # endif # ifdef QT_NO_DEBUG # define QPLUGIN_DEBUG_STR "false" # define QPLUGIN_SECTION_DEBUG_STR "" # else # define QPLUGIN_DEBUG_STR "true" # define QPLUGIN_SECTION_DEBUG_STR ".debug" # endif # define Q_PLUGIN_VERIFICATION_DATA \ static const char qt_plugin_verification_data[] = \ "pattern=QT_PLUGIN_VERIFICATION_DATA\n" \ "version=" QT_VERSION_STR "\n" \ "debug=" QPLUGIN_DEBUG_STR "\n" \ "buildkey=" QT_BUILD_KEY; # if defined (Q_OF_ELF) && defined (Q_CC_GNU) # define Q_PLUGIN_VERIFICATION_SECTION \ __attribute__ ((section (".qtplugin"))) __attribute__((used)) # else # define Q_PLUGIN_VERIFICATION_SECTION # endif # if defined (Q_OS_WIN32) && defined(Q_CC_BOR) # define Q_STANDARD_CALL __stdcall # else # define Q_STANDARD_CALL # endif # define Q_EXPORT_PLUGIN2(PLUGIN, PLUGINCLASS) \ Q_PLUGIN_VERIFICATION_SECTION Q_PLUGIN_VERIFICATION_DATA \ Q_EXTERN_C Q_DECL_EXPORT \ const char * Q_STANDARD_CALL qt_plugin_query_verification_data() \ { return qt_plugin_verification_data; } \ Q_EXTERN_C Q_DECL_EXPORT QT_PREPEND_NAMESPACE(QObject) * Q_STANDARD_CALL qt_plugin_instance() \ Q_PLUGIN_INSTANCE(PLUGINCLASS) # define Q_EXPORT_STATIC_PLUGIN2(PLUGIN, PLUGINCLASS) #endif QT_END_NAMESPACE QT_END_HEADER #endif // Q_PLUGIN_H
[ "39357378+maoxingda@users.noreply.github.com" ]
39357378+maoxingda@users.noreply.github.com
6a1ec0aaf47d85213a912c4375ef96557d46b24a
a0a3a9714ba97260a7c5b3736db6e2e87e50d8d4
/ds/dinic.cpp
a13ba621acf3cc7b14a3b2d6db28af44d42ef20b
[]
no_license
YakutovDmitriy/Cpp-Algorithms
a60991bd725e1ec76da7b4165adc916e2f80b32e
c26752384a3e9ce7f452d99419cdda0c4d856fa4
refs/heads/master
2020-04-15T13:38:26.727377
2017-07-06T09:44:50
2017-07-06T09:44:50
57,463,459
0
0
null
null
null
null
UTF-8
C++
false
false
3,873
cpp
#include <bits/stdc++.h> //#include <fcntl.h> using std::max; using std::swap; using std::abs; using std::priority_queue; using std::queue; using std::bitset; using std::make_tuple; using std::istream; using std::ostream; using std::fixed; using std::greater; using std::tuple; using std::tie; using std::make_pair; using std::cout; using std::cerr; using std::endl; using std::lower_bound; using std::upper_bound; using std::deque; using std::min; using std::map; using std::string; using std::fill; using std::copy; using std::sort; using std::unique; using std::unordered_set; using std::multiset; using std::nth_element; using std::min_element; using std::max_element; using std::vector; using std::set; using std::unordered_map; using std::pair; using std::next_permutation; using std::reverse; using std::rotate; using std::cin; using std::iota; using std::function; using std::shuffle; using std::iter_swap; typedef long long ll; typedef long double ld; typedef unsigned int uint; typedef unsigned long long ull; int const INF = 100 + (int) 1e9; ll const INFL = 100 + (ll) 1e18; ld const PI = 3.141592653589793238462643L; std::mt19937 mt19937(960172); ll rnd(ll x, ll y) { static auto gen = std::bind(std::uniform_int_distribution<ll>(), mt19937); return gen() % (y - x + 1) + x; } bool is_prime(ll x) { if (x <= 1) return 0; for (ll y = 2; y * y <= x; ++y) if (x % y == 0) return 0; return 1; } ll sqr(int a) { return (ll) a * a; } ld sqr(ld a) { return a * a; } ll sqr(ll a) { return a * a; } ll gcd(ll a, ll b) { while (b > 0) { ll t = a % b; a = b; b = t; } return a; } int const N = 200200; struct edge_t { int to, cap, flow; edge_t(int to, int cap) : to(to) , cap(cap) , flow(0) {} }; vector<edge_t> all; vector<int> g[N]; int index[N], dist[N]; void add_edge(int from, int to, int cap1, int cap2) { g[from].push_back(all.size()); all.emplace_back(to, cap1); g[to].push_back(all.size()); all.emplace_back(from, cap2); } void init_graph(int n) { all.clear(); for (int i = 0; i < n; ++i) { g[i].clear(); } } void clear_flow() { for (auto& edge : all) { edge.flow = 0; } } int dfs(int v, int sink, int flow) { if (v == sink || flow == 0) { return flow; } for (int& i = index[v]; i < (int)g[v].size(); ++i) { int x = g[v][i]; auto& e = all[x]; int to = e.to; int diff = e.cap - e.flow; if (diff > 0 && dist[v] - 1 == dist[to]) { int now = dfs(to, sink, min(flow, diff)); if (now > 0) { e.flow += now; all[x ^ 1].flow -= now; return now; } } } return 0; } ll max_flow(int source, int sink, int n) { clear_flow(); ll ret = 0; while (true) { static int q[N]; memset(dist, 63, sizeof(int) * n); int tail = 0; dist[q[tail++] = sink] = 0; for (int i = 0; i < tail; ++i) { int v = q[i]; for (int x : g[v]) { int to = all[x].to; if (all[x ^ 1].flow < all[x ^ 1].cap && dist[to] > INF) { dist[q[tail++] = to] = dist[v] + 1; } } } if (dist[source] > INF) { break; } memset(index, 0, n * sizeof(int)); while (int flow = dfs(source, sink, INF)) { ret += flow; } } return ret; } void solve() { } int main() { //freopen("", "r", stdin); //freopen("", "w", stdout); cout.precision(15); cout << fixed; cerr.precision(6); cerr << fixed; int tcn = 1; for (int tn = 1; tn <= tcn; ++tn) solve(); #ifdef LOCAL cerr << "time: " << (ll) clock() * 1000 / CLOCKS_PER_SEC << " ms" << endl; #endif }
[ "miti_95@mail.ru" ]
miti_95@mail.ru
a37ae8ed3785406eb98e634cc5e8160cf7ee8040
b389755eed095f67bac67bde8690adf0217d8470
/platforms/android/aace/src/main/cpp/src/aace/alexa/LocalMediaSourceBinder.cpp
c6ae79042c5b78ccf01248d5a617ba9c21d9cb83
[ "JSON", "MIT", "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
shoesel/aac-sdk
4fdbb85d4d51aaaad7adb5d7ae69dfd65559dbd6
8370f7c71c73dd1af53469dfa3de1eaf7aa2d347
refs/heads/master
2020-06-10T14:00:11.911393
2019-06-24T22:46:22
2019-06-24T23:04:52
193,653,787
1
0
Apache-2.0
2019-06-25T07:06:17
2019-06-25T07:06:17
null
UTF-8
C++
false
false
40,832
cpp
/* * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /*************************************************************************************** * CAUTION: THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT MODIFY THIS FILE! * * ANY NECESSARY MODIFICATIONS SHOULD BE INCORPORATED INTO THE GENERATOR. * ***************************************************************************************/ #include "aace/alexa/LocalMediaSourceBinder.h" LocalMediaSourceBinder::LocalMediaSourceBinder( aace::alexa::LocalMediaSource::Source source, std::shared_ptr<aace::alexa::Speaker> speaker ) : aace::alexa::LocalMediaSource( source, speaker ) { } LocalMediaSourceBinder::~LocalMediaSourceBinder() {} void LocalMediaSourceBinder::initialize( JNIEnv* env ) { m_javaMethod_authorize_authorized = env->GetMethodID( getJavaClass(), "authorize", "(Z)Z" ); m_javaMethod_play_payload = env->GetMethodID( getJavaClass(), "play", "(Ljava/lang/String;)Z" ); m_javaMethod_playControl_controlType = env->GetMethodID( getJavaClass(), "playControl", "(Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;)Z" ); m_javaMethod_seek_offset = env->GetMethodID( getJavaClass(), "seek", "(J)Z" ); m_javaMethod_adjustSeek_deltaOffset = env->GetMethodID( getJavaClass(), "adjustSeek", "(J)Z" ); m_javaMethod_getState = env->GetMethodID( getJavaClass(), "getState", "()Lcom/amazon/aace/alexa/LocalMediaSource$LocalMediaSourceState;" ); // PlayControlType jclass playControlTypeEnumClass = env->FindClass( "com/amazon/aace/alexa/LocalMediaSource$PlayControlType" ); m_enum_PlayControlType_PAUSE = NativeLib::FindEnum( env, playControlTypeEnumClass, "PAUSE", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_RESUME = NativeLib::FindEnum( env, playControlTypeEnumClass, "RESUME", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_NEXT = NativeLib::FindEnum( env, playControlTypeEnumClass, "NEXT", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_PREVIOUS = NativeLib::FindEnum( env, playControlTypeEnumClass, "PREVIOUS", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_START_OVER = NativeLib::FindEnum( env, playControlTypeEnumClass, "START_OVER", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_FAST_FORWARD = NativeLib::FindEnum( env, playControlTypeEnumClass, "FAST_FORWARD", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_REWIND = NativeLib::FindEnum( env, playControlTypeEnumClass, "REWIND", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_ENABLE_REPEAT_ONE = NativeLib::FindEnum( env, playControlTypeEnumClass, "ENABLE_REPEAT_ONE", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_ENABLE_REPEAT = NativeLib::FindEnum( env, playControlTypeEnumClass, "ENABLE_REPEAT", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_DISABLE_REPEAT = NativeLib::FindEnum( env, playControlTypeEnumClass, "DISABLE_REPEAT", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_ENABLE_SHUFFLE = NativeLib::FindEnum( env, playControlTypeEnumClass, "ENABLE_SHUFFLE", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_DISABLE_SHUFFLE = NativeLib::FindEnum( env, playControlTypeEnumClass, "DISABLE_SHUFFLE", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_FAVORITE = NativeLib::FindEnum( env, playControlTypeEnumClass, "FAVORITE", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); m_enum_PlayControlType_UNFAVORITE = NativeLib::FindEnum( env, playControlTypeEnumClass, "UNFAVORITE", "Lcom/amazon/aace/alexa/LocalMediaSource$PlayControlType;" ); // Source jclass sourceEnumClass = env->FindClass( "com/amazon/aace/alexa/LocalMediaSource$Source" ); m_enum_Source_BLUETOOTH = NativeLib::FindEnum( env, sourceEnumClass, "BLUETOOTH", "Lcom/amazon/aace/alexa/LocalMediaSource$Source;" ); m_enum_Source_USB = NativeLib::FindEnum( env, sourceEnumClass, "USB", "Lcom/amazon/aace/alexa/LocalMediaSource$Source;" ); m_enum_Source_FM_RADIO = NativeLib::FindEnum( env, sourceEnumClass, "FM_RADIO", "Lcom/amazon/aace/alexa/LocalMediaSource$Source;" ); m_enum_Source_AM_RADIO = NativeLib::FindEnum( env, sourceEnumClass, "AM_RADIO", "Lcom/amazon/aace/alexa/LocalMediaSource$Source;" ); m_enum_Source_SATELLITE_RADIO = NativeLib::FindEnum( env, sourceEnumClass, "SATELLITE_RADIO", "Lcom/amazon/aace/alexa/LocalMediaSource$Source;" ); m_enum_Source_LINE_IN = NativeLib::FindEnum( env, sourceEnumClass, "LINE_IN", "Lcom/amazon/aace/alexa/LocalMediaSource$Source;" ); m_enum_Source_COMPACT_DISC = NativeLib::FindEnum( env, sourceEnumClass, "COMPACT_DISC", "Lcom/amazon/aace/alexa/LocalMediaSource$Source;" ); // AdapterState m_javaClass_LocalMediaSourceState = NativeLib::FindClass( env, "com/amazon/aace/alexa/LocalMediaSource$LocalMediaSourceState" ); m_javaClass_LocalMediaSourceState_SessionState = env->GetFieldID( m_javaClass_LocalMediaSourceState.get(), "sessionState", "Lcom/amazon/aace/alexa/LocalMediaSource$SessionState;"); m_javaClass_LocalMediaSourceState_PlaybackState = env->GetFieldID( m_javaClass_LocalMediaSourceState.get(), "playbackState", "Lcom/amazon/aace/alexa/LocalMediaSource$PlaybackState;"); // SessionState m_javaClass_SessionState = NativeLib::FindClass(env, "com/amazon/aace/alexa/LocalMediaSource$SessionState"); m_javaField_SessionState_endpointId = env->GetFieldID( m_javaClass_SessionState.get(), "endpointId", "Ljava/lang/String;"); m_javaField_SessionState_loggedIn = env->GetFieldID( m_javaClass_SessionState.get(), "loggedIn", "Z"); m_javaField_SessionState_userName = env->GetFieldID( m_javaClass_SessionState.get(), "userName", "Ljava/lang/String;"); m_javaField_SessionState_isGuest = env->GetFieldID( m_javaClass_SessionState.get(), "isGuest", "Z"); m_javaField_SessionState_launched = env->GetFieldID( m_javaClass_SessionState.get(), "launched", "Z"); m_javaField_SessionState_active = env->GetFieldID( m_javaClass_SessionState.get(), "active", "Z"); m_javaField_SessionState_accessToken = env->GetFieldID( m_javaClass_SessionState.get(), "accessToken", "Ljava/lang/String;"); m_javaField_SessionState_tokenRefreshInterval = env->GetFieldID( m_javaClass_SessionState.get(), "tokenRefreshInterval", "J"); m_javaField_SessionState_playerCookie = env->GetFieldID( m_javaClass_SessionState.get(), "playerCookie", "Ljava/lang/String;"); m_javaField_SessionState_spiVersion = env->GetFieldID( m_javaClass_SessionState.get(), "spiVersion", "Ljava/lang/String;"); // PlaybackState m_javaClass_PlaybackState = NativeLib::FindClass(env, "com/amazon/aace/alexa/LocalMediaSource$PlaybackState"); m_javaField_PlaybackState_state = env->GetFieldID( m_javaClass_PlaybackState.get(), "state", "Ljava/lang/String;"); m_javaField_PlaybackState_supportedOperations = env->GetFieldID( m_javaClass_PlaybackState.get(), "supportedOperations", "[Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;"); m_javaField_PlaybackState_trackOffset = env->GetFieldID( m_javaClass_PlaybackState.get(), "trackOffset", "J"); m_javaField_PlaybackState_shuffleEnabled = env->GetFieldID( m_javaClass_PlaybackState.get(), "shuffleEnabled", "Z"); m_javaField_PlaybackState_repeatEnabled = env->GetFieldID( m_javaClass_PlaybackState.get(), "repeatEnabled", "Z"); m_javaField_PlaybackState_favorites = env->GetFieldID( m_javaClass_PlaybackState.get(), "favorites", "Lcom/amazon/aace/alexa/LocalMediaSource$Favorites;"); m_javaField_PlaybackState_type = env->GetFieldID( m_javaClass_PlaybackState.get(), "type", "Ljava/lang/String;"); m_javaField_PlaybackState_playbackSource = env->GetFieldID( m_javaClass_PlaybackState.get(), "playbackSource", "Ljava/lang/String;"); m_javaField_PlaybackState_playbackSourceId = env->GetFieldID( m_javaClass_PlaybackState.get(), "playbackSourceId", "Ljava/lang/String;"); m_javaField_PlaybackState_trackName = env->GetFieldID( m_javaClass_PlaybackState.get(), "trackName", "Ljava/lang/String;"); m_javaField_PlaybackState_trackId = env->GetFieldID( m_javaClass_PlaybackState.get(), "trackId", "Ljava/lang/String;"); m_javaField_PlaybackState_trackNumber = env->GetFieldID( m_javaClass_PlaybackState.get(), "trackNumber", "Ljava/lang/String;"); m_javaField_PlaybackState_artistName = env->GetFieldID( m_javaClass_PlaybackState.get(), "artistName", "Ljava/lang/String;"); m_javaField_PlaybackState_artistId = env->GetFieldID( m_javaClass_PlaybackState.get(), "artistId", "Ljava/lang/String;"); m_javaField_PlaybackState_albumName = env->GetFieldID( m_javaClass_PlaybackState.get(), "albumName", "Ljava/lang/String;"); m_javaField_PlaybackState_albumId = env->GetFieldID( m_javaClass_PlaybackState.get(), "albumId", "Ljava/lang/String;"); m_javaField_PlaybackState_tinyURL = env->GetFieldID( m_javaClass_PlaybackState.get(), "tinyURL", "Ljava/lang/String;"); m_javaField_PlaybackState_smallURL = env->GetFieldID( m_javaClass_PlaybackState.get(), "smallURL", "Ljava/lang/String;"); m_javaField_PlaybackState_mediumURL = env->GetFieldID( m_javaClass_PlaybackState.get(), "mediumURL", "Ljava/lang/String;"); m_javaField_PlaybackState_largeURL = env->GetFieldID( m_javaClass_PlaybackState.get(), "largeURL", "Ljava/lang/String;"); m_javaField_PlaybackState_coverId = env->GetFieldID( m_javaClass_PlaybackState.get(), "coverId", "Ljava/lang/String;"); m_javaField_PlaybackState_mediaProvider = env->GetFieldID( m_javaClass_PlaybackState.get(), "mediaProvider", "Ljava/lang/String;"); m_javaField_PlaybackState_mediaType = env->GetFieldID( m_javaClass_PlaybackState.get(), "mediaType", "Lcom/amazon/aace/alexa/LocalMediaSource$MediaType;"); m_javaField_PlaybackState_duration = env->GetFieldID( m_javaClass_PlaybackState.get(), "duration", "J"); // SupportedPlaybackOperation jclass supportedPlaybackOperationEnumClass = env->FindClass( "com/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation" ); m_enum_SupportedPlaybackOperation_PLAY = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "PLAY", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_RESUME = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "RESUME", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_PAUSE = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "PAUSE", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_STOP = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "STOP", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_NEXT = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "NEXT", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_PREVIOUS = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "PREVIOUS", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_START_OVER = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "START_OVER", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_FAST_FORWARD = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "FAST_FORWARD", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_REWIND = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "REWIND", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_ENABLE_REPEAT = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "ENABLE_REPEAT", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_ENABLE_REPEAT_ONE = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "ENABLE_REPEAT_ONE", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_DISABLE_REPEAT = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "DISABLE_REPEAT", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_ENABLE_SHUFFLE = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "ENABLE_SHUFFLE", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_DISABLE_SHUFFLE = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "DISABLE_SHUFFLE", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_FAVORITE = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "FAVORITE", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_UNFAVORITE = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "UNFAVORITE", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_SEEK = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "SEEK", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); m_enum_SupportedPlaybackOperation_ADJUST_SEEK = NativeLib::FindEnum( env, supportedPlaybackOperationEnumClass, "ADJUST_SEEK", "Lcom/amazon/aace/alexa/LocalMediaSource$SupportedPlaybackOperation;" ); // Favorites jclass favoritesEnumClass = env->FindClass( "com/amazon/aace/alexa/LocalMediaSource$Favorites" ); m_enum_Favorites_FAVORITED = NativeLib::FindEnum( env, favoritesEnumClass, "FAVORITED", "Lcom/amazon/aace/alexa/LocalMediaSource$Favorites;" ); m_enum_Favorites_UNFAVORITED = NativeLib::FindEnum( env, favoritesEnumClass, "UNFAVORITED", "Lcom/amazon/aace/alexa/LocalMediaSource$Favorites;" ); m_enum_Favorites_NOT_RATED = NativeLib::FindEnum( env, favoritesEnumClass, "NOT_RATED", "Lcom/amazon/aace/alexa/LocalMediaSource$Favorites;" ); // MediaType jclass mediaTypeEnumClass = env->FindClass( "com/amazon/aace/alexa/LocalMediaSource$MediaType" ); m_enum_MediaType_TRACK = NativeLib::FindEnum( env, mediaTypeEnumClass, "TRACK", "Lcom/amazon/aace/alexa/LocalMediaSource$MediaType;" ); m_enum_MediaType_PODCAST = NativeLib::FindEnum( env, mediaTypeEnumClass, "PODCAST", "Lcom/amazon/aace/alexa/LocalMediaSource$MediaType;" ); m_enum_MediaType_STATION = NativeLib::FindEnum( env, mediaTypeEnumClass, "STATION", "Lcom/amazon/aace/alexa/LocalMediaSource$MediaType;" ); m_enum_MediaType_AD = NativeLib::FindEnum( env, mediaTypeEnumClass, "AD", "Lcom/amazon/aace/alexa/LocalMediaSource$MediaType;" ); m_enum_MediaType_SAMPLE = NativeLib::FindEnum( env, mediaTypeEnumClass, "SAMPLE", "Lcom/amazon/aace/alexa/LocalMediaSource$MediaType;" ); m_enum_MediaType_OTHER = NativeLib::FindEnum( env, mediaTypeEnumClass, "OTHER", "Lcom/amazon/aace/alexa/LocalMediaSource$MediaType;" ); } bool LocalMediaSourceBinder::authorize( bool authorized ) { bool result = false; if( getJavaObject() != nullptr && m_javaMethod_authorize_authorized != nullptr ) { ThreadContext context; if( context.isValid() ) { result = context.getEnv()->CallBooleanMethod( getJavaObject(), m_javaMethod_authorize_authorized, authorized ); } } return result; } bool LocalMediaSourceBinder::play( const std::string & payload ) { bool result = false; if( getJavaObject() != nullptr && m_javaMethod_play_payload != nullptr ) { ThreadContext context; if( context.isValid() ) { jstring payloadStr = context.getEnv()->NewStringUTF( payload.c_str() ); result = context.getEnv()->CallBooleanMethod( getJavaObject(), m_javaMethod_play_payload, payloadStr ); context.getEnv()->DeleteLocalRef( payloadStr ); } } return result; } bool LocalMediaSourceBinder::playControl( aace::alexa::LocalMediaSource::PlayControlType controlType ) { bool result = false; if( getJavaObject() != nullptr && m_javaMethod_playControl_controlType != nullptr ) { ThreadContext context; if( context.isValid() ) { result = context.getEnv()->CallBooleanMethod( getJavaObject(), m_javaMethod_playControl_controlType, convert( controlType ) ); } } return result; } bool LocalMediaSourceBinder::seek( std::chrono::milliseconds offset ) { bool result = false; if( getJavaObject() != nullptr && m_javaMethod_seek_offset != nullptr ) { ThreadContext context; if( context.isValid() ) { result = context.getEnv()->CallBooleanMethod( getJavaObject(), m_javaMethod_seek_offset, offset.count()); } } return result; } bool LocalMediaSourceBinder::adjustSeek( std::chrono::milliseconds deltaOffset ) { bool result = false; if( getJavaObject() != nullptr && m_javaMethod_adjustSeek_deltaOffset != nullptr ) { ThreadContext context; if( context.isValid() ) { result = context.getEnv()->CallBooleanMethod( getJavaObject(), m_javaMethod_adjustSeek_deltaOffset, deltaOffset.count() ); } } return result; } aace::alexa::LocalMediaSource::LocalMediaSourceState LocalMediaSourceBinder::getState() { aace::alexa::LocalMediaSource::LocalMediaSourceState state; if( getJavaObject() != nullptr && m_javaMethod_getState != nullptr ) { ThreadContext context; if( context.isValid() ) { JNIEnv *env = context.getEnv(); jobject localLocalMediaSourceState = env->CallObjectMethod( getJavaObject(), m_javaMethod_getState ); if( localLocalMediaSourceState != nullptr ) { // SessionState jobject localSessionState = env->GetObjectField( localLocalMediaSourceState, m_javaClass_LocalMediaSourceState_SessionState); jstring localEndpointId = ( jstring ) env->GetObjectField( localSessionState, m_javaField_SessionState_endpointId); state.sessionState.endpointId = NativeLib::convert(env, localEndpointId); env->DeleteLocalRef(localEndpointId); jboolean localLoggedIn = env->GetBooleanField( localSessionState, m_javaField_SessionState_loggedIn); state.sessionState.loggedIn = localLoggedIn; jstring localUserName = ( jstring ) env->GetObjectField( localSessionState, m_javaField_SessionState_userName); state.sessionState.userName = NativeLib::convert(env, localUserName); env->DeleteLocalRef(localUserName); jboolean localIsGuest = env->GetBooleanField( localSessionState, m_javaField_SessionState_isGuest); state.sessionState.isGuest = localIsGuest; jboolean localLaunched = env->GetBooleanField( localSessionState, m_javaField_SessionState_launched); state.sessionState.launched = localLaunched; jboolean localActive = env->GetBooleanField( localSessionState, m_javaField_SessionState_active); state.sessionState.active = localActive; jstring localAccessToken = ( jstring ) env->GetObjectField( localSessionState, m_javaField_SessionState_accessToken); state.sessionState.accessToken = NativeLib::convert(env, localAccessToken); env->DeleteLocalRef(localAccessToken); jlong localTokenRefreshInterval = env->GetLongField( localSessionState, m_javaField_SessionState_tokenRefreshInterval); state.sessionState.tokenRefreshInterval = std::chrono::milliseconds( localTokenRefreshInterval ); jstring spiVersion = (jstring) env->GetObjectField(localSessionState, m_javaField_SessionState_spiVersion); state.sessionState.spiVersion = NativeLib::convert(env, spiVersion); env->DeleteLocalRef(spiVersion); jstring playerCookie = (jstring) env->GetObjectField(localSessionState, m_javaField_SessionState_playerCookie); state.sessionState.playerCookie = NativeLib::convert(env, playerCookie); env->DeleteLocalRef(playerCookie); env->DeleteLocalRef(localSessionState); // PlaybackState jobject localPlaybackState = env->GetObjectField( localLocalMediaSourceState, m_javaClass_LocalMediaSourceState_PlaybackState); jstring localState = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_state); state.playbackState.state = NativeLib::convert(env, localState); env->DeleteLocalRef(localState); jobjectArray localSupportedOperations = ( jobjectArray ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_supportedOperations); int localSupportedOperationsLength = env->GetArrayLength( localSupportedOperations ); std::vector<ExternalMediaAdapterBinder::SupportedPlaybackOperation> supportedOperations; for ( int i = 0; i < localSupportedOperationsLength; i++ ) { supportedOperations.push_back( convertSupportedPlaybackOperation(env, env->GetObjectArrayElement(localSupportedOperations, i)) ); } state.playbackState.supportedOperations = supportedOperations; env->DeleteLocalRef(localSupportedOperations); supportedOperations.clear(); jlong localTrackOffset = env->GetLongField( localPlaybackState, m_javaField_PlaybackState_trackOffset); state.playbackState.trackOffset = std::chrono::milliseconds( (long) localTrackOffset ); jboolean localShuffleEnabled = env->GetBooleanField( localPlaybackState, m_javaField_PlaybackState_shuffleEnabled); state.playbackState.shuffleEnabled = localShuffleEnabled; jboolean localRepeatEnabled = env->GetBooleanField( localPlaybackState, m_javaField_PlaybackState_repeatEnabled); state.playbackState.repeatEnabled = localRepeatEnabled; jobject localFavorites = env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_favorites); state.playbackState.favorites = convertFavorites(env, localFavorites); env->DeleteLocalRef( localFavorites ); jstring localType = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_type); state.playbackState.type = NativeLib::convert(env, localType); env->DeleteLocalRef(localType); jstring localPlaybackSource = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_playbackSource); state.playbackState.playbackSource = NativeLib::convert(env, localPlaybackSource); env->DeleteLocalRef(localPlaybackSource); jstring localPlaybackSourceId = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_playbackSourceId); state.playbackState.playbackSourceId = NativeLib::convert(env, localPlaybackSourceId); env->DeleteLocalRef(localPlaybackSourceId); jstring localTrackName = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_trackName); state.playbackState.trackName = NativeLib::convert(env, localTrackName); env->DeleteLocalRef(localTrackName); jstring localTrackId = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_trackId); state.playbackState.trackId = NativeLib::convert(env, localTrackId); env->DeleteLocalRef(localTrackId); jstring localArtistName = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_artistName); state.playbackState.artistName = NativeLib::convert(env, localArtistName); env->DeleteLocalRef(localArtistName); jstring localArtistId = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_artistId); state.playbackState.artistId = NativeLib::convert(env, localArtistId); env->DeleteLocalRef(localArtistId); jstring localAlbumName = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_albumName); state.playbackState.albumName = NativeLib::convert(env, localAlbumName); env->DeleteLocalRef(localAlbumName); jstring localAlbumId = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_albumId); state.playbackState.albumId = NativeLib::convert(env, localAlbumId); env->DeleteLocalRef(localAlbumId); jstring localTinyURL = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_tinyURL); state.playbackState.tinyURL = NativeLib::convert(env, localTinyURL); env->DeleteLocalRef(localTinyURL); jstring localSmallURL = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_smallURL); state.playbackState.smallURL = NativeLib::convert(env, localSmallURL); env->DeleteLocalRef(localSmallURL); jstring localMediumURL = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_mediumURL); state.playbackState.mediumURL = NativeLib::convert(env, localMediumURL); env->DeleteLocalRef(localMediumURL); jstring localLargeURL = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_largeURL); state.playbackState.largeURL = NativeLib::convert(env, localLargeURL); env->DeleteLocalRef(localLargeURL); jstring localCoverId = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_coverId); state.playbackState.coverId = NativeLib::convert(env, localCoverId); env->DeleteLocalRef(localCoverId); jstring localMediaProvider = ( jstring ) env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_mediaProvider); state.playbackState.mediaProvider = NativeLib::convert(env, localMediaProvider); env->DeleteLocalRef(localMediaProvider); jobject localMediaType = env->GetObjectField( localPlaybackState, m_javaField_PlaybackState_mediaType); state.playbackState.mediaType = convertMediaType(env, localMediaType); env->DeleteLocalRef( localMediaType ); jlong localDuration = env->GetLongField( localPlaybackState, m_javaField_PlaybackState_duration); state.playbackState.duration = std::chrono::milliseconds( (long) localDuration ); env->DeleteLocalRef( localPlaybackState ); env->DeleteLocalRef( localLocalMediaSourceState ); } } } return state; } jobject LocalMediaSourceBinder::convert( aace::alexa::LocalMediaSource::PlayControlType type ) { switch( type ) { case aace::alexa::LocalMediaSource::PlayControlType::PAUSE: return m_enum_PlayControlType_PAUSE.get(); case aace::alexa::LocalMediaSource::PlayControlType::RESUME: return m_enum_PlayControlType_RESUME.get(); case aace::alexa::LocalMediaSource::PlayControlType::NEXT: return m_enum_PlayControlType_NEXT.get(); case aace::alexa::LocalMediaSource::PlayControlType::PREVIOUS: return m_enum_PlayControlType_PREVIOUS.get(); case aace::alexa::LocalMediaSource::PlayControlType::START_OVER: return m_enum_PlayControlType_START_OVER.get(); case aace::alexa::LocalMediaSource::PlayControlType::FAST_FORWARD: return m_enum_PlayControlType_FAST_FORWARD.get(); case aace::alexa::LocalMediaSource::PlayControlType::REWIND: return m_enum_PlayControlType_REWIND.get(); case aace::alexa::LocalMediaSource::PlayControlType::ENABLE_REPEAT_ONE: return m_enum_PlayControlType_ENABLE_REPEAT_ONE.get(); case aace::alexa::LocalMediaSource::PlayControlType::ENABLE_REPEAT: return m_enum_PlayControlType_ENABLE_REPEAT.get(); case aace::alexa::LocalMediaSource::PlayControlType::DISABLE_REPEAT: return m_enum_PlayControlType_DISABLE_REPEAT.get(); case aace::alexa::LocalMediaSource::PlayControlType::ENABLE_SHUFFLE: return m_enum_PlayControlType_ENABLE_SHUFFLE.get(); case aace::alexa::LocalMediaSource::PlayControlType::DISABLE_SHUFFLE: return m_enum_PlayControlType_DISABLE_SHUFFLE.get(); case aace::alexa::LocalMediaSource::PlayControlType::FAVORITE: return m_enum_PlayControlType_FAVORITE.get(); case aace::alexa::LocalMediaSource::PlayControlType::UNFAVORITE: return m_enum_PlayControlType_UNFAVORITE.get(); } } /* aace::alexa::LocalMediaSource::PlayControlType LocalMediaSourceBinder::convertPlayControlType( JNIEnv* env, jobject obj ) { if( m_enum_PlayControlType_PAUSE.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::PAUSE; } else if( m_enum_PlayControlType_RESUME.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::RESUME; } else if( m_enum_PlayControlType_NEXT.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::NEXT; } else if( m_enum_PlayControlType_PREVIOUS.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::PREVIOUS; } else if( m_enum_PlayControlType_START_OVER.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::START_OVER; } else if( m_enum_PlayControlType_FAST_FORWARD.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::FAST_FORWARD; } else if( m_enum_PlayControlType_REWIND.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::REWIND; } else if( m_enum_PlayControlType_ENABLE_REPEAT_ONE.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::ENABLE_REPEAT_ONE; } else if( m_enum_PlayControlType_ENABLE_REPEAT.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::ENABLE_REPEAT; } else if( m_enum_PlayControlType_DISABLE_REPEAT.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::DISABLE_REPEAT; } else if( m_enum_PlayControlType_ENABLE_SHUFFLE.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::ENABLE_SHUFFLE; } else if( m_enum_PlayControlType_DISABLE_SHUFFLE.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::DISABLE_SHUFFLE; } else if( m_enum_PlayControlType_FAVORITE.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::FAVORITE; } else if( m_enum_PlayControlType_UNFAVORITE.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::PlayControlType::UNFAVORITE; } else { return aace::alexa::LocalMediaSource::PlayControlType::UNFAVORITE; } } */ jobject LocalMediaSourceBinder::convert( aace::alexa::LocalMediaSource::Source source ) { switch( source ) { case aace::alexa::LocalMediaSource::Source::BLUETOOTH: return m_enum_Source_BLUETOOTH.get(); case aace::alexa::LocalMediaSource::Source::USB: return m_enum_Source_USB.get(); case aace::alexa::LocalMediaSource::Source::FM_RADIO: return m_enum_Source_FM_RADIO.get(); case aace::alexa::LocalMediaSource::Source::AM_RADIO: return m_enum_Source_AM_RADIO.get(); case aace::alexa::LocalMediaSource::Source::SATELLITE_RADIO: return m_enum_Source_SATELLITE_RADIO.get(); case aace::alexa::LocalMediaSource::Source::LINE_IN: return m_enum_Source_LINE_IN.get(); case aace::alexa::LocalMediaSource::Source::COMPACT_DISC: return m_enum_Source_COMPACT_DISC.get(); } } aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation LocalMediaSourceBinder::convertSupportedPlaybackOperation( JNIEnv* env, jobject obj ) { if( m_enum_SupportedPlaybackOperation_PLAY.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::PLAY; } else if( m_enum_SupportedPlaybackOperation_RESUME.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::RESUME; } else if( m_enum_SupportedPlaybackOperation_PAUSE.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::PAUSE; } else if( m_enum_SupportedPlaybackOperation_STOP.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::STOP; } else if( m_enum_SupportedPlaybackOperation_NEXT.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::NEXT; } else if( m_enum_SupportedPlaybackOperation_PREVIOUS.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::PREVIOUS; } else if( m_enum_SupportedPlaybackOperation_START_OVER.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::START_OVER; } else if( m_enum_SupportedPlaybackOperation_FAST_FORWARD.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::FAST_FORWARD; } else if( m_enum_SupportedPlaybackOperation_REWIND.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::REWIND; } else if( m_enum_SupportedPlaybackOperation_ENABLE_REPEAT.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::ENABLE_REPEAT; } else if( m_enum_SupportedPlaybackOperation_ENABLE_REPEAT_ONE.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::ENABLE_REPEAT_ONE; } else if( m_enum_SupportedPlaybackOperation_DISABLE_REPEAT.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::DISABLE_REPEAT; } else if( m_enum_SupportedPlaybackOperation_ENABLE_SHUFFLE.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::ENABLE_SHUFFLE; } else if( m_enum_SupportedPlaybackOperation_DISABLE_SHUFFLE.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::DISABLE_SHUFFLE; } else if( m_enum_SupportedPlaybackOperation_FAVORITE.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::FAVORITE; } else if( m_enum_SupportedPlaybackOperation_UNFAVORITE.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::UNFAVORITE; } else if( m_enum_SupportedPlaybackOperation_SEEK.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::SEEK; } else if( m_enum_SupportedPlaybackOperation_ADJUST_SEEK.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::ADJUST_SEEK; } else { return aace::alexa::ExternalMediaAdapter::SupportedPlaybackOperation::ADJUST_SEEK; } } aace::alexa::LocalMediaSource::Source LocalMediaSourceBinder::convertSource( JNIEnv* env, jobject obj ) { if( m_enum_Source_BLUETOOTH.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::Source::BLUETOOTH; } else if( m_enum_Source_USB.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::Source::USB; } else if( m_enum_Source_FM_RADIO.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::Source::FM_RADIO; } else if( m_enum_Source_AM_RADIO.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::Source::AM_RADIO; } else if( m_enum_Source_SATELLITE_RADIO.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::Source::SATELLITE_RADIO; } else if( m_enum_Source_LINE_IN.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::Source::LINE_IN; } else if( m_enum_Source_COMPACT_DISC.isSameObject( env, obj ) ) { return aace::alexa::LocalMediaSource::Source::COMPACT_DISC; } else { return aace::alexa::LocalMediaSource::Source::COMPACT_DISC; } } aace::alexa::ExternalMediaAdapter::MediaType LocalMediaSourceBinder::convertMediaType( JNIEnv* env, jobject obj ) { if( m_enum_MediaType_TRACK.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::MediaType::TRACK; } else if( m_enum_MediaType_PODCAST.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::MediaType::PODCAST; } else if( m_enum_MediaType_STATION.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::MediaType::STATION; } else if( m_enum_MediaType_AD.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::MediaType::AD; } else if( m_enum_MediaType_SAMPLE.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::MediaType::SAMPLE; } else if( m_enum_MediaType_OTHER.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::MediaType::OTHER; } else { return aace::alexa::ExternalMediaAdapter::MediaType::OTHER; } } aace::alexa::ExternalMediaAdapter::Favorites LocalMediaSourceBinder::convertFavorites( JNIEnv* env, jobject obj ) { if( m_enum_Favorites_FAVORITED.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::Favorites::FAVORITED; } else if( m_enum_Favorites_UNFAVORITED.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::Favorites::UNFAVORITED; } else if( m_enum_Favorites_NOT_RATED.isSameObject( env, obj ) ) { return aace::alexa::ExternalMediaAdapter::Favorites::NOT_RATED; } else { return aace::alexa::ExternalMediaAdapter::Favorites::NOT_RATED; } } // JNI #define LOCALMEDIASOURCE(cptr) ((LocalMediaSourceBinder *) cptr) extern "C" { JNIEXPORT void JNICALL Java_com_amazon_aace_alexa_LocalMediaSource_playerEvent( JNIEnv * env , jobject /* this */, jlong cptr, jstring eventName ) { LOCALMEDIASOURCE(cptr)->playerEvent( NativeLib::convert( env, eventName ) ); } JNIEXPORT void JNICALL Java_com_amazon_aace_alexa_LocalMediaSource_playerError( JNIEnv * env , jobject /* this */, jlong cptr, jstring errorName, jlong code, jstring description, jboolean fatal ) { LOCALMEDIASOURCE(cptr)->playerError( NativeLib::convert( env, errorName ), (long) code, NativeLib::convert( env, description ), fatal ); } JNIEXPORT void JNICALL Java_com_amazon_aace_alexa_LocalMediaSource_setFocus( JNIEnv * env , jobject /* this */, jlong cptr ) { LOCALMEDIASOURCE(cptr)->setFocus(); } } // END OF FILE
[ "muni.sakkuru@gmail.com" ]
muni.sakkuru@gmail.com
bcf09c9acd22055f0e1488ab28cef02619e9f60e
1f797b7f7b7160f0571a1f72ab8593c931c6753b
/Lecture-15/PrincipleOfIncAndExc.cpp
185fb0e5beaf9c52cd8f9f178231726d5ae06d54
[]
no_license
Kartik-Mathur/CareerBootcampOffline24March2020
36b8586d58746528706c899d505d351ce1f700e0
dc0ef18d43b046aefb30329a53031f64cc25dd82
refs/heads/master
2021-04-20T17:07:59.307395
2020-09-03T17:32:13
2020-09-03T17:32:13
249,703,524
8
3
null
null
null
null
UTF-8
C++
false
false
1,680
cpp
// PrincipleOfIncAndExc // Problem link : #include <iostream> #include <vector> #include <algorithm> #include <cstring> #include <map> #include <set> #include <unordered_map> #include <queue> #include <stack> #include <cmath> #include <functional> #include <deque> #include <bitset> #include <climits> #include <cstdio> #include <list> #include <iomanip> using namespace std; #define ll long long int #define mp make_pair #define pb push_back #define fi first #define si second #define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL); #define F(a,n) for(int i=0;i<n;i++){cin>>a[i];} #define F1(a,n) for(int i=1;i<=n;i++){cin>>a[i];} #define P(a,n) for(int i=0;i<n;i++){cout<<a[i]<<' ';}cout<<endl; #define P1(a,n) for(int i=1;i<=n;i++){cout<<a[i]<<' ';}cout<<endl; #define NF(a,n,m) for(int i=0;i<n;i++){for(int j=0;j<m;j++){cin>>a[i][j];}} #define NF1(a,n,m) for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){cin>>a[i][j];}} #define PNF(a,n,m) for(int i=0;i<n;i++){for(int j=0;j<m;j++){cout<<a[i][j]<<' ';}cout<<endl;}cout<<endl; #define PNF1(a,n,m) for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){cout<<a[i][j]<<' ';}cout<<endl;}cout<<endl; #define AS 200001 #define mod 1000000007 ll n; void solve(){ ll N = 7; ll primes[]={2,3,5,7,11,13,17}; ll ans = 0; for(ll i = 1 ; i < (1<<N) ; i++){ ll deno = 1; for(ll j = 0 ; j < N ; j++){ if(i&(1<<j)) deno *= primes[j]; } ll bits = __builtin_popcountll(i); if(bits&1) ans += n/deno; else ans -= n/deno; } cout<<ans<<endl; } int main(){ fastIO #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif cin>>n; solve(); return 0; }
[ "kartik.mathur10@gmail.com" ]
kartik.mathur10@gmail.com
b020348450dbf0aada749099e5d3b141689041e3
a89b1681108d4884a17ced125af9ac689c731b29
/559_2/a.cpp
9c2099bacc2cadee31bae443f043336f2f269505
[]
no_license
pkbmh/Codeforces-Solutions
6c543a47670d51b219580b583d8d6246db3b7dca
9a538e23d1e974d0637c73f53142bfe18f98846f
refs/heads/master
2020-04-30T16:51:58.996165
2020-04-22T04:15:12
2020-04-22T04:15:12
176,961,470
1
0
null
null
null
null
UTF-8
C++
false
false
4,049
cpp
// C #ifndef _GLIBCXX_NO_ASSERT #include <cassert> #endif #include <cctype> #include <cerrno> #include <cfloat> #include <ciso646> #include <climits> #include <clocale> #include <cmath> #include <csetjmp> #include <csignal> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #if __cplusplus >= 201103L #include <ccomplex> #include <cfenv> #include <cinttypes> //#include <cstdalign> #include <cstdbool> #include <cstdint> #include <ctgmath> #include <cwchar> #include <cwctype> #endif // C++ #include <algorithm> #include <bitset> #include <complex> #include <deque> #include <exception> #include <fstream> #include <functional> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <iterator> #include <limits> #include <list> #include <locale> #include <map> #include <memory> #include <new> #include <numeric> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stack> #include <stdexcept> #include <streambuf> #include <string> #include <typeinfo> #include <utility> #include <valarray> #include <vector> #if __cplusplus >= 201103L #include <array> #include <atomic> #include <chrono> #include <condition_variable> #include <forward_list> #include <future> #include <initializer_list> #include <mutex> #include <random> #include <ratio> #include <regex> #include <scoped_allocator> #include <system_error> #include <thread> #include <tuple> #include <typeindex> #include <type_traits> #include <unordered_map> #include <unordered_set> #endif using namespace std; //i/o #define SCI(a) scanf("%d", &a) #define SCLL(a) scanf("%lld", &a) #define PRI(a) printf("%d\n", a) #define PRLL(a) printf("%lld\n", a) #define gc getchar_unlocked /*void fastRead_int(int *a) { register char c=0; while (c#include<33) c=getchar_unlocked(); *a=0; while (c>33) { *a=*a*10+c-'0'; c=getchar_unlocked(); } }*/ //stl function #define F first #define S second #define PB push_back #define MP make_pair #define TR(c , it) for(typeof(c.begin()) it = c.begin(); it != c.end(); it++) #define LB(v , a) lower_bound (v.begin(), v.end(), a) #define UP(v , a) upper_bound (v.begin(), v.end(), a) #define ALL(a) a.begin() , a.end() #define RALL(a) a.rbegin(), a.rend() //data type #define LLI long long int #define LLU long long unsigned #define PII pair<int,int> #define PLLI pair<LLI,LLI> #define PDD pair<double double> #define VI vector<int> #define VF vector<float> #define VD vector<double> #define VLLI vector<LLI> #define VPII vector<PII> #define PSI pair<string,int> #define PSS pair<string,string> #define VS vector<string> #define VVI vector<vector<int> > //Initialization #define SET0(a) memset(a , 0 , sizeof(a)) #define COPY(d , s) memcpy(d , s , sizeof(s)) #define SET1(a) memset(a , 1 , sizeof(a)) #define SETN1(a) memset(a , -1 , sizeof(a)) #define FOR(i ,s, e) for(int i = s; i <= e; i++) #define RFOR(i,s, e) for(int i = s; i >= e; i--) #define LOOP(n) for(int i = 0; i < n; ++i) #define nl '\n' template<class T> void swaper(T &a , T &b) {T c = a; a = b; b = c;} template<class T> T GCD(T a , T b) {if(b == 0)return a; else return GCD(b , a%b);} template<class T> T MulMod(T a , T b , T mod) {T x,y;x = 0;y = a;while(b > 0) {if(b&1) x = (x+y)%mod; y = (y<<1)%mod;b >>= 1;}return x;} template<class T> T PowMod(T a , T b, T mod) {T x,y;x = 1;y = a;while(b > 0) {if(b&1) x = (x*y)%mod;y = (y*y)%mod;b >>= 1;}return x;} template<class T> T Multiply(T a , T b) {T x,y;x = 0;y = a;while(b > 0) {if(b&1) x = (x+y);y = (y<<1);b >>= 1;}return x;} template<class T> T Power(T a , T b) {T x,y;x = 1;y = a;while(b > 0) {if(b&1) x = (x*y);y = (y*y);b >>= 1;}return x;} const int MAX = 1e6+10; const LLI MOD7 = 1e9+7; const LLI MOD9 = 1e9+9; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; string str; cin >> str; int cnt = 0; for(char c : str) { if (c == '-') cnt--; else cnt++; if(cnt < 0) cnt = 0; } cout << cnt << endl; return 0; }
[ "pankaj.birat@shopee.com" ]
pankaj.birat@shopee.com
89e29f274db018e6189c08de626066643bf83032
de1e5905af557c6155ee50f509758a549e458ef3
/src/code/taps_treesynth.h
c59f1980cb7c61fd65330534b88c2305da61f37b
[]
no_license
alltom/taps
f15f0a5b234db92447a581f3777dbe143d78da6c
a3c399d932314436f055f147106d41a90ba2fd02
refs/heads/master
2021-01-13T01:46:24.766584
2011-09-03T23:20:12
2011-09-03T23:20:12
2,486,969
1
0
null
null
null
null
UTF-8
C++
false
false
6,815
h
/*---------------------------------------------------------------------------- TAPESTREA: Techniques And Paradigms for Expressive Synthesis, Transformation, and Rendering of Environmental Audio Engine and User Interface Copyright (c) 2006 Ananya Misra, Perry R. Cook, and Ge Wang. http://taps.cs.princeton.edu/ http://soundlab.cs.princeton.edu/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 U.S.A. -----------------------------------------------------------------------------*/ //----------------------------------------------------------------------------- // file: taps_treesynth.h // desc: taps wavelet tree synthesis // // author: Ananya Misra (amisra@cs.princeton.edu) // Perry R. Cook (prc@cs.princeton.edu) // Ge Wang (gewang@cs.princeton.edu) // date: Autumn 2004 //----------------------------------------------------------------------------- #ifndef __TREESYNTH_H__ #define __TREESYNTH_H__ // libsndfile /*#ifndef __USE_SNDFILE_PRECONF__ #include <sndfile.h> #else #include "util_sndfile.h" #endif*/ #include "ui_audio.h" // Treesynth object #include <stdlib.h> #include <time.h> #include <math.h> #include <assert.h> #include "util_daub.h" #define TS_FLOAT float #define TS_UINT unsigned int #define CUTOFF (1 << 18) #define MAX_TREE_SIZE (CUTOFF << 1) #define TS_BIG_BUFFER_SIZE CUTOFF #define TS_BIG_BUFFER_COUNT 8 #define TS_BUFFER_SIZE 2048; struct Node { TS_FLOAT * value; // Can point to value in m_values_ instead of reproducing, right? TS_UINT * cs; TS_UINT cslength; Node * parent; Node * left; Node * right; Node() {value = NULL; cs = NULL; cslength = 0; parent = NULL; left = NULL; right = NULL;} ~Node(); }; class Tree { public: Tree(); ~Tree(); bool initialize( TS_UINT levels ); // init by levels => size is power of 2 by default void shutdown(); public: inline TS_FLOAT getValue( TS_UINT level, TS_UINT offset ); inline Node * getNode( TS_UINT level, TS_UINT offset ); TS_FLOAT * values(); void setValues( TS_FLOAT * values, TS_UINT size ); // just for convenience TS_UINT getSize(); TS_UINT getLevels(); void resetLevels( TS_UINT levels ); // to change the size dynamically void zero(); // zero out m_nodes_ and m_values_ protected: Node * m_nodes_; TS_FLOAT * m_values_; TS_UINT m_size_; TS_UINT m_levels_; }; class Treesynth { public: Treesynth(); ~Treesynth(); bool initialize(); void shutdown(); double FindEpsilon( Tree * the_tree, int size, double P ); short Ancestors( int lev, int nod, int csl ); short Predecessors( int lev, int nod, int csl ); void CandidateSet(int lev, int nod ); bool setup( void ); void synth( void ); Tree * outputTree(); TS_FLOAT * outputSignal(); void resetTreeLevels( TS_UINT lev ); void resetTrees(); // the trees Tree * tree; Tree * lefttree; // treesynth knobs // If we make these private and implement a bunch of methods to set/get them, // they can always check the values before setting and be safe. float kfactor; // the thing that actually determines npredecessors bool randflip; // whether first 2 coefficients are copied in order or randomly double percentage; // percentage of nodes to be considered when learning new tree bool ancfirst; // whether learning is first done on ancestors or predecessors int startlevel; int stoplevel; // changed later in the program protected: Tree * tnew_data; Tree * tnew; TS_FLOAT * synsig; // synthesized signal bool leftinit; int npredecessors; // number of predecessors checked double epsilon; // closeness threshold; calculated from percentage int * cands; bool * in; short * S; short * L; }; enum TheReadModes { // actions RM_STOP = 0x0, RM_WRAP = 0x1, RM_BOUNCE = 0x2, RM_STATIONARY = 0x4, // directions RM_FORWARD = 0x8, RM_BACKWARD = 0x10, RM_RANDOM = 0x20, // don't or this in RM_ACTION_MASK = 0x7, RM_DIRECTION_MASK = ~RM_ACTION_MASK }; class TreesynthIO { public: // FUNKY THINGS: TreesynthIO(); ~TreesynthIO(); // actual stuff int m_audio_cb( char * buffer, int buffer_size, void * user_data ); bool audio_initialize( int (*audio_cb) (char *, int, void *), TS_UINT srate ); void set_next_pos( const char * filename ); int ReadSoundFile( char filename[], TS_FLOAT * data, int datasize ); int WriteSoundFile( char filename[], TS_FLOAT * data, int datasize ); //void clear(); // imaginary stuff? TS_UINT get_srate(); // DATA: // INPUT AND OUTPUT sound file names and info char ifilename[1024]; char ofilename[1024]; char leftfile[1024]; // INPUT reading mode int rm_mode; // OUTPUT synthesized signal size (# of samples) int nsamples; // OUTPUT whether to write to file and/or buffer (for real-time playing) bool write_to_file; bool write_to_buffer; protected: // MORE DATA: Treesynth * m_treesynth_; // just a harmless pointer... bool leftinit; // delete if not used // INPUT AND OUTPUT sound files and info SF_INFO readinfo, writeinfo; SNDFILE * sfread; SNDFILE * sfwrite; // INPUT reading position and length int rm_next_pos; int rm_next_length; // OUTPUT real-time stuff int g_write_index; int g_read_index; TS_FLOAT g_big_buffer[TS_BIG_BUFFER_COUNT][TS_BIG_BUFFER_SIZE]; int g_buffer_samples[TS_BIG_BUFFER_COUNT]; // how many samples have been written into each of the big buffers TS_FLOAT * g_audio_begin; TS_FLOAT * g_audio_end; int g_buffer_size; TS_UINT g_data_count; TS_UINT g_max_data_count; int g_ready; int g_callbacking; TS_UINT g_srate; }; // floating functions (aka internal hacks) template <class T> T our_min(T a, T b); double pow( int x, int n ); short maximum(short *array, int size); int lg( int n ); int compare( const void *arg1, const void *arg2 ); #endif
[ "tom@alltom.com" ]
tom@alltom.com
370f83f6b5bd2b5c6a24f6a1c2f82141122fb896
9125703b79eff7d9fc6a54d287992db53859758d
/questList.hh
ab01cc73cacd1bf22d28aee3a97de19d4d9d6e10
[]
no_license
Bklayman/Sidequest-Tracker
6bd75f252ed1f374bc38051338967ca053e88dad
17e779fcb5d2d8528fe81325805398bbdd670c77
refs/heads/master
2022-10-09T04:19:07.091518
2020-06-12T18:36:36
2020-06-12T18:36:36
262,599,366
1
1
null
null
null
null
UTF-8
C++
false
false
4,683
hh
#ifndef QuestList_HH_ #define QuestList_HH_ #include <vector> #include "quest.hh" class QuestList{ private: std::vector<Quest*> quests; std::vector<Quest*> questGarbage; std::vector<std::string> storyPoints; std::vector<std::string> storyPointGarbage; public: //Getter function for quests. std::vector<Quest*> getQuests(){ return quests; } //Getter function for questGarbage. std::vector<Quest*> getQuestGarbage(){ return questGarbage; } //Getter function for storyPoints. std::vector<std::string> getStoryPoints(){ return storyPoints; } //Getter function for storyPointGarbage. std::vector<std::string> getStoryPointGarbage(){ return storyPointGarbage; } //Adds a quest to quests. void addQuest(Quest* addedQuest){ quests.push_back(addedQuest); } //Adds a calue to the garbage quests void addQuestGarbage(Quest* garbage){ questGarbage.push_back(garbage); } //Moves a quest from quests to questGarbage. void removeQuest(int index){ Quest* removedQuest = quests[index]; quests.erase(quests.begin() + index); questGarbage.push_back(removedQuest); } //Adds a story point to storyPoints. void addStoryPoint(std::string addedPoint){ storyPoints.push_back(addedPoint); } //Adds a value to the garbage story points void addGarbageStoryPoint(std::string addedGarbagePoint){ storyPointGarbage.push_back(addedGarbagePoint); } //Moves a story point from storyPoints to storyPointGarbage. void removeStoryPoint(int index){ for(int i = index; i >= 0; i--){ std::string removedStoryPoint = storyPoints[i]; storyPoints.erase(storyPoints.begin() + i); storyPointGarbage.push_back(removedStoryPoint); } } //Moves a quest from questGarbage to quests. void reuseQuest(int indexToUse, int indexToAdd){ Quest* reusedQuest = questGarbage[indexToUse]; questGarbage.erase(questGarbage.begin() + indexToUse); quests.insert(quests.begin() + indexToAdd, reusedQuest); } //Moves a story point from storyPointGarbage to storyPoints. //If this story point is not the most recently deleted story point, all story points after will also be moved. void reuseStoryPoint(int indexToUse){ for(int i = storyPointGarbage.size() - 1; i >= indexToUse; i--){ std::string reusedStoryPoint = storyPointGarbage[i]; storyPointGarbage.erase(storyPointGarbage.begin() + i); storyPoints.insert(storyPoints.begin(), reusedStoryPoint); } } //Prints all information for every quest in quests. void printAll(){ for(int i = 0; i < quests.size(); i++){ quests[i]->printQuest(); std::cout << std::endl; } } //Prints all information for every avaliable quest in quests. void printOpen(){ for(int i = 0; i < quests.size(); i++){ if(quests[i]->getStoryPoint() <= storyPointGarbage.size()){ quests[i]->printQuest(); std::cout << std::endl; } } } //Prints all the story points (numbered). void printStoryPoints(){ for(int i = 0; i < storyPoints.size(); i++){ std::cout << i << ". " << storyPoints[i] << std::endl; } } //Prints the deleted story points void printStoryPointsGarbage(){ for(int i = 0; i < storyPointGarbage.size(); i++){ std::cout << i << ". " << storyPointGarbage[i] << std::endl; } } //Prints each quest's information for category. void printCategory(std::string category){ std::string notIncluded = ""; for(int i = 0; i < quests.size(); i++){ quests[i]->printQuest(category); } } //Prints quests numbered from 0 int printNumberedQuests(){ int counter = 0; for(int i = 0; i < quests.size(); i++){ std::vector<std::string> values = quests[i]->getValues(); if(values.size() > 0 && quests[i]->getStoryPoint() <= storyPointGarbage.size()){ std::cout << i << ": " << values[0] << std::endl; counter++; } else if(quests[i]->getStoryPoint() <= storyPointGarbage.size()){ quests.erase(quests.begin() + i); i--; } } return counter; } int printNumberedGarbageQuests(){ int counter = 0; for(int i = 0; i < questGarbage.size(); i++){ std::vector<std::string> values = questGarbage[i]->getValues(); if(values.size() > 0){ counter++; std::cout << i << ": " << values[0] << std::endl; } } return counter; } //Getter function for the size of story points int getStoryPointsSize(){ return storyPoints.size(); } //Getter function for the size of garbage story points int getStoryPointGarbageSize(){ return storyPointGarbage.size(); } }; #endif
[ "bklayma1@binghamton.edu" ]
bklayma1@binghamton.edu
27223aa86016b303b06a8de3b990f41dc37a7520
7622359e2e4099d24bef9ae0ac83c96ca4ac8da0
/src/Defaults.h
f4f883b86f2775a9627566d3c63bbc7315279277
[]
no_license
lingnand/Helium
23300a13dbef3d0a6ce31db92a1c2e4344374aa3
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
refs/heads/master
2023-04-04T10:44:03.009166
2021-04-16T01:48:05
2021-04-16T01:48:05
358,439,449
10
3
null
null
null
null
UTF-8
C++
false
false
724
h
/* * Defaults.h * * Created on: May 23, 2015 * Author: lingnan */ #ifndef DEFAULTS_H_ #define DEFAULTS_H_ #include <bb/cascades/TextInputFlag> #include <bb/cascades/TextContentFlag> #include <bb/cascades/TextStyle> namespace bb { namespace cascades { class Container; } } class Defaults { public: static bb::cascades::TextStyle helpText(); static bb::cascades::TextStyle hintText(); static bb::cascades::TextStyle centeredBodyText(); // flags that disable most of the prediction/correction static bb::cascades::TextInputFlag::Types codeInputFlags(); static bb::cascades::TextContentFlag::Types codeContentFlags(); static float space(); }; #endif /* DEFAULTS_H_ */
[ "lingnan.d@gmail.com" ]
lingnan.d@gmail.com
9bed35a85a04237ffcf89ad25bd030c9a2536f35
f13fc535d6324dffb3ab63ec3b5ec94e0c646809
/Code/Libraries/3D/src/D3D9/d3d9texture.h
956fd47d7b86c68f8308c55a6609707e68818314
[ "Zlib" ]
permissive
rohit-n/Eldritch
df0f2acf553b253478a71f6fe9b26b209b995fc0
b1d2a200eac9c8026e696bdac1f7d2ca629dd38c
refs/heads/master
2021-01-12T22:19:23.762253
2015-04-03T01:06:43
2015-04-03T01:06:43
18,807,726
2
0
null
null
null
null
UTF-8
C++
false
false
593
h
#ifndef D3D9TEXTURE_H #define D3D9TEXTURE_H #include "texturecommon.h" struct IDirect3DDevice9; struct IDirect3DTexture9; class D3D9Texture : public TextureCommon { public: D3D9Texture( IDirect3DDevice9* D3DDevice ); D3D9Texture( IDirect3DDevice9* D3DDevice, IDirect3DTexture9* Texture ); virtual ~D3D9Texture(); virtual void* GetHandle(); private: virtual void CreateTexture( byte* const ARGBImage ); virtual void CreateTextureFromDDS( const IDataStream& Stream ); IDirect3DTexture9* m_Texture; IDirect3DDevice9* m_D3DDevice; }; #endif // D3D9TEXTURE_H
[ "xixonia@gmail.com" ]
xixonia@gmail.com
a7e91d084eee1d680ef399edc190742bce14314c
f323895c7d347fd0f51054d8342a1223c084f614
/ipic3d/postprocessing_tools/vtk3D/convHDF5_EPAR.cpp
13b3e5ae3dddd47d94dd2d409724ae2b57a583eb
[ "Apache-2.0" ]
permissive
EPCCed/MPI_OpenMP_tasks_OmpSs
a7f44663f4c33899337774109c4e7e7179cfef16
3c02f940c22e4be5a3a2187e476810ffe87e2fda
refs/heads/master
2021-05-08T02:07:01.248796
2018-11-13T13:54:37
2018-11-13T13:54:37
107,958,643
6
0
null
null
null
null
UTF-8
C++
false
false
13,884
cpp
/* This release was prepared by Dana Akhmetova <danaak@kth.se>/<danieka@gmail.com> on behalf of the INTERTWinE European Exascale Project <http://www.intertwine-project.eu> */ /*************************************************************************** convHDF5.cpp - Convert program to open Parsek Output ------------------- begin : Jun 2008 copyright : (C) 2004 by Stefano Markidis, Giovanni Lapenta ************************************************************************** */ #include "hdf5.h" #include "Alloc.h" #include "math.h" #include <iostream> #include <fstream> #include <string> #include <sstream> using std::string; using std::stringstream; using std::ofstream; using std::cout; using std::endl; int main(int argc, char **argv) { // cycle we want to open int n_cycle; sscanf(argv[1], "%d", &n_cycle); // hdf stuff hid_t file_id; hid_t dataset_id; herr_t status; // Open the settings file file_id = H5Fopen("settings.hdf", H5F_ACC_RDWR, H5P_DEFAULT); if (file_id < 0) { cout << "couldn't open file: settings.hdf" << endl; return -1; } // First read the topology int nproc; dataset_id = H5Dopen(file_id, "/topology/Nprocs"); status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &nproc); status = H5Dclose(dataset_id); int XLEN; dataset_id = H5Dopen(file_id, "/topology/XLEN"); status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &XLEN); status = H5Dclose(dataset_id); int YLEN; dataset_id = H5Dopen(file_id, "/topology/YLEN"); status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &YLEN); status = H5Dclose(dataset_id); int ZLEN; dataset_id = H5Dopen(file_id, "/topology/ZLEN"); status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &ZLEN); status = H5Dclose(dataset_id); // read Lx double Lx; dataset_id = H5Dopen(file_id, "/collective/Lx"); status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &Lx); status = H5Dclose(dataset_id); // read Ly double Ly; dataset_id = H5Dopen(file_id, "/collective/Ly"); status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &Ly); status = H5Dclose(dataset_id); // read Lz double Lz; dataset_id = H5Dopen(file_id, "/collective/Lz"); status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &Lz); status = H5Dclose(dataset_id); // read nxc int nxc; dataset_id = H5Dopen(file_id, "/collective/Nxc"); status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &nxc); status = H5Dclose(dataset_id); // read nyc int nyc; dataset_id = H5Dopen(file_id, "/collective/Nyc"); status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &nyc); status = H5Dclose(dataset_id); // read nyc int nzc; dataset_id = H5Dopen(file_id, "/collective/Nzc"); status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &nzc); status = H5Dclose(dataset_id); // read ns int ns; dataset_id = H5Dopen(file_id, "/collective/Ns"); status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &ns); // at this point you can close settings status = H5Dclose(file_id); // prepare to read the proc files hid_t *proc_file_id = new hid_t[nproc]; string temp; int *cartesian_cor = new int[3]; int mappa[40][40][40]; for (int i = 0; i < nproc; i++) { stringstream ss; ss << i; temp = "proc" + ss.str() + ".hdf"; // temp = "proc" << ss.c_str() <<".hdf"; proc_file_id[i] = H5Fopen(temp.c_str(), H5F_ACC_RDWR, H5P_DEFAULT); if (proc_file_id[i] < 0) { cout << "couldn't open file: " << temp << endl; return -1; } // read the position in the topology dataset_id = H5Dopen(proc_file_id[i], "/topology/cartesian_coord"); status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, cartesian_cor); mappa[cartesian_cor[0]][cartesian_cor[1]][cartesian_cor[2]] = i; cout << "file" << i << " in topology[" << cartesian_cor[0] << "][" << cartesian_cor[1] << "][" << cartesian_cor[2] << "]" << endl; status = H5Dclose(dataset_id); } // open the output file stringstream cc; cc << n_cycle; // prepare the file // int nxn = nxc/XLEN + 1; // int nyn = nyc/YLEN + 1; // int nzn = nzc/ZLEN + 1; int nxn = nxc / XLEN; int nyn = nyc / YLEN; int nzn = nzc / ZLEN; double dx = Lx / nxc; double dy = Ly / nyc; double dz = Lz / nzc; // B temp = "B_cycle" + cc.str(); temp += ".vtk"; cout << "Preparing file: " << temp << endl; ofstream my_file(temp.c_str()); // E temp = "E_cycle" + cc.str(); temp += ".vtk"; cout << "Preparing file: " << temp << endl; ofstream my_fileE(temp.c_str()); // Epar temp = "Epar_cycle" + cc.str(); temp += ".vtk"; cout << "Preparing file: " << temp << endl; ofstream my_fileEpar(temp.c_str()); // Eper temp = "Eper_cycle" + cc.str(); temp += ".vtk"; cout << "Preparing file: " << temp << endl; ofstream my_fileEper(temp.c_str()); // B my_file << "# vtk DataFile Version 1.0" << endl; my_file << "Magnetic Field from Parsek" << endl; my_file << "ASCII" << endl; my_file << "DATASET STRUCTURED_GRID" << endl; my_file << "DIMENSIONS " << nxn * XLEN << " " << nyn * YLEN << " " << nzn * ZLEN << endl; my_file << "POINTS " << nxn * nyn * nzn * nproc << " float" << endl; cout << "writing to file mesh points for B" << endl; for (int kk = 0; kk < nzn * ZLEN; kk++) for (int jj = 0; jj < nyn * YLEN; jj++) for (int ii = 0; ii < nxn * XLEN; ii++) my_file << ii * dx << " " << jj * dy << " " << kk * dz << endl; my_file << endl; my_file << "POINT_DATA " << nxn * nyn * nzn * nproc << endl; my_file << "VECTORS B float" << endl; // E cout << "writing to file mesh points for E" << endl; my_fileE << "# vtk DataFile Version 1.0" << endl; my_fileE << "Electric Field from Parsek" << endl; my_fileE << "ASCII" << endl; my_fileE << "DATASET STRUCTURED_GRID" << endl; my_fileE << "DIMENSIONS " << nxn * XLEN << " " << nyn * YLEN << " " << nzn * ZLEN << endl; my_fileE << "POINTS " << nxn * nyn * nzn * nproc << " float" << endl; for (int kk = 0; kk < nzn * ZLEN; kk++) for (int jj = 0; jj < nyn * YLEN; jj++) for (int ii = 0; ii < nxn * XLEN; ii++) my_fileE << ii * dx << " " << jj * dy << " " << kk * dz << endl; my_fileE << endl; my_fileE << "POINT_DATA " << nxn * nyn * nzn * nproc << endl; my_fileE << "VECTORS E float" << endl; // Epar cout << "writing to file mesh points for Epar" << endl; my_fileEpar << "# vtk DataFile Version 1.0" << endl; my_fileEpar << "Parallel Electric Field from Parsek" << endl; my_fileEpar << "ASCII" << endl; my_fileEpar << "DATASET STRUCTURED_GRID" << endl; my_fileEpar << "DIMENSIONS " << nxn * XLEN << " " << nyn * YLEN << " " << nzn * ZLEN << endl; my_fileEpar << "POINTS " << nxn * nyn * nzn * nproc << " float" << endl; for (int kk = 0; kk < nzn * ZLEN; kk++) for (int jj = 0; jj < nyn * YLEN; jj++) for (int ii = 0; ii < nxn * XLEN; ii++) my_fileEpar << ii * dx << " " << jj * dy << " " << kk * dz << endl; my_fileEpar << endl; my_fileEpar << "POINT_DATA " << nxn * nyn * nzn * nproc << endl; my_fileEpar << "SCALARS Epar float" << endl; my_fileEpar << "LOOKUP_TABLE default" << endl; // Eper cout << "writing to file mesh points for Eper" << endl; my_fileEper << "# vtk DataFile Version 1.0" << endl; my_fileEper << "Parallel Electric Field from Parsek" << endl; my_fileEper << "ASCII" << endl; my_fileEper << "DATASET STRUCTURED_GRID" << endl; my_fileEper << "DIMENSIONS " << nxn * XLEN << " " << nyn * YLEN << " " << nzn * ZLEN << endl; my_fileEper << "POINTS " << nxn * nyn * nzn * nproc << " float" << endl; for (int kk = 0; kk < nzn * ZLEN; kk++) for (int jj = 0; jj < nyn * YLEN; jj++) for (int ii = 0; ii < nxn * XLEN; ii++) my_fileEper << ii * dx << " " << jj * dy << " " << kk * dz << endl; my_fileEper << endl; my_fileEper << "POINT_DATA " << nxn * nyn * nzn * nproc << endl; my_fileEper << "SCALARS Eper float" << endl; my_fileEper << "LOOKUP_TABLE default" << endl; // my_file << "SCALARS Bx float" << endl; // my_file << "LOOKUP_TABLE default" << endl; cout << "READING VECTOR FROM HDF5 FILES" << endl; double *temp_storageX = new double[(nxn + 1) * (nyn + 1) * (nzn + 1)]; double *temp_storageY = new double[(nxn + 1) * (nyn + 1) * (nzn + 1)]; double *temp_storageZ = new double[(nxn + 1) * (nyn + 1) * (nzn + 1)]; double ***BX = newArr3(double, nxn * XLEN, nyn * YLEN, nzn * ZLEN); double ***BY = newArr3(double, nxn * XLEN, nyn * YLEN, nzn * ZLEN); double ***BZ = newArr3(double, nxn * XLEN, nyn * YLEN, nzn * ZLEN); double ***EX = newArr3(double, nxn * XLEN, nyn * YLEN, nzn * ZLEN); double ***EY = newArr3(double, nxn * XLEN, nyn * YLEN, nzn * ZLEN); double ***EZ = newArr3(double, nxn * XLEN, nyn * YLEN, nzn * ZLEN); double Bmod; double Epar; double Eper; double Eperx; double Epery; double Eperz; int proc = 0; for (int i = 0; i < XLEN; i++) for (int j = 0; j < YLEN; j++) for (int k = 0; k < ZLEN; k++) { temp = "/fields/Bx/cycle_" + cc.str(); dataset_id = H5Dopen(proc_file_id[mappa[i][j][k]], temp.c_str()); status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, temp_storageX); temp = "/fields/By/cycle_" + cc.str(); dataset_id = H5Dopen(proc_file_id[mappa[i][j][k]], temp.c_str()); status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, temp_storageY); temp = "/fields/Bz/cycle_" + cc.str(); dataset_id = H5Dopen(proc_file_id[mappa[i][j][k]], temp.c_str()); status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, temp_storageZ); int node = 0; for (int ii = 0; ii < (nxn + 1); ii++) for (int jj = 0; jj < (nyn + 1); jj++) for (int kk = 0; kk < (nzn + 1); kk++) { if (ii != nxn && jj != nyn && kk != nzn) { BX[ii + nxn * i][jj + nyn * j][kk + nzn * k] = temp_storageX[node]; BY[ii + nxn * i][jj + nyn * j][kk + nzn * k] = temp_storageY[node]; BZ[ii + nxn * i][jj + nyn * j][kk + nzn * k] = temp_storageZ[node]; } node++; } proc++; } cout << "WRITING VECTOR B TO VTK FILE" << endl; // write to disc for (int kk = 0; kk < nzn * ZLEN; kk++) for (int jj = 0; jj < nyn * YLEN; jj++) for (int ii = 0; ii < nxn * XLEN; ii++) { my_file << BX[ii][jj][kk] << " " << BY[ii][jj][kk] << " " << BZ[ii][jj][kk] << endl; // my_file << temp_storageX[node] << " " << temp_storageY[node] << " " << temp_storageZ[node] << endl; } // write Electric field proc = 0; for (int i = 0; i < XLEN; i++) for (int j = 0; j < YLEN; j++) for (int k = 0; k < ZLEN; k++) { temp = "/fields/Ex/cycle_" + cc.str(); dataset_id = H5Dopen(proc_file_id[mappa[i][j][k]], temp.c_str()); status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, temp_storageX); temp = "/fields/Ey/cycle_" + cc.str(); dataset_id = H5Dopen(proc_file_id[mappa[i][j][k]], temp.c_str()); status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, temp_storageY); temp = "/fields/Ez/cycle_" + cc.str(); dataset_id = H5Dopen(proc_file_id[mappa[i][j][k]], temp.c_str()); status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, temp_storageZ); int node = 0; for (int ii = 0; ii < (nxn + 1); ii++) for (int jj = 0; jj < (nyn + 1); jj++) for (int kk = 0; kk < (nzn + 1); kk++) { if (ii != nxn && jj != nyn && kk != nzn) { EX[ii + nxn * i][jj + nyn * j][kk + nzn * k] = temp_storageX[node]; EY[ii + nxn * i][jj + nyn * j][kk + nzn * k] = temp_storageY[node]; EZ[ii + nxn * i][jj + nyn * j][kk + nzn * k] = temp_storageZ[node]; } node++; } proc++; } cout << "WRITING VECTOR E TO VTK FILE" << endl; for (int kk = 0; kk < nzn * ZLEN; kk++) for (int jj = 0; jj < nyn * YLEN; jj++) for (int ii = 0; ii < nxn * XLEN; ii++) { my_fileE << EX[ii][jj][kk] << " " << EY[ii][jj][kk] << " " << EZ[ii][jj][kk] << endl; // my_file << temp_storageX[node] << " " << temp_storageY[node] << " " << temp_storageZ[node] << endl; } cout << "WRITING VECTOR Epar TO VTK FILE" << endl; for (int kk = 0; kk < nzn * ZLEN; kk++) for (int jj = 0; jj < nyn * YLEN; jj++) for (int ii = 0; ii < nxn * XLEN; ii++) { Bmod = sqrt(BX[ii][jj][kk] * BX[ii][jj][kk] + BY[ii][jj][kk] * BY[ii][jj][kk] + BZ[ii][jj][kk] * BZ[ii][jj][kk]); Epar = (EX[ii][jj][kk] * BX[ii][jj][kk] + EY[ii][jj][kk] * BY[ii][jj][kk] + EZ[ii][jj][kk] * BZ[ii][jj][kk]) / Bmod; Eperx = EX[ii][jj][kk] - Epar * BX[ii][jj][kk] / Bmod; Epery = EY[ii][jj][kk] - Epar * BY[ii][jj][kk] / Bmod; Eperz = EZ[ii][jj][kk] - Epar * BZ[ii][jj][kk] / Bmod; Eper = sqrt(Eperx * Eperx + Epery * Epery + Eperz * Eperz); my_fileEpar << Epar << endl; my_fileEper << Eper << endl; } delete[]proc_file_id; delete[]temp_storageX; delete[]temp_storageY; delete[]temp_storageZ; delArr3(BX, nxn * XLEN, nyn * YLEN); delArr3(BY, nxn * XLEN, nyn * YLEN); delArr3(BZ, nxn * XLEN, nyn * YLEN); delArr3(EX, nxn * XLEN, nyn * YLEN); delArr3(EY, nxn * XLEN, nyn * YLEN); delArr3(EZ, nxn * XLEN, nyn * YLEN); my_file.close(); my_fileE.close(); my_fileEpar.close(); my_fileEper.close(); return (0); }
[ "riakymch@kth.se" ]
riakymch@kth.se
22a02bf1ee9f3ab6c6647637d44c3fcf1b291f93
3750f9e24199c13b8caff030ee600d62b55cdd1b
/Babkemon/include/mgg/babkemon/common/item/item_packet.h
7699824614e6e9ac20064547f2922cc84f9811b2
[]
no_license
orange4glace/Babkemon_Server
814f3ab600c075e2ae0bf19f515503b4ab9ef6cb
816f4f660dfdfc9c6028dcffbd9febb9d16b61fb
refs/heads/master
2021-03-27T12:41:02.573257
2017-11-19T12:17:16
2017-11-19T12:17:16
108,437,031
0
0
null
null
null
null
UTF-8
C++
false
false
676
h
// item_packet.h #ifndef MGG_BABKEMON_ITEM_ITEM_PACKET_H_ #define MGG_BABKEMON_ITEM_ITEM_PACKET_H_ #include "..\item_type.h" #include <ProudNetServer.h> namespace mgg { namespace babkemon { class Item; namespace item { struct ItemPacket { Item* item; ItemType type; int amount; // For Serialize ItemPacket(Item* const _item); // For Deserialize ItemPacket(); }; } } } namespace Proud { CMessage& operator >> (CMessage& a, mgg::babkemon::item::ItemPacket& packet); CMessage& operator << (CMessage& a, const mgg::babkemon::item::ItemPacket& packet); inline void AppendTextOut(String& str, const mgg::babkemon::item::ItemPacket& packet) {} } #endif
[ "orange4glace@gmail.com" ]
orange4glace@gmail.com
43b3d83a49b7213e7059d4a93454880e723af609
3822cd75a4a0b48c95ae2a77b09af0358ec3703a
/driver.cpp
28fedf88a3cb27c342e9607fad1e813cb1c41628
[]
no_license
mbaliyethemba/CSC3022F-Assignment-4
2d6bee32f3a88fc7c0c9837df6f1e955dc1145d7
7f8d847c479406f480a3e4bf2c2293b469c858fc
refs/heads/master
2022-11-20T00:41:56.069553
2020-05-06T01:25:06
2020-05-06T01:25:06
275,873,280
0
0
null
null
null
null
UTF-8
C++
false
false
2,819
cpp
#include "KMeansClusterer.h" #include <iostream> #include <fstream> #include <cstring> #include <sstream> #include <dirent.h> using namespace std; int main(int argc, char* argv[]){ SHNMBA004::KMeansClusterer * k = new SHNMBA004::KMeansClusterer(); std::ofstream outStream; if(argc < 2){ std::cout << "Not enough parameters" << std::endl; } else if(argc == 2){ k->ReadingList(string(argv[1]),1); k->centriod(10); k->centriodArray(); k->load_distances(); k->clusterprint(); } else if(argc == 4){ if((string(argv[2]).compare("-o")) == 0){ k->ReadingList(string(argv[1]),1); k->centriod(10); k->centriodArray(); k->load_distances(); outStream.open(string(argv[3])); outStream << k; outStream.close(); std::cout << "The outputfile has been printed" << std::endl; } else if((string(argv[2]).compare("-k")) == 0){ k->ReadingList(string(argv[1]),1); k->centriod(stoi(argv[3])); k->centriodArray(); k->load_distances(); k->clusterprint(); } else if((string(argv[2]).compare("-bin")) == 0){ k->ReadingList(string(argv[1]),stoi(argv[3])); k->centriod(10); k->centriodArray(); k->load_distances(); k->clusterprint(); } else{ std::cout << "Incorrect parameters entered" << std::endl; } } else if(argc == 6){ if((string(argv[2]).compare("-o")) == 0 && (string(argv[4]).compare("-k")) == 0){ k->ReadingList(string(argv[1]),1); k->centriod(stoi(argv[5])); k->centriodArray(); k->load_distances(); outStream.open(string(argv[3])); outStream << k; outStream.close(); std::cout << "The outputfile has been printed" << std::endl; } else if((string(argv[2]).compare("-o")) == 0 && (string(argv[4]).compare("-bin")) == 0){ k->ReadingList(string(argv[1]),stoi(argv[5])); k->centriod(10); k->centriodArray(); k->load_distances(); outStream.open(string(argv[3])); outStream << k; outStream.close(); std::cout << "The outputfile has been printed" << std::endl; } else if((string(argv[2]).compare("-k")) == 0 && (string(argv[4]).compare("-bin")) == 0){ k->ReadingList(string(argv[1]),stoi(argv[5])); k->centriod(stoi(argv[3])); k->centriodArray(); k->load_distances(); k->clusterprint(); } else{ std::cout << "Incorrect parameters entered" << std::endl; } } else if(argc == 8){ if((string(argv[2]).compare("-o")) == 0 && (string(argv[4]).compare("-k")) == 0 && (string(argv[6]).compare("-bin")) == 0 ){ k->ReadingList(string(argv[1]),stoi(argv[7])); k->centriod(stoi(argv[5])); k->centriodArray(); k->load_distances(); outStream.open(string(argv[3])); outStream << k; outStream.close(); std::cout << "The outputfile has been printed" << std::endl; } else{ std::cout << "Incorrect parameters entered" << std::endl; } } }
[ "SHNMBA004@uct.ac.za" ]
SHNMBA004@uct.ac.za
9940010de36aa4b5e8233335b9f6a03f0c9def33
f0e276cd595518a98c857b3cf9a9db95bc639d70
/udp_socket_create_mt.cpp
0af5cc704df198c22bd01277fd8b277b32277061
[]
no_license
greshem/develop_cpp
caa6fa4f07d925ff1423cab2f29684de40748eb3
4f3d4b780eed8d7d678b975c7f098f58bb3b860e
refs/heads/master
2021-01-19T01:53:15.922285
2017-10-08T07:25:35
2017-10-08T07:25:35
45,077,580
0
0
null
null
null
null
GB18030
C++
false
false
2,579
cpp
#include <algorithm> #include <arpa/inet.h> #include <fstream> #include <iostream> #include <iostream> #include <iterator> #include <map> #include <netdb.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <sys/socket.h> #include <vector> //#include <Baselib.hpp> //#include <MLmyUnit.hpp> //#include <QzjUnit.hpp> //#include <dirent.h> using namespace std; template< class T> int dump(T &in) { typedef typename T::iterator IT; IT it; for(it=in.begin(); it!= in.end(); it++) { cout<<*it<<endl; } return 1; } using namespace std; int zeor() { return 0; } int work_net() { socklen_t len; int count=0; vector<int> vecSock(100); generate(vecSock.begin(), vecSock.end(), zeor); for(vector<int>::iterator it=vecSock.begin(); it!= vecSock.end(); it++) { len=sizeof(struct sockaddr_in); int fd=socket(AF_INET, SOCK_STREAM, 0); if(fd == -1 ) { printf("socket socket %d 创建失败",count); printf("socket %d 创建失败", count); } else { *it=fd; count++; } } // dump<vector<int> > (vecSock); struct sockaddr_in addr; for(vector<int>::iterator it=vecSock.begin(); it!= vecSock.end(); it++) { memset(&addr, '\0', sizeof(addr)); addr.sin_family=AF_INET; addr.sin_port=htons(*it); addr.sin_addr.s_addr=htonl(INADDR_ANY); int ret=bind(*it, (sockaddr *) &addr, sizeof(addr)); if(ret != 0) { warn<char> ("bind %d port error", *it); printf("端口 %d 端口绑定失败", *it); } else { printf("端口 %d 端口绑定成功", *it); } } for(vector<int>::iterator it=vecSock.begin(); it!= vecSock.end(); it++) { int ret=listen(*it, 3); if(ret != 0) { printf("端口 %d 端口绑定失败", *it); } else { printf("端口 %d 端口绑定成功", *it); } } /* int cfd; while( (cfd =accept( fd, (sockaddr *)&addr, &len)) > 0 ) { while(1) { memset(buffer, '\0', sizeof(buffer)); int count=read(cfd, buffer, sizeof(buffer)); //if(count< 0) printf("%s\n", buffer); if(count<=0) { cout<<"客户端断开连接了"<<endl; break; } } }*/ return 1; } static void * __stdcall work( void *in) { int i; i=*(int *)in; //while(1) { // printf("%d\n", i); i++; work_net(); sleep(1); } } int main(int argc, char *argv[]) { MThread<char> thread; int a=100; int b=1000; thread.StartThread("test1", work, &a); thread.StartThread("test2", work, &b); // while(1) // { // sleep(1); // } return 0; }
[ "qianzhongjie@gmail.com" ]
qianzhongjie@gmail.com
b4f87ab99045bde740480c2ca44d259e305457f3
f043ea2cacdb9fff33c0995e9737d0d485867309
/BestTimeSellStock/BestTimeSellStock.cpp
8c74bcddc20b54b5337c98e41fdd6e2976fcf023
[]
no_license
jszhujun2010/LeetCode
5a863712f2968705c35902f2048d65f14c4d1a67
89fb6712a137d6a9a7f69c4d51683d1f039f2c84
refs/heads/master
2021-01-10T09:25:49.426403
2016-01-29T01:38:30
2016-01-29T01:38:30
50,625,884
0
0
null
null
null
null
UTF-8
C++
false
false
669
cpp
#include <vector> #include <iostream> using namespace std; class Solution { public: int maxProfit(vector<int>& prices) { if (prices.empty()) return 0; int min_so_far = prices[0]; int max_profit = 0; for (int i = 1; i < prices.size(); i++) { if (prices[i] < min_so_far) min_so_far = prices[i]; if ((prices[i] - min_so_far) > max_profit) max_profit = prices[i] - min_so_far; } return max_profit; } }; int main() { vector<int> prices = {5, 4, 3, 2, 1, 7, 10, 5}; Solution sln = Solution(); cout << sln.maxProfit(prices) << endl; }
[ "jszhujun2010@gmail.com" ]
jszhujun2010@gmail.com
e9b8ff1b11414319153057856c90910e88965004
9afe323ddb085bbcd9a2c78689c93715d452a11b
/arduinoToExcel.ino
1cbc25a090b18bacfa6a123cf65c89c556a3781d
[]
no_license
gsampallo/serialToExcel
36d4bea115e23caccd8e171d72f38da3309473ee
9afb0b33bfd2f25f0dce8ee94186290592e4827a
refs/heads/master
2021-07-16T01:11:27.514232
2020-08-02T19:12:29
2020-08-02T19:12:29
196,285,713
11
16
null
null
null
null
UTF-8
C++
false
false
292
ino
int sensorPin = A0; int ledPin = 13; int sensorValue = 0; void setup() { Serial.begin(115200); } int i = 0; void loop() { sensorValue = analogRead(sensorPin); Serial.print(i); Serial.print(","); Serial.print(sensorValue); Serial.println(";"); i = i + 1; delay(10); }
[ "guille@gmail.com" ]
guille@gmail.com
4b071b43d6f3055aa7053a8bc0250449d0d4334e
87276f6a96a7b884a4a1c575945a30d0babf5e38
/CodingTests/primesieve.cpp
201c210554ffff8150bd066b2daf449d358b4f00
[]
no_license
HemangMaan/CPP-DS-Algo
03a7396bad2f61983285aec7115abd7c9996c357
b98f370cdd3fef7f26cbf41aea23e159bff27750
refs/heads/master
2023-09-04T16:15:45.535812
2021-10-17T04:01:44
2021-10-17T04:01:44
305,699,621
0
0
null
null
null
null
UTF-8
C++
false
false
628
cpp
#include<bits/stdc++.h> using namespace std; #define endl "\n" void primeSieve(int n,vector<bool> &primes){ primes[0]=false; primes[1]=false; for(int i=2;i*i<=n;i++){ if(primes[i]){ for(int j=i*i;j<=n;j+=i){ primes[j]=false; } } } for(int i=0;i<n;i++){ if(primes[i]){ cout<<i<<" "; } } } int main(){ ios_base::sync_with_stdio(0); cin.tie(NULL);cout.tie(NULL); int t,tc=1; cin>>t; while(t--){ int n; cin>>n; vector<bool> primes(n,true); primeSieve(n,primes); } return 0; }
[ "hemangmaan@gmail.com" ]
hemangmaan@gmail.com
4a094aa4f2060ae0c32b353dcf4c787fb728d23e
b8ce859b04c66d6872c6ffb86d1329b30f8b4f6d
/Tempest/dx/directx9.cpp
1e2b7be5cb0f573f8633a8ee8a2194ae968615c1
[ "MIT" ]
permissive
enotio/Tempest
fc8cca311ae10b1cf7825202296cdbabec373834
1a7105cfca3669d54c696ad8188f04f25159c0a0
refs/heads/master
2023-02-04T11:38:58.829324
2020-12-26T12:49:34
2020-12-26T12:49:34
8,636,507
5
4
null
null
null
null
UTF-8
C++
false
false
35,034
cpp
#include "directx9.h" #include <Tempest/Platform> #ifdef __WINDOWS__ #include <d3d9.h> #include <d3dx9.h> #include <Tempest/HLSL> #include <Tempest/RenderState> #include <map> #include <set> #include <iostream> #include <algorithm> #include <Tempest/Pixmap> #include <Tempest/Assert> #include <Tempest/Utility> using namespace Tempest; /// \cond HIDDEN_SYMBOLS struct DirectX9::Device{ LPDIRECT3DDEVICE9 dev; DirectX9::IBO * curIBO; D3DCAPS9 caps; D3DADAPTER_IDENTIFIER9 adapter; int scrW, scrH; bool hasDepthTaget, hasStencilTaget; DWORD mkClearFlg(bool cl, bool d, bool s ){ DWORD re = 0; if( cl ) re |= D3DCLEAR_TARGET; if( d && hasDepthTaget ) re |= D3DCLEAR_ZBUFFER; if( s && hasStencilTaget ) re |= D3DCLEAR_STENCIL; return re; } }; struct DirectX9::IBO{ LPDIRECT3DINDEXBUFFER9 index; std::vector<uint16_t> pbuf; struct Min{ uint16_t val, begin, size; }; std::vector<Min> min; }; struct DirectX9::Data{ static LPDIRECT3DDEVICE9 dev( AbstractAPI::Device* d ){ return ((DirectX9::Device*)(d))->dev; } }; /// \endcond DirectX9::DirectX9(){ impl = (DirectX9Impl*)Direct3DCreate9( D3D_SDK_VERSION ); //data = new Data(); } DirectX9::~DirectX9(){ LPDIRECT3D9 dev = LPDIRECT3D9(impl); //delete data; dev->Release(); } AbstractAPI::Caps DirectX9::caps( AbstractAPI::Device *d ) const { Device *dx = (Device*)d; Caps c; memset( (char*)&c, 0, sizeof(c) ); c.maxRTCount = dx->caps.NumSimultaneousRTs; c.maxTextureSize = std::min( dx->caps.MaxTextureWidth, dx->caps.MaxTextureHeight ); c.maxVaryingVectors = 8; c.maxVaryingComponents = c.maxVaryingVectors*4; c.maxFragmentUniformVectors = 512; //FIXME c.maxVertexUniformVectors = 512; //FIXME c.hasHalf2 = 1; c.hasHalf4 = 1; c.has3DTexture = false; c.hasNpotTexture = true; return c; } std::string DirectX9::vendor( AbstractAPI::Device * ) const { return "Direct3D"; } std::string DirectX9::renderer( AbstractAPI::Device *d ) const { Device *dx = (Device*)d; return dx->adapter.Description; } AbstractAPI::Device* DirectX9::allocDevice(void *hwnd, const Options &opt) const { LPDIRECT3D9 D3D = LPDIRECT3D9(impl); D3DPRESENT_PARAMETERS d3dpp; makePresentParams( &d3dpp, hwnd, opt ); Device* dev = new Device; HRESULT derr = D3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, (HWND)hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &dev->dev ); /* IDirect3DDevice9Ex* devEx = 0; HRESULT derr = D3D->CreateDeviceEx( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, (HWND)hwnd, D3DCREATE_FPU_PRESERVE|D3DCREATE_HARDWARE_VERTEXPROCESSING, );*/ T_ASSERT_X( !FAILED(derr), "failed to create D3D-Device"); dev->dev->GetDeviceCaps( &dev->caps ); D3D->GetAdapterIdentifier( D3DADAPTER_DEFAULT, 0, &dev->adapter ); dev->hasDepthTaget = 1; dev->hasStencilTaget = 1; RECT rectWindow; GetClientRect( HWND(hwnd), &rectWindow); dev->scrW = rectWindow.right - rectWindow.left; dev->scrH = rectWindow.bottom - rectWindow.top; return (AbstractAPI::Device*)dev; } void DirectX9::makePresentParams( void * p, void *hWnd, const Options &opt ) const{ LPDIRECT3D9 D3D = LPDIRECT3D9(impl); D3DDISPLAYMODE d3ddm; D3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ); D3DPRESENT_PARAMETERS& d3dpp = *(reinterpret_cast<D3DPRESENT_PARAMETERS*>(p)); ZeroMemory( &d3dpp, sizeof(d3dpp) ); RECT rectWindow; GetClientRect( HWND(hWnd), &rectWindow); //GetSystemMetrics d3dpp.BackBufferWidth = rectWindow.right - rectWindow.left; d3dpp.BackBufferHeight = rectWindow.bottom - rectWindow.top; d3dpp.Windowed = !opt.displaySettings.fullScreen; d3dpp.BackBufferFormat = d3ddm.Format; d3dpp.EnableAutoDepthStencil = TRUE; d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; d3dpp.SwapEffect = D3DSWAPEFFECT_COPY; if( opt.vSync ) d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; else d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; if( !d3dpp.Windowed ){ d3dpp.BackBufferWidth = d3ddm.Width; d3dpp.BackBufferHeight = d3ddm.Height; d3dpp.FullScreen_RefreshRateInHz = d3ddm.RefreshRate; } if( opt.displaySettings.width>=0 ) d3dpp.BackBufferWidth = opt.displaySettings.width; if( opt.displaySettings.height>=0 ) d3dpp.BackBufferHeight = opt.displaySettings.height; } void DirectX9::freeDevice(AbstractAPI::Device *d) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); if( dev ) dev->Release(); Device* de = (Device*)(d); delete de; } void DirectX9::clear( AbstractAPI::Device *d, const Color& cl, float z, unsigned stencil ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); Device *dx = (Device*)d; dev->Clear( 0, 0, dx->mkClearFlg(1,1,1), D3DCOLOR_COLORVALUE( cl.r(), cl.g(), cl.b(), cl.a() ), z, stencil ); } void DirectX9::clear(AbstractAPI::Device *d, const Color &cl) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); Device *dx = (Device*)d; dev->Clear( 0, 0, dx->mkClearFlg(1,0,0), D3DCOLOR_COLORVALUE( cl.r(), cl.g(), cl.b(), cl.a() ), 0, 0 ); } void DirectX9::clearZ( AbstractAPI::Device *d, float z ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); Device *dx = (Device*)d; dev->Clear( 0, 0, dx->mkClearFlg(0,1,0), 0, z, 0 ); } void DirectX9::clearStencil( AbstractAPI::Device *d, unsigned s ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); Device *dx = (Device*)d; dev->Clear( 0, 0, dx->mkClearFlg(0,0,1), 0, 0, s ); } void DirectX9::clear( AbstractAPI::Device *d, float z, unsigned s ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); Device *dx = (Device*)d; dev->Clear( 0, 0, dx->mkClearFlg(0,1,1), 0, z, s ); } void DirectX9::clear( AbstractAPI::Device *d, const Color& cl, float z ) const{ LPDIRECT3DDEVICE9 dev = Data::dev(d); Device *dx = (Device*)d; dev->Clear( 0, 0, dx->mkClearFlg(1,1,0), D3DCOLOR_COLORVALUE( cl.r(), cl.g(), cl.b(), cl.a() ), z, 0 ); } void DirectX9::beginPaint( AbstractAPI::Device *d ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); dev->BeginScene(); } void DirectX9::endPaint ( AbstractAPI::Device *d ) const{ LPDIRECT3DDEVICE9 dev = Data::dev(d); dev->EndScene(); } bool DirectX9::readPixels(GraphicsSubsystem::Device *d, Pixmap &output, int rt, int x, int y, int w, int h) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DSURFACE9 surf = 0; LPDIRECT3DSURFACE9 plain = 0; D3DSURFACE_DESC desc = {}; HRESULT hr=dev->GetRenderTarget(rt,&surf); if(FAILED(hr)) return false; surf->GetDesc(&desc); if( desc.Width<=UINT(x) || desc.Height<=UINT(y) ) { surf->Release(); return false; } if( desc.Width<UINT(x+w)) w=int(desc.Width)-x; if( desc.Height<UINT(y+h)) y=int(desc.Height)-y; bool done=false; if(SUCCEEDED(dev->CreateOffscreenPlainSurface(desc.Width,desc.Height,desc.Format,D3DPOOL_SYSTEMMEM, &plain,NULL))) { RECT rect={}; rect.left =x; rect.top =y; rect.right =x+w; rect.bottom=y+h; if(SUCCEEDED(dev->GetRenderTargetData(surf,plain))) { D3DLOCKED_RECT lk ={}; HRESULT ret=plain->LockRect(&lk,&rect,D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_READONLY); if(SUCCEEDED(ret)){ done=mkImage(output,w,h,desc.Format,lk.Pitch,lk.pBits); plain->UnlockRect(); } plain->Release(); } } surf->Release(); return done; } bool DirectX9::mkImage(Pixmap &out,int w,int h,int desc, int pitch, void *praw) { const uint8_t* raw=reinterpret_cast<uint8_t*>(praw); if(desc==D3DFMT_A8R8G8B8/* || desc==D3DFMT_X8R8G8B8*/) { if(out.width()!=w || out.height()!=h || out.hasAlpha()!=true) out = Pixmap(w,h,true); uint8_t* img=reinterpret_cast<uint8_t*>(out.data()); for(int i=0;i<h;++i) for(int r=0;r<w;++r){ uint8_t* px=&img[(i*w +r)*4]; const uint8_t* in=&raw[i*pitch+r*4]; px[0]=in[2]; px[1]=in[1]; px[2]=in[0]; px[3]=in[3]; } return true; } if(desc==D3DFMT_X8R8G8B8) { if(out.width()!=w || out.height()!=h || out.hasAlpha()!=false) out = Pixmap(w,h,false); uint8_t* img=reinterpret_cast<uint8_t*>(out.data()); for(int i=0;i<h;++i) for(int r=0;r<w;++r){ uint8_t* px=&img[(i*w+r)*3]; const uint8_t* in=&raw[i*pitch+r*4]; px[0]=in[2]; px[1]=in[1]; px[2]=in[0]; } return true; } if(desc==D3DFMT_R8G8B8) { out = Pixmap(w,h,false); uint8_t* img=reinterpret_cast<uint8_t*>(out.data()); for(int i=0;i<h;++i) for(int r=0;r<w;++r){ uint8_t* px=&img[(i*w+r)*3]; const uint8_t* in=&raw[i*pitch+r*3]; px[0]=in[2]; px[1]=in[1]; px[2]=in[0]; } return true; } return false; } void DirectX9::setRenderTaget( AbstractAPI::Device *d, AbstractAPI::Texture *t, int mip, int mrtSlot ) const { T_ASSERT_X(t!=nullptr, "null render taget"); LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DTEXTURE9 tex = LPDIRECT3DTEXTURE9(t); LPDIRECT3DSURFACE9 surf = 0; tex->GetSurfaceLevel( mip, &surf); //UINT c = surf->Release(); //for (int i=0; i<16; i++) //dev->SetTexture(i, 0); HRESULT hr=dev->SetRenderTarget(mrtSlot, surf); tex->Release(); T_ASSERT(SUCCEEDED(hr)); } void DirectX9::unsetRenderTagets( AbstractAPI::Device *d, int count ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); IDirect3DSurface9* backBuf = 0; dev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuf); dev->SetRenderTarget( 0, backBuf ); backBuf->Release(); for( int i=1; i<count; ++i) dev->SetRenderTarget( i, 0 ); } AbstractAPI::StdDSSurface *DirectX9::getDSSurfaceTaget( AbstractAPI::Device *d ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DSURFACE9 surf = 0; if( FAILED(dev->GetDepthStencilSurface(&surf)) ) return 0; return (AbstractAPI::StdDSSurface*)(surf); } void DirectX9::retDSSurfaceTaget( AbstractAPI::Device *d, AbstractAPI::StdDSSurface *s ) const { Device* dev = (Device*)(d); LPDIRECT3DSURFACE9 surf = LPDIRECT3DSURFACE9(s); if( surf ) surf->Release(); dev->hasDepthTaget = 1; dev->hasStencilTaget = 1; } void DirectX9::setDSSurfaceTaget( AbstractAPI::Device *d, AbstractAPI::StdDSSurface *tx ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DSURFACE9 surf = LPDIRECT3DSURFACE9(tx); //LPDIRECT3DTEXTURE9 tex = LPDIRECT3DTEXTURE9(tx); //tex->GetSurfaceLevel( 0, &surf ); dev->SetDepthStencilSurface( surf ); { Device* dev = (Device*)(d); dev->hasDepthTaget = (surf!=nullptr); dev->hasStencilTaget = (surf!=nullptr); } //surf->Release(); } void DirectX9::setDSSurfaceTaget( AbstractAPI::Device *d, AbstractAPI::Texture *tx ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); if( tx ){ LPDIRECT3DSURFACE9 surf = 0; LPDIRECT3DTEXTURE9 tex = LPDIRECT3DTEXTURE9(tx); tex->GetSurfaceLevel( 0, &surf ); dev->SetDepthStencilSurface( surf ); tex->Release(); } else { dev->SetDepthStencilSurface(0); } { Device* dev = (Device*)(d); dev->hasDepthTaget = (tx!=nullptr); dev->hasStencilTaget = (tx!=nullptr); } } bool DirectX9::startRender(AbstractAPI::Device *d, void* /*hwnd*/, bool isLost ) const { if( isLost ){ Sleep( 100 ); LPDIRECT3DDEVICE9 dev = Data::dev(d); return (dev->TestCooperativeLevel() == D3DERR_DEVICENOTRESET); } return 1; } bool DirectX9::present(AbstractAPI::Device *d, void* /*hwnd*/, SwapBehavior /*b*/ ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); return ( D3DERR_DEVICELOST == dev->Present( NULL, NULL, NULL, NULL ) ); } bool DirectX9::reset( AbstractAPI::Device *d, void* hwnd, const Options &opt ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); D3DPRESENT_PARAMETERS d3dpp; makePresentParams( &d3dpp, hwnd, opt ); Device* dx = (Device*)d; RECT rectWindow; GetClientRect( HWND(hwnd), &rectWindow); dx->scrW = rectWindow.right - rectWindow.left; dx->scrH = rectWindow.bottom - rectWindow.top; //return 1; HRESULT hr = dev->Reset( &d3dpp ); if( FAILED(hr ) ) return 0; else return 1; } bool DirectX9::isFormatSupported( AbstractAPI::Device *, Pixmap::Format f) const { if( f==Pixmap::Format_RGB || f==Pixmap::Format_RGBA ) return 1; if( Pixmap::Format_DXT1 <=f && f<= Pixmap::Format_DXT5 ) return 1; return 0; } AbstractAPI::Texture *DirectX9::createTexture( AbstractAPI::Device *d, const Pixmap &p, bool mips, bool /*compress*/ ) const { if( p.width()==0 || p.height()==0 ) return 0; D3DLOCKED_RECT lockedRect; LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DTEXTURE9 tex = 0; static const D3DFORMAT frm[] = { D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_DXT1, D3DFMT_DXT3, D3DFMT_DXT5 }; //D3DFORMAT format = frm[p.format()]; if( !(p.format()==Pixmap::Format_RGB || p.format()==Pixmap::Format_RGBA) ){ int mipCount = 0; if( mips ){ mipCount = AbstractAPI::mipCount(p.width(),p.height()); } if (FAILED(dev->CreateTexture( p.width(), p.height(), mipCount, 0, frm[p.format()], D3DPOOL_MANAGED, &tex, NULL))) { return 0; } } else { if (FAILED(dev->CreateTexture( p.width(), p.height(), 0, D3DUSAGE_AUTOGENMIPMAP, frm[p.format()], D3DPOOL_MANAGED, &tex, NULL))) { return 0; } } if( p.format()==Pixmap::Format_RGB || p.format()==Pixmap::Format_RGBA ){ if (FAILED( tex->LockRect(0, &lockedRect, 0, 0))) { return 0; } unsigned char *dest = (unsigned char*) lockedRect.pBits; for( int i=0; i<p.width(); ++i ) for( int r=0; r<p.height(); ++r ){ unsigned char * t = &dest[ 4*(i + r*p.width()) ]; const Pixmap::Pixel s = p.at(i, p.height()-r-1 ); t[2] = s.r; t[1] = s.g; t[0] = s.b; t[3] = s.a; } tex->UnlockRect(0); if( mips ) tex->GenerateMipSubLevels(); } else { int nBlockSize = 16; if( p.format() == Pixmap::Format_DXT1 ) nBlockSize = 8; const unsigned char *mipData = p.const_data(); int w = p.width(), h = p.height(); for(int i=0; w>1 || h>1; ++i ){ if (FAILED( tex->LockRect(i, &lockedRect, 0, 0))) { return 0; } int nSize = ((w+3)/4) * ((h+3)/4) * nBlockSize; memcpy( lockedRect.pBits, mipData, nSize ); tex->UnlockRect(0); if( w>1 ) w/=2; if( h>1 ) h/=2; mipData += nSize; if( !mips ){ return ((AbstractAPI::Texture*)tex); } } } //data->tex.insert( tex ); return ((AbstractAPI::Texture*)tex); } AbstractAPI::Texture *DirectX9::recreateTexture( AbstractAPI::Device *d, const Pixmap &p, bool mips, bool compress, AbstractAPI::Texture *oldT ) const { if( oldT==0 ) return createTexture(d, p, mips, compress); D3DLOCKED_RECT lockedRect; LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DTEXTURE9 tex = 0; LPDIRECT3DTEXTURE9 old = LPDIRECT3DTEXTURE9(oldT); static const D3DFORMAT frm[] = { D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_DXT1, D3DFMT_DXT3, D3DFMT_DXT5 }; D3DSURFACE_DESC desc; if( FAILED( old->GetLevelDesc(0, &desc) ) ){ deleteTexture(d, oldT); return 0; } if( int(desc.Width)==p.width() && int(desc.Height)==p.height() && desc.Format==frm[p.format()] ){ tex = old; } else { deleteTexture(d, oldT); if( !(p.format()==Pixmap::Format_RGB || p.format()==Pixmap::Format_RGBA) ){ int mipCount = 0; if( mips ){ mipCount = AbstractAPI::mipCount(p.width(), p.height()); } if (FAILED(dev->CreateTexture( p.width(), p.height(), mipCount, 0, frm[p.format()], D3DPOOL_MANAGED, &tex, NULL))) { return 0; } } else { if (FAILED(dev->CreateTexture( p.width(), p.height(), 0, D3DUSAGE_AUTOGENMIPMAP, frm[p.format()], D3DPOOL_MANAGED, &tex, NULL))) { return 0; } } } if( p.format()==Pixmap::Format_RGB || p.format()==Pixmap::Format_RGBA ){ if (FAILED( tex->LockRect(0, &lockedRect, 0, 0))) { return 0; } int bpp = 3; if( p.format()==Pixmap::Format_RGBA ) bpp = 4; unsigned char *dest = (unsigned char*) lockedRect.pBits; const unsigned char *src = p.const_data(); for( int i=0; i<p.width(); ++i ) for( int r=0; r<p.height(); ++r ){ unsigned char * t = &dest[ 4*(i + r*p.width()) ]; const unsigned char * s = &src[ bpp*(i + (p.height()-r-1)*p.width()) ]; /* const Pixmap::Pixel s = p.at(i,r); t[2] = s.r; t[1] = s.g; t[0] = s.b; t[3] = s.a;*/ t[2] = s[0]; t[1] = s[1]; t[0] = s[2]; t[3] = (bpp==4)?s[3]:255; } tex->UnlockRect(0); if( mips ) tex->GenerateMipSubLevels(); } else { int nBlockSize = 16; if( p.format() == Pixmap::Format_DXT1 ) nBlockSize = 8; const unsigned char *mipData = p.const_data(); int w = p.width(), h = p.height(); for(int i=0; w>1 || h>1; ++i ){ if (FAILED( tex->LockRect(i, &lockedRect, 0, 0))) { return 0; } int nSize = ((w+3)/4) * ((h+3)/4) * nBlockSize; memcpy( lockedRect.pBits, mipData, nSize ); tex->UnlockRect(0); if( w>1 ) w/=2; if( h>1 ) h/=2; mipData += nSize; if( !mips ){ return ((AbstractAPI::Texture*)tex); } } } //data->tex.insert( tex ); return ((AbstractAPI::Texture*)tex); } AbstractAPI::Texture* DirectX9::createTexture(AbstractAPI::Device *d, int w, int h, bool mips, AbstractTexture::Format::Type f, TextureUsage u ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DTEXTURE9 tex = 0; static const DWORD usage[] = { D3DUSAGE_RENDERTARGET, D3DUSAGE_RENDERTARGET, D3DUSAGE_DYNAMIC, 0 }; static const D3DFORMAT d3frm[] = { D3DFMT_L16, // Luminance, D3DFMT_A4L4, // Luminance4, D3DFMT_L8, // Luminance8, D3DFMT_L16, // Luminance16, D3DFMT_R8G8B8, // RGB, D3DFMT_X4R4G4B4, // RGB4, D3DFMT_R5G6B5, // RGB5, D3DFMT_A2B10G10R10, // RGB10, D3DFMT_A2B10G10R10, // RGB12, D3DFMT_A2B10G10R10, // RGB16, D3DFMT_A8R8G8B8, // RGBA, D3DFMT_A1R5G5B5, // RGBA5, D3DFMT_A8R8G8B8, // RGBA8, D3DFMT_A2B10G10R10, // RGB10_A2, D3DFMT_A2B10G10R10, // RGBA12, D3DFMT_A16B16G16R16, // RGBA16, D3DFMT_DXT1, // RGB_DXT1, D3DFMT_DXT3, // RGBA_DXT1, D3DFMT_DXT3, // RGBA_DXT3, D3DFMT_DXT5, // RGBA_DXT5, D3DFMT_D16, // Depth16, D3DFMT_D24X8, // Depth24, D3DFMT_D32, // Depth32, D3DFMT_G16R16,// RG16 D3DFMT_D16, // RedableDepth16, D3DFMT_D32, // RedableDepth32, D3DFMT_A8R8G8B8, //Count }; if( f==AbstractTexture::Format::Depth16 || f==AbstractTexture::Format::Depth24 || f==AbstractTexture::Format::Depth32 ){ HRESULT hr = D3DXCreateTexture( dev, w, h, 1, D3DUSAGE_DEPTHSTENCIL,//usage[u], d3frm[f], D3DPOOL_DEFAULT, &tex ); if( FAILED( hr ) ){ return 0; } return ((AbstractAPI::Texture*)tex); } else { int ww = std::max(w,h)/2, mipsc = 1; while( mips && ww>1 ){ ww/=2; ++mipsc; } if( FAILED( D3DXCreateTexture( dev, w, h, mipsc, usage[u], d3frm[f], D3DPOOL_DEFAULT, &tex ) ) ){ return 0; } //data->tex.insert( tex ); return ((AbstractAPI::Texture*)tex); } } AbstractAPI::Texture* DirectX9::createTexture3d( AbstractAPI::Device *d, int x, int y, int z, bool mips, AbstractTexture::Format::Type f, TextureUsage usage, const char *data ) const { T_WARNING_X(0, "unimplemented yet"); return 0; } void DirectX9::generateMipmaps(AbstractAPI::Device *, AbstractAPI::Texture *t) const { //LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)t; tex->GenerateMipSubLevels(); } void DirectX9::deleteTexture( AbstractAPI::Device *, AbstractAPI::Texture *t ) const { IUnknown *tex = (IUnknown*)(t); if( tex ){ /*ULONG count = */tex->Release(); //std::cout << "DirectX9::deleteTexture " << count << std::endl; } } AbstractAPI::VertexBuffer* DirectX9::createVertexBuffer( AbstractAPI::Device *d, size_t size, size_t elSize, BufferUsage /*usage*/) const{ LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DVERTEXBUFFER9 vbo = 0; int c = 100; // avoid false out of memory alarm while( !vbo && c>0 ){ if( FAILED( dev->CreateVertexBuffer( UINT(size*elSize), D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, &vbo, 0 ) ) ){ T_ASSERT(0); vbo = 0; } --c; } return ((AbstractAPI::VertexBuffer*)vbo); } void DirectX9::deleteVertexBuffer( AbstractAPI::Device *, AbstractAPI::VertexBuffer*v ) const{ LPDIRECT3DVERTEXBUFFER9 vbo = LPDIRECT3DVERTEXBUFFER9(v); if( vbo ) vbo->Release(); } AbstractAPI::IndexBuffer* DirectX9::createIndexBuffer( AbstractAPI::Device *d, size_t size, size_t elSize, BufferUsage /*usage*/ ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DINDEXBUFFER9 index = 0; int c = 100; // avoid false out of memory alarm while( !index && c>0 ){ if( FAILED( dev->CreateIndexBuffer( UINT(size*elSize), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &index, 0 ) ) ){ T_ASSERT(0); index = 0; } --c; } if( index==0 ) return 0; IBO * ibo = new IBO(); ibo->pbuf.reserve( size ); ibo->pbuf.resize( size ); ibo->index = index; return ((AbstractAPI::IndexBuffer*)ibo); } void DirectX9::deleteIndexBuffer( AbstractAPI::Device *, AbstractAPI::IndexBuffer* b) const { IBO* ibo = (IBO*)(b); if( ibo && ibo->index ) ibo->index->Release(); delete ibo; } void* DirectX9::lockBuffer( AbstractAPI::Device *, AbstractAPI::VertexBuffer * v, unsigned offset, unsigned /*size*/ ) const { LPDIRECT3DVERTEXBUFFER9 vbo = LPDIRECT3DVERTEXBUFFER9(v); void* pVertices = 0; T_ASSERT( vbo->Lock( 0, 0, &pVertices, 0 )==D3D_OK ); return (char*)pVertices+offset; } void DirectX9::unlockBuffer( AbstractAPI::Device *, AbstractAPI::VertexBuffer* v) const { LPDIRECT3DVERTEXBUFFER9 vbo = LPDIRECT3DVERTEXBUFFER9(v); vbo->Unlock(); } void* DirectX9::lockBuffer( AbstractAPI::Device *, AbstractAPI::IndexBuffer * v, unsigned offset, unsigned /*size*/) const { IBO* ibo = (IBO*)(v); char* ptr = (char*)&ibo->pbuf[0]; return ptr+offset; } void DirectX9::unlockBuffer( AbstractAPI::Device *, AbstractAPI::IndexBuffer* v) const { IBO* ibo = (IBO*)(v); void *pIBO = 0; size_t byteSize = ibo->pbuf.size()*sizeof(ibo->pbuf[0]); T_ASSERT( ibo->index->Lock( 0, 0, &pIBO, 0 )==D3D_OK ); if(pIBO) memcpy(pIBO, &ibo->pbuf[0], byteSize ); ibo->index->Unlock(); ibo->min.clear(); } AbstractShadingLang *DirectX9::createShadingLang( AbstractAPI::Device *d ) const { AbstractAPI::DirectX9Device* dev = (AbstractAPI::DirectX9Device*)reinterpret_cast<DirectX9::Device*>(d)->dev; return new HLSL( dev ); } void DirectX9::deleteShadingLang( const AbstractShadingLang * l ) const { delete l; } AbstractAPI::VertexDecl * DirectX9::createVertexDecl( AbstractAPI::Device *d, const VertexDeclaration::Declarator &de ) const { BYTE ct[] = { D3DDECLTYPE_FLOAT1, D3DDECLTYPE_FLOAT2, D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT4, D3DDECLTYPE_D3DCOLOR, D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT4, D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_4 }; BYTE usage[] = { D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT, // 1 D3DDECLUSAGE_BLENDINDICES, // 2 D3DDECLUSAGE_NORMAL, // 3 D3DDECLUSAGE_PSIZE, // 4 D3DDECLUSAGE_TEXCOORD, // 5 D3DDECLUSAGE_TANGENT, // 6 D3DDECLUSAGE_BINORMAL, // 7 D3DDECLUSAGE_TESSFACTOR, // 8 D3DDECLUSAGE_POSITIONT, // 9 D3DDECLUSAGE_COLOR, // 10 D3DDECLUSAGE_FOG, // 11 D3DDECLUSAGE_DEPTH, // 12 D3DDECLUSAGE_SAMPLE, // 13 }; /* D3DVERTEXELEMENT9 declaration[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, 20, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, D3DDECL_END() };*/ std::vector<D3DVERTEXELEMENT9> decl; for( int i=0; i<de.size(); ++i ){ D3DVERTEXELEMENT9 e; e.Stream = 0; e.Offset = 4*de[i].component; e.Type = ct[ de[i].component-1 ]; if( de[i].component==Decl::color ) e.Offset = 4; if( de[i].component==Decl::short2 || de[i].component==Decl::half2 ) e.Offset = 4; if( de[i].component==Decl::short4 || de[i].component==Decl::half4 ) e.Offset = 8; e.Method = D3DDECLMETHOD_DEFAULT; e.Usage = usage[ de[i].usage ]; e.UsageIndex = de[i].index; decl.push_back(e); } for( size_t i=1; i<decl.size(); ++i ){ decl[i].Offset += decl[i-1].Offset; } if( decl.size() ){ for( size_t i=decl.size()-1; i>=1; --i ){ decl[i].Offset = decl[i-1].Offset; } decl[0].Offset = 0; } D3DVERTEXELEMENT9 endEl = D3DDECL_END(); decl.push_back( endEl ); // cgD3D9ValidateVertexDeclaration( g_CGprogram_vertex, declaration ); LPDIRECT3DVERTEXDECLARATION9 ret = 0; LPDIRECT3DDEVICE9 dev = Data::dev(d); HRESULT hr = dev->CreateVertexDeclaration( decl.data(), &ret ); if( FAILED(hr) ){ T_ASSERT(0); } return reinterpret_cast<AbstractAPI::VertexDecl*>(ret); } void DirectX9::deleteVertexDecl( AbstractAPI::Device *, AbstractAPI::VertexDecl* de ) const { LPDIRECT3DVERTEXDECLARATION9 decl = LPDIRECT3DVERTEXDECLARATION9(de); if( decl ) decl->Release(); } void DirectX9::setVertexDeclaration( AbstractAPI::Device *d, AbstractAPI::VertexDecl* de, size_t ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); LPDIRECT3DVERTEXDECLARATION9 decl = LPDIRECT3DVERTEXDECLARATION9(de); dev->SetFVF(0); dev->SetVertexDeclaration( decl ); } void DirectX9::bindVertexBuffer(AbstractAPI::Device *d, AbstractAPI::VertexBuffer* b, size_t vsize ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); HRESULT re = dev->SetStreamSource( 0, LPDIRECT3DVERTEXBUFFER9(b), 0, vsize ); T_ASSERT(re==D3D_OK); } void DirectX9::bindIndexBuffer( AbstractAPI::Device * d, AbstractAPI::IndexBuffer * b ) const { LPDIRECT3DDEVICE9 dev = Data::dev(d); HRESULT re = dev->SetIndices( ((IBO*)(b))->index ); ((Device*)d)->curIBO = (IBO*)(b); T_ASSERT(re==D3D_OK); } void DirectX9::draw( AbstractAPI::Device *d, AbstractAPI::PrimitiveType t, int firstVertex, int pCount ) const { LPDIRECT3DDEVICE9 dev = Data::dev( d ); static const D3DPRIMITIVETYPE type[] = { D3DPT_POINTLIST,// = 1, D3DPT_LINELIST,// = 2, D3DPT_LINESTRIP,// = 3, D3DPT_TRIANGLELIST,// = 4, D3DPT_TRIANGLESTRIP,// = 5, D3DPT_TRIANGLEFAN,// = 6 }; //int vpCount = vertexCount(t, pCount); dev->DrawPrimitive( type[ t-1 ], firstVertex, pCount ); } void DirectX9::drawIndexed( AbstractAPI::Device *d, AbstractAPI::PrimitiveType t, int vboOffsetIndex, int iboOffsetIndex, int pCount ) const { Device *dev = (Device*)( d ); static const D3DPRIMITIVETYPE type[] = { D3DPT_POINTLIST,// = 1, D3DPT_LINELIST,// = 2, D3DPT_LINESTRIP,// = 3, D3DPT_TRIANGLELIST,// = 4, D3DPT_TRIANGLESTRIP,// = 5, D3DPT_TRIANGLEFAN,// = 6 }; int vpCount = vertexCount(t, pCount); uint16_t minID = -1; for( size_t i=0; i<dev->curIBO->min.size(); ++i ){ IBO::Min& m = dev->curIBO->min[i]; if( m.begin==iboOffsetIndex && m.size==vpCount ) minID = m.val; } if( minID == uint16_t(-1) ){ IBO::Min m; m.begin = iboOffsetIndex; m.size = vpCount; m.val = *std::min_element( dev->curIBO->pbuf.begin()+iboOffsetIndex, dev->curIBO->pbuf.begin()+iboOffsetIndex+vpCount ); minID = m.val; dev->curIBO->min.push_back(m); } dev->dev->DrawIndexedPrimitive( type[ t-1 ], vboOffsetIndex, minID, vpCount, iboOffsetIndex, pCount ); } Size DirectX9::windowSize( Tempest::AbstractAPI::Device *d) const { Device *dev = (Device*)( d ); return Size(dev->scrW, dev->scrH); } void DirectX9::setRenderState( AbstractAPI::Device *d, const RenderState & r) const { LPDIRECT3DDEVICE9 dev = Data::dev( d ); static const D3DCULL cull[] = { D3DCULL_NONE, D3DCULL_CW, D3DCULL_CCW }; static const D3DCMPFUNC cmp[] = { D3DCMP_NEVER, D3DCMP_GREATER, D3DCMP_LESS, D3DCMP_GREATEREQUAL, D3DCMP_LESSEQUAL, D3DCMP_NOTEQUAL, D3DCMP_EQUAL, D3DCMP_ALWAYS, D3DCMP_ALWAYS }; dev->SetRenderState( D3DRS_CULLMODE, cull[ r.cullFaceMode() ]); dev->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE ); D3DCMPFUNC f = cmp[ r.getZTestMode() ] ; if( !r.isZTest() ) f = D3DCMP_ALWAYS; dev->SetRenderState( D3DRS_ZFUNC, f ); dev->SetRenderState( D3DRS_ZWRITEENABLE, r.isZWriting() ); if( r.alphaTestMode()!=RenderState::AlphaTestMode::Always ){ dev->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE ); dev->SetRenderState( D3DRS_ALPHAFUNC, cmp[ r.alphaTestMode() ] ); dev->SetRenderState( D3DRS_ALPHAREF, DWORD(255*r.alphaTestRef()) ); } else { dev->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE ); } static const D3DBLEND blend[] = { D3DBLEND_ZERO, //zero, //GL_ZERO, D3DBLEND_ONE, //one, //GL_ONE, D3DBLEND_SRCCOLOR, //src_color, //GL_SRC_COLOR, D3DBLEND_INVSRCCOLOR, //GL_ONE_MINUS_SRC_COLOR, D3DBLEND_SRCALPHA, //GL_SRC_ALPHA, D3DBLEND_INVSRCALPHA, //GL_ONE_MINUS_SRC_ALPHA, D3DBLEND_DESTALPHA, //GL_DST_ALPHA, D3DBLEND_INVDESTALPHA, //GL_ONE_MINUS_DST_ALPHA, D3DBLEND_DESTCOLOR, //GL_DST_COLOR, D3DBLEND_INVDESTCOLOR, //GL_ONE_MINUS_DST_COLOR, D3DBLEND_SRCALPHASAT, //GL_SRC_ALPHA_SATURATE, D3DBLEND_ZERO }; if( r.isBlend() ){ dev->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); dev->SetRenderState( D3DRS_SRCBLEND, blend[ r.getBlendSFactor() ] ); dev->SetRenderState( D3DRS_DESTBLEND, blend[ r.getBlendDFactor() ] ); } else { dev->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); } bool w[4]; r.getColorMask( w[0], w[1], w[2], w[3] ); DWORD flg = 0; if( w[0] ) flg |= D3DCOLORWRITEENABLE_RED; if( w[1] ) flg |= D3DCOLORWRITEENABLE_GREEN; if( w[2] ) flg |= D3DCOLORWRITEENABLE_BLUE; if( w[3] ) flg |= D3DCOLORWRITEENABLE_ALPHA; dev->SetRenderState( D3DRS_COLORWRITEENABLE, flg ); D3DFILLMODE fm[3] = { D3DFILL_SOLID, D3DFILL_WIREFRAME, D3DFILL_POINT }; dev->SetRenderState( D3DRS_FILLMODE, fm[ r.frontPolygonRenderMode() ] ); } #endif
[ "try9998@gmail.com" ]
try9998@gmail.com
d8f9091487129bcfe5308563a826909d7e940d21
7b00100a6f4f7eb33fd8a1ddea88fa226169c1b4
/DoAnGame/Leaf.h
c0347a32fafc6b5a8b77a043e4c11b998a897f02
[]
no_license
DonMartialMinh/DoAnGame
3e0eb8f780f8eca58e34128abd04a6bae23053e8
6ae25a341bcb3ff21efb4eea1e781d63e2d7ab70
refs/heads/master
2023-07-02T00:55:26.539295
2021-08-17T03:58:11
2021-08-17T03:58:11
300,098,147
0
0
null
null
null
null
UTF-8
C++
false
false
707
h
#pragma once #include "GameObject.h" #include "Game.h" #include "Board.h" #define LEAF_BBOX_WIDTH 16 #define LEAF_BBOX_HEIGHT 14 #define LEAF_FALL_RIGHT 0 #define LEAF_FALL_LEFT 1 #define LEAF_FALL_SPEED_VX 0.04f #define LEAF_FALL_SPEED_VY 0.02f #define LEAF_RISING_TIME 500 #define LEAF_STATE_FALLING 100 class CLeaf : public CGameObject { virtual void Update(DWORD dt, vector<LPGAMEOBJECT>* coObjects); virtual void GetBoundingBox(float& l, float& t, float& r, float& b); virtual void Render(); float xMax = 0; float xMin = 0; DWORD rise_start; int rising = 0; public: CLeaf(float x); void StartRising() { rising = 1; rise_start = DWORD(GetTickCount64()); } void SetState(int state); };
[ "43954674+fueledbyramental@users.noreply.github.com" ]
43954674+fueledbyramental@users.noreply.github.com
4a9a5dedac6ec759fdbbc0b42761a29fa91e6fc9
58a0ba5ee99ec7a0bba36748ba96a557eb798023
/Olympiad Solutions/URI/1285.cpp
3a92eed235e7d7e5c89a00454364a1d79c7b7a1d
[ "MIT" ]
permissive
adityanjr/code-DS-ALGO
5bdd503fb5f70d459c8e9b8e58690f9da159dd53
1c104c33d2f56fe671d586b702528a559925f875
refs/heads/master
2022-10-22T21:22:09.640237
2022-10-18T15:38:46
2022-10-18T15:38:46
217,567,198
40
54
MIT
2022-10-18T15:38:47
2019-10-25T15:50:28
C++
UTF-8
C++
false
false
506
cpp
// Ivan Carvalho // Solution to https://www.urionlinejudge.com.br/judge/problems/view/1285 #include <cstdio> #include <cstring> int soma[6000]; int checa(int x){ int freq[11]; memset(freq,0,sizeof(freq)); while(x > 0){ freq[x%10]++; x /= 10; } for(int i=0;i<=9;i++){ if(freq[i] >= 2){ return 0; } } return 1; } int main(){ for(int i=1;i<=5000;i++){ soma[i] = soma[i-1] + checa(i); } int n,m; while(scanf("%d %d",&n,&m) != EOF){ printf("%d\n",soma[m] - soma[n-1]); } return 0; }
[ "samant04aditya@gmail.com" ]
samant04aditya@gmail.com
92702df4e708bb06878c9ac4e044afbc996f074a
a9566a402d1c0e178af3218f29fe55f42644ebb8
/folly/experimental/logging/test/PrintfTest.cpp
1f7fbe1e1aa36d780b24e3f927d85d2020e2ecb8
[ "Apache-2.0" ]
permissive
monad-one/folly
b8a84e27456ffc1e3bdbbd4958f15ba00d01b83b
98d1077ce0603b0713353d638cb1436a28827af6
refs/heads/master
2021-05-11T20:34:29.501635
2018-01-13T07:57:16
2018-01-13T08:05:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,644
cpp
/* * Copyright 2004-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/experimental/logging/printf.h> #include <folly/experimental/logging/test/TestLogHandler.h> #include <folly/portability/GTest.h> using namespace folly; using std::make_shared; TEST(PrintfTest, printfStyleMacros) { LoggerDB db{LoggerDB::TESTING}; Logger logger{&db, "test"}; auto* category = logger.getCategory(); auto handler = make_shared<TestLogHandler>(); category->addHandler(handler); category->setLevel(LogLevel::DBG, true); Logger foo{&db, "test.foo.bar"}; Logger foobar{&db, "test.foo.bar"}; Logger footest{&db, "test.foo.test"}; Logger footest1234{&db, "test.foo.test.1234"}; Logger other{&db, "test.other"}; db.setLevel("test", LogLevel::ERR); db.setLevel("test.foo", LogLevel::DBG2); db.setLevel("test.foo.test", LogLevel::DBG7); auto& messages = handler->getMessages(); // test.other's effective level should be ERR, so a warning // message to it should be discarded FB_LOGC(other, WARN, "this should be discarded: %d", 5); ASSERT_EQ(0, messages.size()); // Disabled log messages should not evaluate their arguments bool argumentEvaluated = false; auto getValue = [&] { argumentEvaluated = true; return 5; }; FB_LOGC(foobar, DBG3, "discarded message: %d", getValue()); EXPECT_FALSE(argumentEvaluated); FB_LOGC(foobar, DBG1, "this message should pass: %d", getValue()); ASSERT_EQ(1, messages.size()); EXPECT_EQ("this message should pass: 5", messages[0].first.getMessage()); EXPECT_TRUE(argumentEvaluated); messages.clear(); // The FB_LOGC() macro should work even if the format string does not contain // any format sequences. Ideally people would just use FB_LOG() if they // aren't actually formatting anything, but making FB_LOGC() work in this // scenario still makes it easier for people to switch legacy printf-style // code to FB_LOGC(). FB_LOGC(foobar, DBG1, "no actual format arguments"); ASSERT_EQ(1, messages.size()); EXPECT_EQ("no actual format arguments", messages[0].first.getMessage()); messages.clear(); // Similar checks with XLOGC() auto* xlogCategory = XLOG_GET_CATEGORY(); xlogCategory->addHandler(handler); xlogCategory->setLevel(LogLevel::DBG5, true); argumentEvaluated = false; XLOGC(DBG9, "failing log check: %d", getValue()); EXPECT_FALSE(argumentEvaluated); XLOGC(DBG5, "passing log: %03d", getValue()); ASSERT_EQ(1, messages.size()); EXPECT_EQ("passing log: 005", messages[0].first.getMessage()); EXPECT_TRUE(argumentEvaluated); messages.clear(); XLOGC(DBG1, "no xlog format arguments"); ASSERT_EQ(1, messages.size()); EXPECT_EQ("no xlog format arguments", messages[0].first.getMessage()); messages.clear(); // Errors attempting to format the message should not throw FB_LOGC(footest1234, ERR, "width overflow: %999999999999999999999d", 5); ASSERT_EQ(1, messages.size()); EXPECT_EQ( "error formatting printf-style log message: " "width overflow: %999999999999999999999d", messages[0].first.getMessage()); messages.clear(); }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
534423dabf81d5a617630e6616c3e3d4baba49ea
a0bf0dc827d621b2cc0616dd2439736faec442ed
/Misc/ArrayReversal.cpp
15494e7623600e73f104d78e1cc426dc4d178e66
[]
no_license
anuragbisht/Cpp
b4fd50a95b53374ffec061e08bf5c0c08b250c37
44033a24bc77f98031f137159e5e3eddb2bbf5aa
refs/heads/master
2021-06-20T01:31:14.150186
2021-01-11T18:08:01
2021-01-11T18:08:01
167,524,073
0
0
null
null
null
null
UTF-8
C++
false
false
671
cpp
#include <iostream> void reverseArrayUsingIteration(int array[], int sizeOfArray); void printArray(int array[], int sizeOfArray); int main(){ int array[10] = {1,2,3,4,5,6,7,8,9,10}; reverseArrayUsingIteration(array, 10); printArray(array, 10); return 0; } void reverseArrayUsingIteration(int array[], int sizeOfArray){ int left = 0; int right = sizeOfArray-1; while(left < right){ int temp = array[left]; array[left] = array[right]; array[right] = temp; left++; right--; } } void printArray(int array[], int sizeOfArray){ for(int i = 0; i < sizeOfArray; ++i ){ std::cout<<array[i]; } }
[ "admfav2012@gmail.com" ]
admfav2012@gmail.com
3fbebc9ba42b5972cb3365cc4799e62cabf211f9
b31a0ecd63f5b12e564bb6190e4bfd8b9e9eb889
/u06_new/test4.cpp
a9486303617d1f5e742b926669a932feccb3a001
[]
no_license
shmhlove/CPPIntermediate
99f5a7f509aa143ed7cf9821666d0f2b5f2283e0
02057f5741a520e90ee7d4c4b2a044a9ac5095f3
refs/heads/master
2020-06-04T00:31:25.806841
2019-07-12T20:38:29
2019-07-12T20:38:29
191,796,215
0
0
null
null
null
null
UTF-8
C++
false
false
730
cpp
/* 빌드 하는 법 g++ test1.cpp cl test2.cpp /nologo /EHsc 주의! VC++ 확장 문법 사용을 사용해야함. /Za 옵션을 사용하면 컴파일 안됨 */ #include <stdio.h> #include <iostream> using namespace std; class Point { private: int x, y; public: Point(int a, int b) : x(a), y(b) { printf("Point(%d, %d)\n", x, y); } ~Point() { printf("~Point()\n"); } }; int main() { int iMaxObject = 10; Point* p1 = static_cast<Point*>(operator new(sizeof(Point) * iMaxObject)); for (int iLoop = 0; iLoop < iMaxObject; ++iLoop) { new(&p1[iLoop]) Point(iLoop, iLoop); } for (int iLoop = 0; iLoop < iMaxObject; ++iLoop) { p1[iLoop].~Point(); } operator delete(p1); }
[ "shmhlove@naver.com" ]
shmhlove@naver.com
efaf1cd4ca0a975d7b1507e3180e7682c2f2ffbd
717b1f3b6073b97a0953722f177e66c0befa79e8
/include/game/SystemComponent.hpp
7b8610484f1b3110c636f5319446a221d173a74e
[]
no_license
Lehdari/ECSTestGame
969ccb14c7b4fd0a01f66923a68709237e7b07af
db1ef9fc62f84c9c3a555ae3fbe061e9a2a08de1
refs/heads/master
2020-04-04T14:41:17.343473
2019-06-20T19:57:47
2019-06-29T15:50:27
156,008,318
0
0
null
2019-06-29T15:50:28
2018-11-03T17:43:08
C++
UTF-8
C++
false
false
807
hpp
// // Created by Lehdari on 17.4.2019. // #ifndef ECSTESTGAME_SYSTEMCOMPONENT_HPP #define ECSTESTGAME_SYSTEMCOMPONENT_HPP #include <Ecs.hpp> #include <engine/EventSystem.hpp> #include <engine/LogicSystem.hpp> #include <game/PhysicsSystem.hpp> #include <game/SpriteRenderer.hpp> #include <game/CollisionSystem.hpp> #include <memory> /// SystemComponent is a singleton component containing all the systems used struct SystemComponent { std::unique_ptr<PhysicsSystem> physicsSystem; std::unique_ptr<SpriteRenderer> spriteRenderer; std::unique_ptr<CollisionSystem> collisionSystem; std::unique_ptr<EventSystem> eventSystem; std::unique_ptr<LogicSystem> logicSystem; }; DECLARE_COMPONENT_TEMPLATES(SystemComponent); #endif //ECSTESTGAME_SYSTEMCOMPONENT_HPP
[ "aapo.vienamo@iki.fi" ]
aapo.vienamo@iki.fi
92f60fba34516a27ae54db6e9bbd380674669034
e8b0e4004449f5149dafe9a8bfc5996e4b33637e
/Surface/Implicit/Operator/AIntersection.cpp
d424aa99a88d42f37075fc75bb80f5c03ddbaa71
[]
no_license
benardp/Wickbert
3259ee4c0129769cf1e2a4aed587d2465beb4e77
73f72b160945f9c4f5cc91e55941bf85836276d2
refs/heads/master
2020-03-13T13:32:19.900393
2018-05-04T11:18:18
2018-05-04T11:18:18
131,140,762
2
0
null
null
null
null
UTF-8
C++
false
false
200
cpp
/** * @file AIntersection.cpp * Surface Modeling Library * CS497 * * @author William Nagel and John C. Hart */ #include "ABlend.h" REGISTER_IMPLICIT(AIntersection,"BinaryOp:AIntersection");
[ "pierre.g.benard@inria.fr" ]
pierre.g.benard@inria.fr
21174a6523353442f080a7f2afdedc47176f023f
6b64f647cb11e5e36f7fd9fc10790b3ef42f54ba
/fail.cpp
37b5e55c25df2668fa66772153268d648712233e
[]
no_license
forflo/bugReproductionPackage02
e7ceb5cdd4730b61b517a0b8d66856d0dcc2b32e
c01d33347575d3decc1e361d9507899627c3bb57
refs/heads/master
2020-07-06T23:20:29.968927
2019-08-19T12:44:20
2019-08-19T12:44:20
203,170,105
0
0
null
null
null
null
UTF-8
C++
false
false
906
cpp
#include "rose.h" #include <iostream> #include <sstream> int main(int argc, char **argv) { SgProject *project = frontend(argc, argv); std::cout << "content of project->get_includeDirectorySpecifierList()" << std::endl; project->initialization(); auto il = project->get_includeDirectorySpecifierList(); std::for_each(std::begin(il), std::end(il), [](auto &i) { std::cout << i << std::endl; }); std::cout << "content of project->get_includePathList()" << std::endl; auto ip = project->get_includePathList(); std::for_each(std::begin(ip), std::end(ip), [](auto &i) { std::cout << i << std::endl; }); std::cout << "content of project->get_includeFileList()" << std::endl; auto if_ = project->get_includeFileList(); std::for_each(std::begin(if_), std::end(if_), [](auto &i) { std::cout << i << std::endl; }); return 0; }
[ "florian.andrefranc.mayer@fau.de" ]
florian.andrefranc.mayer@fau.de
0d209d02ba8a0150a2ccb689f3e8784f736a9341
5f7f7fb66c95025a154007d90df0ea3e7a73c24a
/ForwardingCenter/mysql_connect.h
256d0529b20dfd7c083943aa6a260a604094eb77
[]
no_license
blank-black/NAS-Data-transfer-center
76b6a4e61bd8d161030f7b1a5f3247f0c7013de2
4ee33e676cb7ca0db4d6b8172a34117ab1ccbae7
refs/heads/master
2021-09-02T06:47:42.581385
2017-12-31T06:02:03
2017-12-31T06:02:03
114,733,438
3
0
null
null
null
null
UTF-8
C++
false
false
787
h
//mysql_connect.h #include <iostream> #include <mysql.h> using namespace std; #define HOST "10.60.102.252" #define USERNAME "G1551265" #define PASSWORD "G1551265" #define DATABASE "G1551265" int save_nasid(string id) { MYSQL *mysql; string str = "INSERT INTO nas_user VALUES ('"+id+"')"; if ((mysql = mysql_init(NULL)) == NULL) { cout << "mysql_init failed" << endl; return -1; } if (mysql_real_connect(mysql, HOST, USERNAME, PASSWORD, DATABASE, 0, NULL, 0) == NULL) { cout << "mysql_real_connect failed(" << mysql_error(mysql) << ")" << endl; return -1; } mysql_set_character_set(mysql, "gbk"); if (mysql_query(mysql, str.c_str())) { cout << "mysql_query failed(" << mysql_error(mysql) << ")" << endl; return -1; } mysql_close(mysql); return 0; }
[ "wy98926@gmail.com" ]
wy98926@gmail.com
20831c2f7c34e82af1bb49adfb93a297509c09e2
b2d70bc01464859761817522e6e4ef157b6bfda6
/Study/Leetcode/Medium/Split Linked List in Parts.cpp
8f4a4d9568e450846db9150a048e11a2b1f0cd83
[]
no_license
ben-jnr/competitive-coding
a1b65b72db73a7b9322281ca9e788937ac71eb31
4e3bcd90b593749aa29228c54a211bf0da75501a
refs/heads/main
2023-08-26T07:43:10.018640
2021-10-27T13:50:08
2021-10-27T13:50:08
273,961,346
5
0
null
null
null
null
UTF-8
C++
false
false
1,193
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: vector<ListNode*> splitListToParts(ListNode* head, int k) { int count = 0; vector<ListNode*> ans; ListNode* node = head; while(node != NULL) { count++; node = node->next; } int i,extra=1; node = head; for(i=0;i<k;i++) { ListNode* prev = NULL; ListNode* start = NULL; if(i>=count%k) extra=0; for(int j=0; j<(count/k)+extra; j++) { ListNode* temp = new ListNode(node->val); if(prev == NULL) { prev = temp; start = temp; } else { prev->next = temp; prev = temp; } node=node->next; } ans.push_back(start); } return(ans); } };
[ "bichubenkuruvilla@gmail.com" ]
bichubenkuruvilla@gmail.com
01cff689e992c164f8c66998f07f98f0e2a90014
30e454af4970ecb2798ec45e48f2462ae25b8d56
/3/test.cpp
91e9dc9672328775aa31da0c467bcfb973e3c9a2
[]
no_license
espilya/ed
b23794cfbc52460706a6d833896e9cd37b27a189
576eeada29d1f9bd4eef4d7f730ca55612c442f6
refs/heads/master
2022-11-12T01:26:09.642430
2020-07-03T21:43:30
2020-07-03T21:43:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
#include <iostream> #include <vector> #include <climits> #include "complejos.h" #include <algorithm> using namespace std; int main() { int numT; while (cin >> numT && numT != 0) { Pelicula temp; vector<Pelicula> pelis; for (int i = 0; i < numT; i++) { cin >> temp; pelis.push_back(temp); pelis[i].calcFin(); } sort(pelis.begin(), pelis.end()); for (int i = 0; i < numT; i++) { cout << pelis[i]; } cout << "---\n"; } return 0; }
[ "espilya@gmail.com" ]
espilya@gmail.com
dacbb50855347010816fc9ee0c2365fbf335fd78
5be08a041fa9c019337f2187813a4f54108e6e2d
/GUI/Output.h
ba3a68307154685925a243ff15b8689a84faa1e7
[]
no_license
AymanAzzam/Paint-for-Kids
ae8c647b7ffb64ad87dd2a78be3a3bf15ebfc5c9
66ac8c7f24f881175fb505ed468e7055b313b5e5
refs/heads/master
2020-08-10T02:38:52.562643
2019-10-10T17:53:02
2019-10-10T17:53:02
214,212,999
0
0
null
null
null
null
UTF-8
C++
false
false
1,669
h
#ifndef OUPTUT_H #define OUPTUT_H #include "Input.h" class Output //The application manager should have a pointer to this class { private: string status; window* pWind; //Pointer to the Graphics Window void drawToolBar(string dir, int i = 0) const; void clearToolBar() const; void read_directory(string, vector<string> &) const; public: Output(); window* CreateWind(int, int, int, int) const; //creates the application window void CreateDrawToolBar() const; //creates Draw mode toolbar & menu void CreatePlayToolBar() const; //creates Play mode toolbar & menu void drawCurrentToolBar() const; void CreateStatusBar() const; //create the status bar Input* CreateInput() const; //creates a pointer to the Input object void ClearStatusBar(); //Clears the status bar void ClearDrawArea() const; //Clears the drawing area // -- Figures Drawing functions void DrawRect(Point P1, Point P2, GfxInfo RectGfxInfo, bool selected = false) const; //Draw a rectangle void DrawLine(Point p1, Point p2, GfxInfo linegfxinfo, bool selsected = false) const; void DrawTriangle(Point p1, Point p2, Point p3, GfxInfo trianglegfxinfo, bool selected = false) const; void DrawCircle(Point P1, int R, GfxInfo circleGfxInfo, bool selected = false) const; ///Make similar functions for drawing all other figures. void PrintMessage(string msg); //Print a message on Status bar void refreshStatus(); color getCrntDrawColor() const; //get current drwawing color color getCrntFillColor() const; //get current filling color int getCrntPenWidth() const; //get current pen width void drawColorPalette(); ~Output(); }; #endif
[ "aymanazzam63@gmail.com" ]
aymanazzam63@gmail.com
cde49897cf4f9da08d4293bc1536e150053241d1
af8e87266bc5589be606eefd2c5cffc095e9d2b6
/Language/Problem16/main.cpp
4a4bedfb12df60877e379be7f2bd578bb5814dd3
[ "MIT" ]
permissive
zsef123/ModernCppChallengeStudy
03298ef98e2832ba2286840a29d9717d4dcf45b2
058c0a6c5e41758f53336e554f29b497c9881fae
refs/heads/master
2020-04-01T08:38:55.933351
2018-12-01T03:50:36
2018-12-01T03:50:36
153,040,572
0
0
MIT
2018-10-15T02:14:34
2018-10-15T02:14:34
null
UTF-8
C++
false
false
1,183
cpp
#include <gsl/gsl> #include "../Problem15/IPv4.cpp" /* Enumerating IPv4 addresses in a range Write a program that allows the user to input two IPv4 addresses representing a range and list all the addresses in that range. Extend the structure defined for the previous problem to implement the requested functionality. */ void test_incremental(IPv4 x) { printf("###############\n"); printf("Increment test\n"); printf("x : "); x.writeToConsole(); printf("x++ : "); (x++).writeToConsole(); printf("++x : "); (++x).writeToConsole(); printf("###############\n"); } void test_compare(IPv4 a, IPv4 b) { ++b; printf("Compare Test\n"); printf("a : "); a.writeToConsole(); printf("b : "); b.writeToConsole(); printf("(a > b) : %d, (a < b) : %d", (a > b), (a < b)); } int main(int argc, char* argv[]) { IPv4 ip_big, ip_small; printf("1st input : "); ip_big.readFromConsole(); printf("2nd input : "); ip_small.readFromConsole(); if (ip_small > ip_big) { IPv4 tmp = ip_small; ip_small = ip_big; ip_big = tmp; } while (ip_small < ip_big) (++ip_small).writeToConsole(); return 0; }
[ "zsef123@gmail.com" ]
zsef123@gmail.com
9f55c8135d39d0196eab2e11f3bd5f2cd65949a6
721b81ef1453012640242785e28ed589a0180435
/URI/2246.cpp
7f27115d7dc4cb1c7702148452d01869d03fbd80
[]
no_license
tyronedamasceno/CompetitiveProgramming
f2bd21813b6e29ab19fa5bb36b42cc6a309bb41d
7bf2d74fe2ac075996c9120a49c03e13e5b165e4
refs/heads/master
2020-04-22T02:34:41.434554
2016-09-23T19:31:16
2016-09-23T19:31:16
66,939,413
0
0
null
null
null
null
UTF-8
C++
false
false
1,266
cpp
/* MARATONA SBC - 2016 PROBLEMA L */ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <int> vi; typedef pair <int, int> ii; typedef vector <ii> vii; typedef map <int, int> mii; typedef map <string, int> msi; #define pb push_back #define mp make_pair #define F first #define S second #define clr(a, k) memset(a, k, sizeof(a)) #define rep(i, a, b) for(int i = a; i < b; i++) #define in1(a) scanf("%d", &a) #define in2(a, b) scanf("%d %d", &a, &b) #define in3(a, b, c) scanf("%d %d %d", &a, &b, &c) int h, l, cont; int m[205][205]; int vis[205][205]; vi v; void dfs(int i, int j) { if (!vis[i][j]) { vis[i][j] = 1; if (j < l-1 && m[i][j] == m[i][j+1] && !vis[i][j+1]) { cont++; dfs(i, j+1); } if (j > 0 && m[i][j] == m[i][j-1] && !vis[i][j-1]) { cont++; dfs(i, j-1); } if (i < h-1 && m[i][j] == m[i+1][j] && !vis[i+1][j]) { cont++; dfs(i+1, j); } if (i > 0 && m[i][j] == m[i-1][j] && !vis[i-1][j]) { cont++; dfs(i-1, j); } } } int main() { cin >> h >> l; rep(i, 0, h) rep(j, 0, l) cin >> m[i][j]; rep(i, 0, h) rep(j, 0, l) if (!vis[i][j]) { cont = 1; dfs(i, j); v.pb(cont); } sort(v.begin(), v.end()); cout << v[0] << endl; return 0; }
[ "tyronedamasceno@gmail.com" ]
tyronedamasceno@gmail.com
d382e0d018d200b9416d4de62efd5f40287663cc
15106e71a62f8bd87479f0631be5b136b55a5569
/PathSumII.cpp
32c6ade32fc7f20b12990261f546d31b449eb7ef
[]
no_license
edgar-323/leetcode
e38ed0d9ea1a6d65c69cdb5552c1cdb5a6d70a6c
6e09b388662124326263d97790a2a148de97e5a4
refs/heads/master
2020-07-15T14:51:42.448172
2020-01-22T17:58:02
2020-01-22T17:58:02
205,587,568
0
0
null
null
null
null
UTF-8
C++
false
false
1,679
cpp
/* Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 Return: [ [5,4,11,2], [5,8,4,5] ] */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: std::vector<std::vector<int>> results; int S; void recurse1(const TreeNode* node, const int sum, std::vector<int>& stack) { const auto left = node->left; const auto right = node->right; const int new_sum = sum + node->val; stack.push_back(node->val); if (not left and not right) { if (new_sum == S) { results.push_back(stack); } } if (not right) { recurse1(left, new_sum, stack); } else if (not left) { recurse1(right, new_sum, stack); } else { recurse1(left, new_sum, stack); recurse1(right, new_sum, stack); } stack.pop_back(); } std::vector<std::vector<int>> solution1(TreeNode* root, const int sum) { if (not root) { return {}; } results.clear(); S = sum; auto stack = std::vector<int>(); recurse1(root, 0, stack); return results; } public: vector<vector<int>> pathSum(TreeNode* root, int sum) { return solution1(root, sum); } };
[ "edgarbarboza@Edgars-MBP.lan1" ]
edgarbarboza@Edgars-MBP.lan1
a3d8cadeb91bcca29b30adeffe853f869646c6f9
7557a09ce9dafc7fa1b029076286574724355da9
/test.cpp
e93e1f3e0f19bf84752bb882b14aaa9c89ee334d
[]
no_license
Icay12/Video-Segment-RT
b73c0dde30a2418714a9ceb94f28c54da3535ec7
fd234ac5d6d7d0b8f9971692a59eeb984aadc9a9
refs/heads/master
2021-01-01T03:48:30.385433
2016-05-24T11:42:55
2016-05-24T11:42:55
59,566,053
0
0
null
null
null
null
UTF-8
C++
false
false
9,477
cpp
#include <cmath> #include <cstdlib> #include <iostream> #include <time.h> #include <string> #include <unistd.h> #include <pthread.h> #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #define e 10 #define FRAME_NUM 100 #define NN 999 //3 bit decimal using namespace std; using namespace cv; extern "C" { extern int dgeqrf_(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); extern int dorgqr_(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info); } class MatQueue{ public: int h,t; bool first; Mat q[FRAME_NUM]; MatQueue():h(0),t(-1),first(1){} void add(Mat& x){ t=(t+1)%FRAME_NUM; q[t]=x.clone(); if (first) first=0; else if (t==h) h=(h+1)%FRAME_NUM; } void reset(){ h=0; t=-1; first=1; } void getVideoMatrix(Mat& videoMatrix){ int ii = 0, n = 0; // Current column in img for (int k=h;k!=t;k=(k+1)%FRAME_NUM){ ii=0; for (int i = 0; i<q[k].rows; i++) { for (int j = 0; j < q[k].cols; j++) { videoMatrix.at<double>(ii++,n) = q[k].at<uchar>(i,j); } } n++; //cerr<<"x "<<k<<" "<<n<<endl; } reset(); } } frameQueue; int height=120,width=160; volatile bool calc_start=0; volatile bool save_frame=1; volatile bool start_sub=0; Mat bg(height,width,CV_8UC1),bg_f(height,width,CV_64FC1); int isCamera; void MatToArray(Mat& X, double* array) { int m = X.rows; int n = X.cols; double* X_line; for(int i = 0; i < m; ++i) { X_line = (double*)(X.data+i*X.step); for(int j = 0; j < n; ++j) { array[i+j*m] = X_line[j]; } } } void ArrayToMat(Mat& X, double* array) { int m = X.rows; int n = X.cols; double* X_line; for(int i = 0; i < m; ++i) { X_line = (double*)(X.data+i*X.step); for(int j = 0; j < n; ++j) { X_line[j] = array[i+j*m]; } } } void qr( double* Q, double* R, double* A, int m, int n) { int row; // Maximal rank is used by Lapacke int rank = m > n ? n : m; // Tmp Array for Lapacke double* tau = (double*)malloc(sizeof(double)*rank ); // Calculate QR factorisations int info = 0; int lwork = -1; int lda=m; double iwork; dgeqrf_(&m, &n, A, &lda, tau, &iwork, &lwork, &info); lwork = (int)iwork; double* work = (double*)malloc(sizeof(double)*lwork); dgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info); free(work); // Copy the upper triangular Matrix R (rank x _n) into position for(row =0; row < rank; ++row) { memset(R+row*n, 0, row*sizeof(double)); // Set starting zeros memcpy(R+row*n+row, A+row*n+row, (n-row)*sizeof(double)); // Copy upper triangular part from Lapack result. } // Create orthogonal matrix Q (in tmpA) info = 0; lwork = -1; //double iwork; dorgqr_(&m, &rank, &rank, A, &m, tau, &iwork, &lwork, &info); lwork = (int)iwork; //double* work = (double*)malloc(sizeof(double)*lwork); dorgqr_(&m, &rank, &rank, A, &m, tau, work, &lwork, &info); free(work); //Copy Q (_m x rank) into position memcpy(Q, A, sizeof(double)*(m*n)); } void sign(Mat& x,Mat& y) { int m = x.rows; int n = x.cols; int i,j; //Mat y(m,n,CV_64FC1); double* x_line; double* y_line; for(i = 0; i < m; ++i) { x_line = (double*)(x.data+i*x.step); y_line = (double*)(y.data+i*y.step); for(j = 0; j < n; ++j) { double s = x_line[j]; y_line[j] = s > 0 ? 1 : (s < 0? -1:0); } } //return y; } void dotMul(Mat& x, Mat& y) { int m = x.rows; int n = x.cols; int i,j; double* x_line; double* y_line; for(i = 0; i < m; ++i) { x_line = (double*)(x.data+i*x.step); y_line = (double*)(y.data+i*y.step); for(j = 0; j < n; ++j) { y_line[j] = x_line[j]*y_line[j]; } } } void wthresh(Mat& x, Mat& y, int t) { Mat tmp = abs(x) - t; tmp = (tmp + abs(tmp))/ 2; sign(x,y); dotMul(tmp,y); } double SSGoDec(const Mat& X, Mat& L, Mat& S, int m, int n, int rank, int tau, int power) { double iter_max = 100; double error_bound = 0.001; int iter = 1; ///RMSE double RMSE; L = X.clone(); Mat tmp(Mat::zeros(m,n, CV_64FC1)); S = tmp.clone(); //S while(1) { ///Y2=randn(n,rank); Mat Y2(n,rank,CV_64FC1); Mat mean = cv::Mat::zeros(1,1,CV_64FC1); Mat sigma= cv::Mat::ones(1,1,CV_64FC1); randn(Y2, mean, sigma); Mat Y1(m,rank,CV_64FC1); for(int i=0; i <= power; ++i) { Y1 = L * Y2; Y2 = L.t() * Y1; } double* Qarr = (double*)malloc(sizeof(double)*n*rank); double* Rarr = (double*)malloc(sizeof(double)*rank*rank); double Y2arr[n*rank];// = (double*)(Y2.data); MatToArray(Y2, Y2arr); qr(Qarr, Rarr, Y2arr, n, rank); Mat Q(n,rank,CV_64FC1); ArrayToMat(Q, Qarr); Mat L_new = (L*Q) * Q.t(); //Update of S Mat T = L - L_new + S; L = L_new.clone(); /* for(int i=0; i < Q.rows; ++i) { for(int j=0; j < Q.cols;++j) { double t = Q.at<double>(i,j); printf("%4.4lf ",t); } cout<<endl; } */ //Soft thresholding wthresh(T,S,tau); T = T - S; ///RMSE=[RMSE norm(T(:))]; Mat tmpT = T.reshape(0,T.rows*T.cols); RMSE = norm(tmpT,NORM_L2,noArray()); if(RMSE < error_bound || iter > iter_max) //if(iter > iter_max) break; else L = L+T; ++iter; Mat tmpS = S.reshape(0,S.rows*S.cols); double Snorm = norm(tmpS,NORM_L2,noArray()); cerr<<"Iter : "<<iter<<endl; cerr<<"RMSE : "<<RMSE<<endl; cerr<<"Snorm : "<<Snorm<<endl; /* if (iter%10==2){ Mat L_out, S_out; L.convertTo(L_out,CV_8UC1); S.convertTo(S_out,CV_8UC1); getOriginalMatrix(L_out,"bg"); getOriginalMatrix(S_out,"fg"); } */ } Mat LS = L + S; Mat tmpLS = LS.reshape(0, LS.rows*LS.cols); Mat tmpX = X.reshape(0, X.rows*X.cols); double error = norm(tmpLS-tmpX,NORM_L2,noArray()) / norm(tmpX,NORM_L2,noArray()); cout << "GoDec end" <<endl; return error; } void filter(Mat& x){ int m = x.rows; int n = x.cols; int i,j; double* x_line; for(i = 0; i < m; ++i) { x_line = (double*)(x.data+i*x.step); for(j = 0; j < n; ++j) { if (fabs(x_line[j])<10) x_line[j]=0; } } } void videoHandler(){ VideoCapture cap; int frameNum = FRAME_NUM; if(isCamera) { cap.open(0); cap.set(CV_CAP_PROP_FRAME_WIDTH, width); cap.set(CV_CAP_PROP_FRAME_HEIGHT, height); } else { cap.open("hall.avi"); //int num = cap.get(CV_CAP_PROP_FRAME_COUNT); //frameNum = frameNum > num ? num : frameNum; } if(!cap.isOpened()) { printf("\nCan not open camera or video file\n"); system("PAUSE"); exit(0); } Mat img, img2, img_f, G, G_out; namedWindow("X",1); namedWindow("L",1); namedWindow("G",1); int cnt=0; char s[10]; while (1) { cap >> img; if(img.empty()) break; cnt++; cvtColor(img,img,CV_BGR2GRAY); // RGB to GRAY resize(img,img2,Size(160,120)); imshow("X",img2); if (start_sub){ imshow("L",bg); img2.convertTo(img_f,CV_64FC1); G=img_f-bg_f; filter(G); normalize(G, G_out, 0, 255, NORM_MINMAX, CV_8UC1, Mat()); //equalizeHist(G_norm, G_out); imshow("G",G_out); //return; } char c = (char)waitKey(50); if(c == 27) // quit after ESC break; cerr << "cnt : "<<cnt <<endl; if (save_frame) frameQueue.add(img2); if (cnt==FRAME_NUM) calc_start=1;// return;} if (start_sub && cnt<2000){ sprintf(s,"res/%d_X.jpg",cnt); imwrite(s,img2); sprintf(s,"res/%d_L.jpg",cnt); imwrite(s,bg); sprintf(s,"res/%d_G.jpg",cnt); imwrite(s,G_out); } } } int main(void) { pthread_t vhid; isCamera=1; pthread_create(&vhid,NULL,(void* (*)(void*))videoHandler,NULL); //cerr << "here 1"<<endl; while (!calc_start){} //cerr << "here 2"<<endl; Mat X(width*height,FRAME_NUM,CV_64FC1); Mat L(width*height,FRAME_NUM,CV_64FC1); Mat S(width*height,FRAME_NUM,CV_64FC1); while (1){ //cerr << "here 3"<<endl; save_frame = 0; frameQueue.getVideoMatrix(X); save_frame = 1; double tau = 8; //cerr << "here 4"<<endl; double err = SSGoDec(X,L,S,height*width,FRAME_NUM,1,8,0); cout << "Err : " << err << endl; start_sub = 0; for (int i = 0; i<L.rows; i++) bg_f.at<double>(i/width,i%width) = L.at<double>(i,FRAME_NUM/2); bg_f.convertTo(bg,CV_8UC1); //imwrite("bg.jpg", bg ); //cerr << "here 5"<<endl; //break; start_sub = 1; } return 0; }
[ "mymaiill@163.com" ]
mymaiill@163.com