DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.

DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (c68fe15a81fc)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "CompositorD3D11.h"


#include "TextureD3D11.h"

#include "gfxWindowsPlatform.h"
#include "nsIWidget.h"
#include "Layers.h"
#include "Layers.h"
#include "mozilla/gfx/D3D11Checks.h"
#include "mozilla/gfx/DeviceManagerDx.h"
#include "mozilla/gfx/GPUParent.h"
#include "mozilla/gfx/Swizzle.h"
#include "mozilla/layers/ImageHost.h"
#include "mozilla/layers/ContentHost.h"
#include "mozilla/layers/Diagnostics.h"
#include "mozilla/layers/DiagnosticsD3D11.h"
#include "mozilla/layers/Effects.h"
#include "mozilla/layers/Effects.h"
#include "mozilla/layers/HelpersD3D11.h"
#include "nsWindowsHelpers.h"
#include "gfxConfig.h"
#include "gfxCrashReporterUtils.h"
#include "gfxUtils.h"
#include "gfxUtils.h"
#include "mozilla/gfx/StackArray.h"
#include "mozilla/widget/WinCompositorWidget.h"

#include "mozilla/EnumeratedArray.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_layers.h"
#include "mozilla/Telemetry.h"
#include "BlendShaderConstants.h"

#include "D3D11ShareHandleImage.h"
#include "D3D11ShareHandleImage.h"
#include "DeviceAttachmentsD3D11.h"

#include <versionhelpers.h>  // For IsWindows8OrGreater
#include <winsdkver.h>


namespace mozilla {

using namespace gfx;

namespace layers {
namespace layers {

bool CanUsePartialPresents(ID3D11Device* aDevice);

const FLOAT sBlendFactor[] = {0, 0, 0, 0};


class AsyncReadbackBufferD3D11 final : public AsyncReadbackBuffer {
 public:
  AsyncReadbackBufferD3D11(ID3D11DeviceContext* aContext,
                           ID3D11Texture2D* aTexture, const IntSize& aSize);

  bool MapAndCopyInto(DataSourceSurface* aSurface,
                      const IntSize& aReadSize) const override;

  ID3D11Texture2D* GetTexture() { return mTexture; }
  ID3D11Texture2D* GetTexture() { return mTexture; }

 private:
  RefPtr<ID3D11DeviceContext> mContext;
  RefPtr<ID3D11Texture2D> mTexture;
};


AsyncReadbackBufferD3D11::AsyncReadbackBufferD3D11(
    ID3D11DeviceContext* aContext, ID3D11Texture2D* aTexture,
    const IntSize& aSize)
    : AsyncReadbackBuffer(aSize), mContext(aContext), mTexture(aTexture) {}


bool AsyncReadbackBufferD3D11::MapAndCopyInto(DataSourceSurface* aSurface,
                                              const IntSize& aReadSize) const {
  D3D11_MAPPED_SUBRESOURCE map;
  HRESULT hr = mContext->Map(mTexture, 0, D3D11_MAP_READ, 0, &map);

  if (FAILED(hr)) {
    return false;
    return false;
  }

  RefPtr<DataSourceSurface> sourceSurface =
      Factory::CreateWrappingDataSourceSurface(static_cast<uint8_t*>(map.pData),
                                               map.RowPitch, mSize,
                                               map.RowPitch, mSize,
                                               SurfaceFormat::B8G8R8A8);

  bool result;
  {
    DataSourceSurface::ScopedMap sourceMap(sourceSurface,
    DataSourceSurface::ScopedMap sourceMap(sourceSurface,
                                           DataSourceSurface::READ);
    DataSourceSurface::ScopedMap destMap(aSurface, DataSourceSurface::WRITE);

    result = SwizzleData(sourceMap.GetData(), sourceMap.GetStride(),
                         SurfaceFormat::B8G8R8A8, destMap.GetData(),
                         SurfaceFormat::B8G8R8A8, destMap.GetData(),
                         destMap.GetStride(), aSurface->GetFormat(), aReadSize);
  }

  mContext->Unmap(mTexture, 0);


  return result;
}

CompositorD3D11::CompositorD3D11(CompositorBridgeParent* aParent,
CompositorD3D11::CompositorD3D11(CompositorBridgeParent* aParent,
                                 widget::CompositorWidget* aWidget)
    : Compositor(aWidget, aParent),
    : Compositor(aWidget, aParent),
      mWindowRTCopy(nullptr),
      mAttachments(nullptr),
      mHwnd(nullptr),
      mDisableSequenceForNextFrame(false),
      mAllowPartialPresents(false),
      mAllowPartialPresents(false),
      mIsDoubleBuffered(false),
      mVerifyBuffersFailed(false),
      mUseMutexOnPresent(false) {
  mUseMutexOnPresent = StaticPrefs::gfx_use_mutex_on_present_AtStartup();
}
}

CompositorD3D11::~CompositorD3D11() {}

template <typename VertexType>
void CompositorD3D11::SetVertexBuffer(ID3D11Buffer* aBuffer) {
void CompositorD3D11::SetVertexBuffer(ID3D11Buffer* aBuffer) {
  UINT size = sizeof(VertexType);
  UINT offset = 0;
  mContext->IASetVertexBuffers(0, 1, &aBuffer, &size, &offset);
}


bool CompositorD3D11::SupportsLayerGeometry() const {
  return StaticPrefs::layers_geometry_d3d11_enabled();
}

bool CompositorD3D11::UpdateDynamicVertexBuffer(
bool CompositorD3D11::UpdateDynamicVertexBuffer(
    const nsTArray<gfx::TexturedTriangle>& aTriangles) {
  HRESULT hr;

  // Resize the dynamic vertex buffer if needed.
  if (!mAttachments->EnsureTriangleBuffer(aTriangles.Length())) {
  if (!mAttachments->EnsureTriangleBuffer(aTriangles.Length())) {
    return false;
  }

  D3D11_MAPPED_SUBRESOURCE resource{};
  hr = mContext->Map(mAttachments->mDynamicVertexBuffer, 0,
                     D3D11_MAP_WRITE_DISCARD, 0, &resource);


  if (Failed(hr, "map dynamic vertex buffer")) {
    return false;
  }


  const nsTArray<TexturedVertex> vertices =
      TexturedTrianglesToVertexArray(aTriangles);

  memcpy(resource.pData, vertices.Elements(),
         vertices.Length() * sizeof(TexturedVertex));

  mContext->Unmap(mAttachments->mDynamicVertexBuffer, 0);
  mContext->Unmap(mAttachments->mDynamicVertexBuffer, 0);

  return true;
}

bool CompositorD3D11::Initialize(nsCString* const out_failureReason) {
bool CompositorD3D11::Initialize(nsCString* const out_failureReason) {
  ScopedGfxFeatureReporter reporter("D3D11 Layers");

  HRESULT hr;

  DeviceManagerDx::Get()->GetCompositorDevices(&mDevice, &mAttachments);
  DeviceManagerDx::Get()->GetCompositorDevices(&mDevice, &mAttachments);
  if (!mDevice) {
    gfxCriticalNote << "[D3D11] failed to get compositor device.";
    *out_failureReason = "FEATURE_FAILURE_D3D11_NO_DEVICE";
    return false;
  }
  }
  if (!mAttachments || !mAttachments->IsValid()) {
    gfxCriticalNote << "[D3D11] failed to get compositor device attachments";
    *out_failureReason =
        mAttachments ? mAttachments->GetFailureId()
                     : NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_ATTACHMENTS");
                     : NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_ATTACHMENTS");
    return false;
  }

  mDevice->GetImmediateContext(getter_AddRefs(mContext));
  if (!mContext) {
  if (!mContext) {
    gfxCriticalNote << "[D3D11] failed to get immediate context";
    *out_failureReason = "FEATURE_FAILURE_D3D11_CONTEXT";
    return false;
  }

  mDiagnostics = MakeUnique<DiagnosticsD3D11>(mDevice, mContext);
  mDiagnostics = MakeUnique<DiagnosticsD3D11>(mDevice, mContext);
  mFeatureLevel = mDevice->GetFeatureLevel();

  mHwnd = mWidget->AsWindows()->GetHwnd();

  memset(&mVSConstants, 0, sizeof(VertexShaderConstants));
  memset(&mVSConstants, 0, sizeof(VertexShaderConstants));

  RefPtr<IDXGIDevice> dxgiDevice;
  RefPtr<IDXGIAdapter> dxgiAdapter;

  mDevice->QueryInterface(dxgiDevice.StartAssignment());
  mDevice->QueryInterface(dxgiDevice.StartAssignment());
  dxgiDevice->GetAdapter(getter_AddRefs(dxgiAdapter));

  {
    RefPtr<IDXGIFactory> dxgiFactory;
    RefPtr<IDXGIFactory> dxgiFactory;
    dxgiAdapter->GetParent(IID_PPV_ARGS(dxgiFactory.StartAssignment()));

    RefPtr<IDXGIFactory2> dxgiFactory2;
    hr = dxgiFactory->QueryInterface(
        (IDXGIFactory2**)getter_AddRefs(dxgiFactory2));
        (IDXGIFactory2**)getter_AddRefs(dxgiFactory2));

#if (_WIN32_WINDOWS_MAXVER >= 0x0A00)
    if (gfxVars::UseDoubleBufferingWithCompositor() && SUCCEEDED(hr) &&
        dxgiFactory2) {
      // DXGI_SCALING_NONE is not available on Windows 7 with Platform Update.
      // DXGI_SCALING_NONE is not available on Windows 7 with Platform Update.
      // This looks awful for things like the awesome bar and browser window
      // resizing so we don't use a flip buffer chain here. When using
      // EFFECT_SEQUENTIAL it looks like windows doesn't stretch the surface
      // when resizing. We chose not to run this before Windows 10 because it
      // appears sometimes this breaks our ability to test ASAP compositing.
      // appears sometimes this breaks our ability to test ASAP compositing.
      RefPtr<IDXGISwapChain1> swapChain;

      DXGI_SWAP_CHAIN_DESC1 swapDesc;
      ::ZeroMemory(&swapDesc, sizeof(swapDesc));
      swapDesc.Width = 0;
      swapDesc.Width = 0;
      swapDesc.Height = 0;
      swapDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
      swapDesc.SampleDesc.Count = 1;
      swapDesc.SampleDesc.Quality = 0;
      swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
      swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
      swapDesc.BufferCount = 2;
      swapDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
      swapDesc.Scaling = DXGI_SCALING_NONE;
      mIsDoubleBuffered = true;
      swapDesc.Flags = 0;
      swapDesc.Flags = 0;

      /**
       * Create a swap chain, this swap chain will contain the backbuffer for
       * the window we draw to. The front buffer is the full screen front
       * buffer.
       * buffer.
       */
      hr = dxgiFactory2->CreateSwapChainForHwnd(mDevice, mHwnd, &swapDesc,
                                                nullptr, nullptr,
                                                getter_AddRefs(swapChain));
      if (SUCCEEDED(hr)) {
      if (SUCCEEDED(hr)) {
        DXGI_RGBA color = {1.0f, 1.0f, 1.0f, 1.0f};
        swapChain->SetBackgroundColor(&color);

        mSwapChain = swapChain;
      } else if (mWidget->AsWindows()->GetCompositorHwnd()) {
      }
        // Destroy compositor window.
        mWidget->AsWindows()->DestroyCompositorWindow();
        mHwnd = mWidget->AsWindows()->GetHwnd();
      }
    }

    {
    // In some configurations double buffering may have failed with an
    // ACCESS_DENIED error.
    if (!mSwapChain)
#endif
    {
      swapDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
      DXGI_SWAP_CHAIN_DESC swapDesc;
      ::ZeroMemory(&swapDesc, sizeof(swapDesc));
      swapDesc.BufferDesc.Width = 0;
      swapDesc.BufferDesc.Height = 0;
      swapDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
      swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
      swapDesc.BufferDesc.RefreshRate.Numerator = 60;
      swapDesc.BufferDesc.RefreshRate.Denominator = 1;
      swapDesc.SampleDesc.Count = 1;
      swapDesc.SampleDesc.Quality = 0;
      swapDesc.Flags = 0;
      swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
      swapDesc.BufferCount = 1;
      swapDesc.OutputWindow = mHwnd;
      swapDesc.Windowed = TRUE;
      swapDesc.Flags = 0;
      swapDesc.SwapEffect = DXGI_SWAP_EFFECT_SEQUENTIAL;
       * the window we draw to. The front buffer is the full screen front

      /**
       * Create a swap chain, this swap chain will contain the backbuffer for
       * the window we draw to. The front buffer is the full screen front
       * buffer.
      if (Failed(hr, "create swap chain")) {
       */
      hr = dxgiFactory->CreateSwapChain(dxgiDevice, &swapDesc,
      }
                                        getter_AddRefs(mSwapChain));
    }
      if (Failed(hr, "create swap chain")) {
        *out_failureReason = "FEATURE_FAILURE_D3D11_SWAP_CHAIN";
        return false;
    dxgiFactory->MakeWindowAssociation(mHwnd, DXGI_MWA_NO_WINDOW_CHANGES);
      }
    }

    // We need this because we don't want DXGI to respond to Alt+Enter.
    dxgiFactory->MakeWindowAssociation(mHwnd, DXGI_MWA_NO_WINDOW_CHANGES);
    return false;
  }

  if (!mWidget->InitCompositor(this)) {
    *out_failureReason = "FEATURE_FAILURE_D3D11_INIT_COMPOSITOR";
    return false;
  reporter.SetSuccessful();
  }

  mAllowPartialPresents = CanUsePartialPresents(mDevice);

  reporter.SetSuccessful();
  if (StaticPrefs::gfx_partialpresent_force() > 0) {
  return true;
}

bool CanUsePartialPresents(ID3D11Device* aDevice) {
  if (StaticPrefs::gfx_partialpresent_force() > 0) {
    return true;
  }
    return true;
  if (StaticPrefs::gfx_partialpresent_force() < 0) {
    return false;
  }
  if (DeviceManagerDx::Get()->IsWARP()) {
    return true;
    return false;
  }

  DXGI_ADAPTER_DESC desc;
  if (!D3D11Checks::GetDxgiDesc(aDevice, &desc)) {
    return false;
  }
    return false;

  // We have to disable partial presents on NVIDIA (bug 1189940).
  if (desc.VendorId == 0x10de) {
    return false;
  }


  return true;
}
      new DataTextureSourceD3D11(gfx::SurfaceFormat::UNKNOWN, this, aFlags);

already_AddRefed<DataTextureSource> CompositorD3D11::CreateDataTextureSource(
    TextureFlags aFlags) {
  RefPtr<DataTextureSource> result =
      new DataTextureSourceD3D11(gfx::SurfaceFormat::UNKNOWN, this, aFlags);
  TextureFactoryIdentifier ident;
  return result.forget();
}

TextureFactoryIdentifier CompositorD3D11::GetTextureFactoryIdentifier() {
  TextureFactoryIdentifier ident;
  ident.mMaxTextureSize = GetMaxTextureSize();
    ident.mUseCompositorWnd = !!mWidget->AsWindows()->GetCompositorHwnd();
  ident.mParentProcessType = XRE_GetProcessType();
  ident.mParentBackend = LayersBackend::LAYERS_D3D11;
  if (mWidget) {
    ident.mUseCompositorWnd = !!mWidget->AsWindows()->GetCompositorHwnd();
  return ident;
  }
  if (mAttachments->mSyncObject) {
    ident.mSyncHandle = mAttachments->mSyncObject->GetSyncHandle();
  }
  return ident;
}

    return false;
bool CompositorD3D11::CanUseCanvasLayerForSize(const gfx::IntSize& aSize) {
  int32_t maxTextureSize = GetMaxTextureSize();

  if (aSize.width > maxTextureSize || aSize.height > maxTextureSize) {
    return false;

  }

  return true;
}

already_AddRefed<CompositingRenderTarget> CompositorD3D11::CreateRenderTarget(
int32_t CompositorD3D11::GetMaxTextureSize() const {
  return GetMaxTextureSizeForFeatureLevel(mFeatureLevel);
}

already_AddRefed<CompositingRenderTarget> CompositorD3D11::CreateRenderTarget(
    return nullptr;
    const gfx::IntRect& aRect, SurfaceInitMode aInit) {
  MOZ_ASSERT(!aRect.IsZeroArea());

  if (aRect.IsZeroArea()) {
    return nullptr;
      D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET);
  }

  CD3D11_TEXTURE2D_DESC desc(
  HRESULT hr =
      DXGI_FORMAT_B8G8R8A8_UNORM, aRect.width, aRect.height, 1, 1,
      mDevice->CreateTexture2D(&desc, nullptr, getter_AddRefs(texture));
      D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET);

  RefPtr<ID3D11Texture2D> texture;
  HRESULT hr =
    return nullptr;
      mDevice->CreateTexture2D(&desc, nullptr, getter_AddRefs(texture));
  if (FAILED(hr) || !texture) {
    gfxCriticalNote << "Failed in CreateRenderTarget " << hexa(hr);
    return nullptr;
  rt->SetSize(IntSize(aRect.Width(), aRect.Height()));
  }

  RefPtr<CompositingRenderTargetD3D11> rt =
      new CompositingRenderTargetD3D11(texture, aRect.TopLeft());
  rt->SetSize(IntSize(aRect.Width(), aRect.Height()));

  }
  if (aInit == INIT_MODE_CLEAR) {

    FLOAT clear[] = {0, 0, 0, 0};
    mContext->ClearRenderTargetView(rt->mRTView, clear);

  }

  return rt.forget();
}


RefPtr<ID3D11Texture2D> CompositorD3D11::CreateTexture(
    const gfx::IntRect& aRect, const CompositingRenderTarget* aSource,
    const gfx::IntPoint& aSourcePoint) {
  MOZ_ASSERT(!aRect.IsZeroArea());

  CD3D11_TEXTURE2D_DESC desc(
  if (aRect.IsZeroArea()) {
    return nullptr;
  }

  CD3D11_TEXTURE2D_DESC desc(
  HRESULT hr =
      DXGI_FORMAT_B8G8R8A8_UNORM, aRect.Width(), aRect.Height(), 1, 1,
      D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET);

  RefPtr<ID3D11Texture2D> texture;
  HRESULT hr =
    HandleError(hr);
      mDevice->CreateTexture2D(&desc, nullptr, getter_AddRefs(texture));

  if (FAILED(hr) || !texture) {
    gfxCriticalNote << "Failed in CreateRenderTargetFromSource " << hexa(hr);
  if (aSource) {
    HandleError(hr);
    return nullptr;
  }

  if (aSource) {
    const CompositingRenderTargetD3D11* sourceD3D11 =
    MOZ_ASSERT(srcSize.width >= 0 && srcSize.height >= 0,
        static_cast<const CompositingRenderTargetD3D11*>(aSource);

    const IntSize& srcSize = sourceD3D11->GetSize();
    MOZ_ASSERT(srcSize.width >= 0 && srcSize.height >= 0,
               "render targets should have nonnegative sizes");
    if (!srcRect.Contains(copyRect)) {

    IntRect srcRect(IntPoint(), srcSize);
    IntRect copyRect(aSourcePoint, aRect.Size());
    if (!srcRect.Contains(copyRect)) {
      NS_WARNING("Could not copy the whole copy rect from the render target");

    }

    copyRect = copyRect.Intersect(srcRect);

    if (!copyRect.IsEmpty()) {
      copyBox.left = copyRect.X();
      D3D11_BOX copyBox;
      copyBox.front = 0;
      copyBox.back = 1;
      copyBox.left = copyRect.X();
      copyBox.top = copyRect.Y();
      copyBox.right = copyRect.XMost();
    }
      copyBox.bottom = copyRect.YMost();

      mContext->CopySubresourceRegion(
          texture, 0, 0, 0, 0, sourceD3D11->GetD3D11Texture(), 0, &copyBox);
    }

  }

  return texture;
}

  RefPtr<ID3D11Texture2D> texture = CreateTexture(aRect, aSource, aSourcePoint);
already_AddRefed<CompositingRenderTarget>
CompositorD3D11::CreateRenderTargetFromSource(
    const gfx::IntRect& aRect, const CompositingRenderTarget* aSource,
    const gfx::IntPoint& aSourcePoint) {
  RefPtr<ID3D11Texture2D> texture = CreateTexture(aRect, aSource, aSourcePoint);
  if (!texture) {
  RefPtr<CompositingRenderTargetD3D11> rt =
    return nullptr;
  }

  RefPtr<CompositingRenderTargetD3D11> rt =
      new CompositingRenderTargetD3D11(texture, aRect.TopLeft());
}
  rt->SetSize(aRect.Size());

  return rt.forget();
}

bool CompositorD3D11::ShouldAllowFrameRecording() const {
#else
#ifdef MOZ_GECKO_PROFILER
  return mAllowFrameRecording ||
         profiler_feature_active(ProfilerFeature::Screenshots);
#else
  return mAllowFrameRecording;
already_AddRefed<CompositingRenderTarget>
#endif
}

already_AddRefed<CompositingRenderTarget>
CompositorD3D11::GetWindowRenderTarget() const {

  if (!ShouldAllowFrameRecording()) {
    return nullptr;
  }

  const IntSize size = mDefaultRT->GetSize();
  if (!mDefaultRT) {
    return nullptr;
  }

  if (!mWindowRTCopy || mWindowRTCopy->GetSize() != size) {
  const IntSize size = mDefaultRT->GetSize();

  RefPtr<ID3D11Texture2D> rtTexture;

  if (!mWindowRTCopy || mWindowRTCopy->GetSize() != size) {
     * we were to simply return mDefaultRT then scaling would fail.
    /*
     * The compositor screenshots infrastructure is going to scale down the
     * render target returned by this method. However, mDefaultRT does not
     * contain a texture created wth the D3D11_BIND_SHADER_RESOURCE flag, so if
     * we were to simply return mDefaultRT then scaling would fail.
    HRESULT hr =
     */
    CD3D11_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, size.width,
                               size.height, 1, 1, D3D11_BIND_SHADER_RESOURCE);

    HRESULT hr =

        mDevice->CreateTexture2D(&desc, nullptr, getter_AddRefs(rtTexture));
    if (FAILED(hr)) {
        rtTexture, IntPoint(0, 0), DXGI_FORMAT_B8G8R8A8_UNORM);
      return nullptr;
    }

    mWindowRTCopy = MakeRefPtr<CompositingRenderTargetD3D11>(
        rtTexture, IntPoint(0, 0), DXGI_FORMAT_B8G8R8A8_UNORM);

    mWindowRTCopy->SetSize(size);
  } else {
    rtTexture = mWindowRTCopy->GetD3D11Texture();
  }

             static_cast<CompositingRenderTarget*>(mWindowRTCopy))
  const RefPtr<ID3D11Texture2D> sourceTexture = mDefaultRT->GetD3D11Texture();
  mContext->CopyResource(rtTexture, sourceTexture);

  return RefPtr<CompositingRenderTarget>(
             static_cast<CompositingRenderTarget*>(mWindowRTCopy))
                                           AsyncReadbackBuffer* aDest) {
      .forget();
}

bool CompositorD3D11::ReadbackRenderTarget(CompositingRenderTarget* aSource,
                                           AsyncReadbackBuffer* aDest) {
  RefPtr<CompositingRenderTargetD3D11> srcTexture =

      static_cast<CompositingRenderTargetD3D11*>(aSource);
  RefPtr<AsyncReadbackBufferD3D11> destBuffer =
      static_cast<AsyncReadbackBufferD3D11*>(aDest);

  mContext->CopyResource(destBuffer->GetTexture(),
}
                         srcTexture->GetD3D11Texture());

  return true;
}
  RefPtr<ID3D11Texture2D> texture;

already_AddRefed<AsyncReadbackBuffer>
CompositorD3D11::CreateAsyncReadbackBuffer(const gfx::IntSize& aSize) {
  RefPtr<ID3D11Texture2D> texture;


  CD3D11_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, aSize.width,
                             aSize.height, 1, 1, 0, D3D11_USAGE_STAGING,
                             D3D11_CPU_ACCESS_READ);

  HRESULT hr =
    HandleError(hr);
      mDevice->CreateTexture2D(&desc, nullptr, getter_AddRefs(texture));

  }
  if (FAILED(hr)) {
    HandleError(hr);
    return nullptr;
  }

bool CompositorD3D11::BlitRenderTarget(CompositingRenderTarget* aSource,
  return MakeAndAddRef<AsyncReadbackBufferD3D11>(mContext, texture, aSize);
}

bool CompositorD3D11::BlitRenderTarget(CompositingRenderTarget* aSource,
                                       const gfx::IntSize& aSourceSize,

                                       const gfx::IntSize& aDestSize) {
  RefPtr<CompositingRenderTargetD3D11> source =
      static_cast<CompositingRenderTargetD3D11*>(aSource);

           Float(aSourceSize.height) / Float(source->GetSize().height));
  RefPtr<TexturedEffect> texturedEffect = CreateTexturedEffect(
      SurfaceFormat::B8G8R8A8, source, SamplingFilter::LINEAR, true);
  texturedEffect->mTextureCoords =
      Rect(0, 0, Float(aSourceSize.width) / Float(source->GetSize().width),
           Float(aSourceSize.height) / Float(source->GetSize().height));
  const Float scaleX = Float(aDestSize.width) / Float(aSourceSize.width);

  EffectChain effect;
  effect.mPrimaryEffect = texturedEffect;

  const Float scaleX = Float(aDestSize.width) / Float(aSourceSize.width);
  const Float scaleY = Float(aDestSize.height) / (aSourceSize.height);
  const Matrix4x4 transform = Matrix4x4::Scaling(scaleX, scaleY, 1.0f);

  const Rect sourceRect(0, 0, aSourceSize.width, aSourceSize.height);
  return true;

  DrawQuad(sourceRect, IntRect(0, 0, aDestSize.width, aDestSize.height), effect,
           1.0f, transform, sourceRect);

  return true;
                                   RefPtr<ID3D11ShaderResourceView>* aOutView) {
}

bool CompositorD3D11::CopyBackdrop(const gfx::IntRect& aRect,
                                   RefPtr<ID3D11Texture2D>* aOutTexture,
                                   RefPtr<ID3D11ShaderResourceView>* aOutView) {
  RefPtr<ID3D11Texture2D> texture =
      CreateTexture(aRect, mCurrentRT, aRect.TopLeft());
  if (!texture) {
    return false;
  }
  RefPtr<ID3D11ShaderResourceView> srv;

  CD3D11_SHADER_RESOURCE_VIEW_DESC desc(D3D11_SRV_DIMENSION_TEXTURE2D,
                                        DXGI_FORMAT_B8G8R8A8_UNORM);

  RefPtr<ID3D11ShaderResourceView> srv;
  }
  HRESULT hr =
      mDevice->CreateShaderResourceView(texture, &desc, getter_AddRefs(srv));
  if (FAILED(hr) || !srv) {
    return false;
  }
}

  *aOutTexture = texture.forget();
  *aOutView = srv.forget();
  return true;
}
      static_cast<CompositingRenderTargetD3D11*>(aRenderTarget);

void CompositorD3D11::SetRenderTarget(CompositingRenderTarget* aRenderTarget) {
  MOZ_ASSERT(aRenderTarget);
  CompositingRenderTargetD3D11* newRT =
      static_cast<CompositingRenderTargetD3D11*>(aRenderTarget);

  if (mCurrentRT != newRT) {
    mCurrentRT = newRT;
    mCurrentRT->BindRenderTarget(mContext);
  }

  if (newRT->HasComplexProjection()) {
    gfx::Matrix4x4 projection;
    bool depthEnable;
    float zNear, zFar;
    newRT->GetProjection(projection, depthEnable, zNear, zFar);
  }
    PrepareViewport(newRT->GetSize(), projection, zNear, zFar);
  } else {
    PrepareViewport(newRT->GetSize());
  }
}
                                                   const MaskType aMaskType) {

ID3D11PixelShader* CompositorD3D11::GetPSForEffect(Effect* aEffect,
                                                   const bool aUseBlendShader,

                                                   const MaskType aMaskType) {
  if (aUseBlendShader) {
    return mAttachments->mBlendShader[MaskType::MaskNone];
  }

      return mAttachments->mRGBAShader[aMaskType];
  switch (aEffect->mType) {
    case EffectTypes::SOLID_COLOR:
      return mAttachments->mSolidColorShader[aMaskType];
    case EffectTypes::RENDER_TARGET:
      return mAttachments->mRGBAShader[aMaskType];
              format == SurfaceFormat::R8G8B8A8)
    case EffectTypes::RGB: {
      SurfaceFormat format =
          static_cast<TexturedEffect*>(aEffect)->mTexture->GetFormat();
      return (format == SurfaceFormat::B8G8R8A8 ||
              format == SurfaceFormat::R8G8B8A8)
                 ? mAttachments->mRGBAShader[aMaskType]
      return mAttachments->mNV12Shader[aMaskType];
                 : mAttachments->mRGBShader[aMaskType];
    }
    case EffectTypes::NV12:
      return mAttachments->mNV12Shader[aMaskType];
    case EffectTypes::YCBCR:
    default:
      return mAttachments->mYCbCrShader[aMaskType];
    case EffectTypes::COMPONENT_ALPHA:
      return mAttachments->mComponentAlphaShader[aMaskType];
    default:
      NS_WARNING("No shader to load");

      return nullptr;
  }
}

void CompositorD3D11::ClearRect(const gfx::Rect& aRect) {

  if (aRect.IsEmpty()) {
    return;
  }

  mContext->OMSetBlendState(mAttachments->mDisabledBlendState, sBlendFactor,
                            0xFFFFFFFF);


  Matrix4x4 identity;
  memcpy(&mVSConstants.layerTransform, &identity._11, 64);

  mVSConstants.layerQuad = aRect;
  mVSConstants.renderTargetOffset[0] = 0;
  scissor.left = aRect.X();
  mVSConstants.renderTargetOffset[1] = 0;
  mPSConstants.layerOpacity[0] = 1.0f;

  D3D11_RECT scissor;
  scissor.left = aRect.X();
  mContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
  scissor.right = aRect.XMost();
  scissor.top = aRect.Y();
  scissor.bottom = aRect.YMost();
  mContext->RSSetScissorRects(1, &scissor);
  mContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
  mContext->VSSetShader(mAttachments->mVSQuadShader[MaskType::MaskNone],
                        nullptr, 0);
                        nullptr, 0);

  mContext->PSSetShader(mAttachments->mSolidColorShader[MaskType::MaskNone],
                        nullptr, 0);
  mPSConstants.layerColor[0] = 0;

  mPSConstants.layerColor[1] = 0;
  mPSConstants.layerColor[2] = 0;
  mPSConstants.layerColor[3] = 0;

  if (!UpdateConstantBuffers()) {

    NS_WARNING("Failed to update shader constant buffers");
    return;
  }
  mContext->OMSetBlendState(mAttachments->mPremulBlendState, sBlendFactor,

  mContext->Draw(4, 0);

  // Restore the default blend state.
  mContext->OMSetBlendState(mAttachments->mPremulBlendState, sBlendFactor,
  if (aEffect->mType == EffectTypes::RGB) {
                            0xFFFFFFFF);
}

static inline bool EffectHasPremultipliedAlpha(Effect* aEffect) {
  if (aEffect->mType == EffectTypes::RGB) {
    return static_cast<TexturedEffect*>(aEffect)->mPremultiplied;
  }
  return true;
}
      return PS_LAYER_COLOR;

static inline int EffectToBlendLayerType(Effect* aEffect) {
  switch (aEffect->mType) {
    case EffectTypes::SOLID_COLOR:
      return PS_LAYER_COLOR;
              format == gfx::SurfaceFormat::R8G8B8A8)
    case EffectTypes::RGB: {
      gfx::SurfaceFormat format =
          static_cast<TexturedEffect*>(aEffect)->mTexture->GetFormat();
      return (format == gfx::SurfaceFormat::B8G8R8A8 ||
              format == gfx::SurfaceFormat::R8G8B8A8)
      return PS_LAYER_RGBA;
                 ? PS_LAYER_RGBA
                 : PS_LAYER_RGB;
    }
    case EffectTypes::RENDER_TARGET:
      return PS_LAYER_RGBA;
    case EffectTypes::YCBCR:
    default:
      return PS_LAYER_YCBCR;
    case EffectTypes::NV12:
      return PS_LAYER_NV12;
    default:
      MOZ_ASSERT_UNREACHABLE("blending not supported for this layer type");

      return 0;
  }
}
                               gfx::Float aOpacity,

void CompositorD3D11::DrawQuad(const gfx::Rect& aRect,
                               const gfx::IntRect& aClipRect,
                               const EffectChain& aEffectChain,
                               gfx::Float aOpacity,
}
                               const gfx::Matrix4x4& aTransform,
                               const gfx::Rect& aVisibleRect) {
void CompositorD3D11::DrawTriangles(
  DrawGeometry(aRect, aRect, aClipRect, aEffectChain, aOpacity, aTransform,
               aVisibleRect);
}

void CompositorD3D11::DrawTriangles(
    const nsTArray<gfx::TexturedTriangle>& aTriangles, const gfx::Rect& aRect,
    const gfx::IntRect& aClipRect, const EffectChain& aEffectChain,
}
    gfx::Float aOpacity, const gfx::Matrix4x4& aTransform,
    const gfx::Rect& aVisibleRect) {
  DrawGeometry(aTriangles, aRect, aClipRect, aEffectChain, aOpacity, aTransform,
               aVisibleRect);
}
  SetVertexBuffer<TexturedVertex>(mAttachments->mDynamicVertexBuffer);

void CompositorD3D11::PrepareDynamicVertexBuffer() {
  mContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  mContext->IASetInputLayout(mAttachments->mDynamicInputLayout);
  SetVertexBuffer<TexturedVertex>(mAttachments->mDynamicVertexBuffer);
}
  mContext->IASetInputLayout(mAttachments->mInputLayout);

void CompositorD3D11::PrepareStaticVertexBuffer() {
  mContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
  mContext->IASetInputLayout(mAttachments->mInputLayout);
                           const gfx::Rect*) {
  SetVertexBuffer<Vertex>(mAttachments->mVertexBuffer);
}

void CompositorD3D11::Draw(const nsTArray<gfx::TexturedTriangle>& aTriangles,
                           const gfx::Rect*) {

  if (!UpdateConstantBuffers()) {
    NS_WARNING("Failed to update shader constant buffers");
    return;
  }

    NS_WARNING("Failed to update shader dynamic buffers");
  PrepareDynamicVertexBuffer();

  if (!UpdateDynamicVertexBuffer(aTriangles)) {
    NS_WARNING("Failed to update shader dynamic buffers");
    return;

  }


  mContext->Draw(3 * aTriangles.Length(), 0);

  PrepareStaticVertexBuffer();
}
  Rect textureRects[4] = {};

void CompositorD3D11::Draw(const gfx::Rect& aRect,
                           const gfx::Rect* aTexCoords) {
  Rect layerRects[4] = {aRect};
  Rect textureRects[4] = {};
                                       &textureRects);
  size_t rects = 1;

  if (aTexCoords) {
    rects = DecomposeIntoNoRepeatRects(aRect, *aTexCoords, &layerRects,
                                       &textureRects);
    mVSConstants.textureCoords = textureRects[i];
  }

  for (size_t i = 0; i < rects; i++) {
    mVSConstants.layerQuad = layerRects[i];
    mVSConstants.textureCoords = textureRects[i];
    }

    if (!UpdateConstantBuffers()) {
      NS_WARNING("Failed to update shader constant buffers");
      break;
    }


    mContext->Draw(4, 0);
  }
}

ID3D11VertexShader* CompositorD3D11::GetVSForGeometry(
                          : mAttachments->mVSDynamicShader[aMaskType];
    const nsTArray<gfx::TexturedTriangle>& aTriangles,
    const bool aUseBlendShaders, const MaskType aMaskType) {
  return aUseBlendShaders ? mAttachments->mVSDynamicBlendShader[aMaskType]
                          : mAttachments->mVSDynamicShader[aMaskType];
}
    const MaskType aMaskType) {

ID3D11VertexShader* CompositorD3D11::GetVSForGeometry(
    const gfx::Rect& aRect, const bool aUseBlendShaders,
    const MaskType aMaskType) {
  return aUseBlendShaders ? mAttachments->mVSQuadBlendShader[aMaskType]
                          : mAttachments->mVSQuadShader[aMaskType];
}

template <typename Geometry>
void CompositorD3D11::DrawGeometry(const Geometry& aGeometry,
                                   gfx::Float aOpacity,
                                   const gfx::Rect& aRect,
                                   const gfx::IntRect& aClipRect,
                                   const EffectChain& aEffectChain,
                                   gfx::Float aOpacity,
                                   const gfx::Matrix4x4& aTransform,
  }
                                   const gfx::Rect& aVisibleRect) {
  if (mCurrentClip.IsEmpty()) {
    return;
  }

  IntPoint origin = mCurrentRT->GetOrigin();
  MOZ_ASSERT(mCurrentRT, "No render target");

  memcpy(&mVSConstants.layerTransform, &aTransform._11, 64);
  IntPoint origin = mCurrentRT->GetOrigin();
  mVSConstants.renderTargetOffset[0] = origin.x;

  mVSConstants.renderTargetOffset[1] = origin.y;

  mPSConstants.layerOpacity[0] = aOpacity;

  bool restoreBlendMode = false;
  if (aEffectChain.mSecondaryEffects[EffectTypes::MASK]) {

  MaskType maskType = MaskType::MaskNone;

  if (aEffectChain.mSecondaryEffects[EffectTypes::MASK]) {
    maskType = MaskType::Mask;
    TextureSourceD3D11* source = maskEffect->mMaskTexture->AsSourceD3D11();

    EffectMask* maskEffect = static_cast<EffectMask*>(
        aEffectChain.mSecondaryEffects[EffectTypes::MASK].get());
    TextureSourceD3D11* source = maskEffect->mMaskTexture->AsSourceD3D11();

    }
    if (!source) {
      NS_WARNING("Missing texture source!");
      return;
    }

    ID3D11ShaderResourceView* srView = source->GetShaderResourceView();
    mContext->PSSetShaderResources(TexSlot::Mask, 1, &srView);

    bounds = maskTransform.As2D().TransformBounds(bounds);
    const gfx::Matrix4x4& maskTransform = maskEffect->mMaskTransform;
    NS_ASSERTION(maskTransform.Is2D(),
                 "How did we end up with a 3D transform here?!");
    Rect bounds = Rect(Point(), Size(maskEffect->mSize));
    bounds = maskTransform.As2D().TransformBounds(bounds);
    transform._41 = float(-bounds.X()) / bounds.Width();

    Matrix4x4 transform;
    transform._11 = 1.0f / bounds.Width();
    transform._22 = 1.0f / bounds.Height();
    transform._41 = float(-bounds.X()) / bounds.Width();
    transform._42 = float(-bounds.Y()) / bounds.Height();
  D3D11_RECT scissor;
    memcpy(mVSConstants.maskTransform, &transform._11, 64);
  }

  D3D11_RECT scissor;

    clipRect = clipRect.Intersect(mCurrentClip);
  IntRect clipRect(aClipRect.X(), aClipRect.Y(), aClipRect.Width(),
                   aClipRect.Height());
  if (mCurrentRT == mDefaultRT) {
    clipRect = clipRect.Intersect(mCurrentClip);
  }
  }

  if (clipRect.IsEmpty()) {
    return;
  }

  scissor.bottom = clipRect.YMost();
  scissor.left = clipRect.X();
  scissor.right = clipRect.XMost();
  scissor.top = clipRect.Y();
  scissor.bottom = clipRect.YMost();

  if (aEffectChain.mSecondaryEffects[EffectTypes::BLEND_MODE]) {
  bool useBlendShaders = false;
  RefPtr<ID3D11Texture2D> mixBlendBackdrop;
  gfx::CompositionOp blendMode = gfx::CompositionOp::OP_OVER;
  if (aEffectChain.mSecondaryEffects[EffectTypes::BLEND_MODE]) {
    // If the blend operation needs to read from the backdrop, copy the
    EffectBlendMode* blendEffect = static_cast<EffectBlendMode*>(
        aEffectChain.mSecondaryEffects[EffectTypes::BLEND_MODE].get());
    blendMode = blendEffect->mBlendMode;

    // If the blend operation needs to read from the backdrop, copy the
                                                  &backdropTransform);
    // current render target into a new texture and bind it now.
    if (BlendOpIsMixBlendMode(blendMode)) {
      gfx::Matrix4x4 backdropTransform;
      gfx::IntRect rect = ComputeBackdropCopyRect(aRect, aClipRect, aTransform,
                                                  &backdropTransform);
        useBlendShaders = true;

      RefPtr<ID3D11ShaderResourceView> srv;
      if (CopyBackdrop(rect, &mixBlendBackdrop, &srv) &&
          mAttachments->InitBlendShaders()) {
        useBlendShaders = true;

        memcpy(&mVSConstants.backdropTransform, &backdropTransform._11, 64);
        ID3D11ShaderResourceView* srView = srv.get();
        mContext->PSSetShaderResources(TexSlot::Backdrop, 1, &srView);

        memcpy(&mVSConstants.backdropTransform, &backdropTransform._11, 64);

        mPSConstants.blendConfig[2] = BlendOpToShaderConstant(blendMode);
        mPSConstants.blendConfig[0] =
            EffectToBlendLayerType(aEffectChain.mPrimaryEffect);
        mPSConstants.blendConfig[1] = int(maskType);
        mPSConstants.blendConfig[2] = BlendOpToShaderConstant(blendMode);
        mPSConstants.blendConfig[3] =
  }
            EffectHasPremultipliedAlpha(aEffectChain.mPrimaryEffect);
      }
    }
  }

      GetVSForGeometry(aGeometry, useBlendShaders, maskType);
  mContext->RSSetScissorRects(1, &scissor);

  RefPtr<ID3D11VertexShader> vertexShader =
      GetVSForGeometry(aGeometry, useBlendShaders, maskType);

  mContext->VSSetShader(vertexShader, nullptr, 0);
  RefPtr<ID3D11PixelShader> pixelShader =
      GetPSForEffect(aEffectChain.mPrimaryEffect, useBlendShaders, maskType);


  mContext->VSSetShader(vertexShader, nullptr, 0);
  mContext->PSSetShader(pixelShader, nullptr, 0);

  const Rect* pTexCoordRect = nullptr;

              ->mColor;
  switch (aEffectChain.mPrimaryEffect->mType) {
    case EffectTypes::SOLID_COLOR: {
      DeviceColor color =
          static_cast<EffectSolidColor*>(aEffectChain.mPrimaryEffect.get())
              ->mColor;
    } break;
      mPSConstants.layerColor[0] = color.r * color.a * aOpacity;
      mPSConstants.layerColor[1] = color.g * color.a * aOpacity;
      mPSConstants.layerColor[2] = color.b * color.a * aOpacity;
      mPSConstants.layerColor[3] = color.a * aOpacity;
    } break;

    case EffectTypes::RGB:
    case EffectTypes::RENDER_TARGET: {
      TexturedEffect* texturedEffect =
          static_cast<TexturedEffect*>(aEffectChain.mPrimaryEffect.get());

      if (!source) {
      pTexCoordRect = &texturedEffect->mTextureCoords;

      TextureSourceD3D11* source = texturedEffect->mTexture->AsSourceD3D11();

      if (!source) {
      ID3D11ShaderResourceView* srView = source->GetShaderResourceView();
        NS_WARNING("Missing texture source!");
        return;
      }

      ID3D11ShaderResourceView* srView = source->GetShaderResourceView();
                                  sBlendFactor, 0xFFFFFFFF);
      mContext->PSSetShaderResources(TexSlot::RGB, 1, &srView);

      if (!texturedEffect->mPremultiplied) {
        mContext->OMSetBlendState(mAttachments->mNonPremulBlendState,
                                  sBlendFactor, 0xFFFFFFFF);
    } break;
        restoreBlendMode = true;
      }

      SetSamplerForSamplingFilter(texturedEffect->mSamplingFilter);
    } break;
    case EffectTypes::NV12: {
      EffectNV12* effectNV12 =
          static_cast<EffectNV12*>(aEffectChain.mPrimaryEffect.get());
      if (!source) {

      pTexCoordRect = &effectNV12->mTextureCoords;

      TextureSourceD3D11* source = effectNV12->mTexture->AsSourceD3D11();
      if (!source) {
      RefPtr<ID3D11Texture2D> texture = source->GetD3D11Texture();
        NS_WARNING("Missing texture source!");
        return;
      }

      RefPtr<ID3D11Texture2D> texture = source->GetD3D11Texture();
      D3D11_TEXTURE2D_DESC sourceDesc;
      if (!texture) {
        NS_WARNING("No texture found in texture source!");
      }

      D3D11_TEXTURE2D_DESC sourceDesc;

      texture->GetDesc(&sourceDesc);
      MOZ_DIAGNOSTIC_ASSERT(sourceDesc.Format == DXGI_FORMAT_NV12 ||
                            sourceDesc.Format == DXGI_FORMAT_P010 ||
                            sourceDesc.Format == DXGI_FORMAT_P016);

          CD3D11_SHADER_RESOURCE_VIEW_DESC(D3D11_SRV_DIMENSION_TEXTURE2D,
      // Might want to cache these for efficiency.
      RefPtr<ID3D11ShaderResourceView> srViewY;
      RefPtr<ID3D11ShaderResourceView> srViewCbCr;
      D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc =
          CD3D11_SHADER_RESOURCE_VIEW_DESC(D3D11_SRV_DIMENSION_TEXTURE2D,
                                        getter_AddRefs(srViewY));
                                           sourceDesc.Format == DXGI_FORMAT_NV12
                                               ? DXGI_FORMAT_R8_UNORM
                                               : DXGI_FORMAT_R16_UNORM);
      mDevice->CreateShaderResourceView(texture, &srvDesc,
                                        getter_AddRefs(srViewY));
                                        getter_AddRefs(srViewCbCr));
      srvDesc.Format = sourceDesc.Format == DXGI_FORMAT_NV12
                           ? DXGI_FORMAT_R8G8_UNORM
                           : DXGI_FORMAT_R16G16_UNORM;
      mDevice->CreateShaderResourceView(texture, &srvDesc,
                                        getter_AddRefs(srViewCbCr));

      ID3D11ShaderResourceView* views[] = {srViewY, srViewCbCr};
      mContext->PSSetShaderResources(TexSlot::Y, 2, views);

      mPSConstants.vCoefficient[0] =
      const float* yuvToRgb =
          gfxUtils::YuvToRgbMatrix4x3RowMajor(effectNV12->mYUVColorSpace);
      memcpy(&mPSConstants.yuvColorMatrix, yuvToRgb,
             sizeof(mPSConstants.yuvColorMatrix));
      mPSConstants.vCoefficient[0] =
          RescalingFactorForColorDepth(effectNV12->mColorDepth);
    case EffectTypes::YCBCR: {

      SetSamplerForSamplingFilter(effectNV12->mSamplingFilter);
    } break;
    case EffectTypes::YCBCR: {
      EffectYCbCr* ycbcrEffect =
          static_cast<EffectYCbCr*>(aEffectChain.mPrimaryEffect.get());


      SetSamplerForSamplingFilter(SamplingFilter::LINEAR);

      pTexCoordRect = &ycbcrEffect->mTextureCoords;

        NS_WARNING("No texture to composite");
      const int Y = 0, Cb = 1, Cr = 2;
      TextureSource* source = ycbcrEffect->mTexture;

      if (!source) {
        NS_WARNING("No texture to composite");
          !source->GetSubSource(Cr)) {
        return;
      }

      if (!source->GetSubSource(Y) || !source->GetSubSource(Cb) ||
          !source->GetSubSource(Cr)) {

        // This can happen if we failed to upload the textures, most likely
        // because of unsupported dimensions (we don't tile YCbCr textures).
        return;
      }


      const float* yuvToRgb =
          gfxUtils::YuvToRgbMatrix4x3RowMajor(ycbcrEffect->mYUVColorSpace);
      memcpy(&mPSConstants.yuvColorMatrix, yuvToRgb,
             sizeof(mPSConstants.yuvColorMatrix));

      // Adjust range according to the bit depth.
      mPSConstants.vCoefficient[0] =
      TextureSourceD3D11* sourceCb = source->GetSubSource(Cb)->AsSourceD3D11();
          RescalingFactorForColorDepth(ycbcrEffect->mColorDepth);

      TextureSourceD3D11* sourceY = source->GetSubSource(Y)->AsSourceD3D11();
      TextureSourceD3D11* sourceCb = source->GetSubSource(Cb)->AsSourceD3D11();
      TextureSourceD3D11* sourceCr = source->GetSubSource(Cr)->AsSourceD3D11();

    } break;
      ID3D11ShaderResourceView* srViews[3] = {
          sourceY->GetShaderResourceView(), sourceCb->GetShaderResourceView(),
          sourceCr->GetShaderResourceView()};
      mContext->PSSetShaderResources(TexSlot::Y, 3, srViews);
    } break;
          static_cast<EffectComponentAlpha*>(aEffectChain.mPrimaryEffect.get());
    case EffectTypes::COMPONENT_ALPHA: {
      MOZ_ASSERT(LayerManager::LayersComponentAlphaEnabled());
      MOZ_ASSERT(mAttachments->mComponentBlendState);
      EffectComponentAlpha* effectComponentAlpha =
          static_cast<EffectComponentAlpha*>(aEffectChain.mPrimaryEffect.get());
          effectComponentAlpha->mOnBlack->AsSourceD3D11();

      TextureSourceD3D11* sourceOnWhite =
          effectComponentAlpha->mOnWhite->AsSourceD3D11();
      TextureSourceD3D11* sourceOnBlack =
          effectComponentAlpha->mOnBlack->AsSourceD3D11();
      }

      if (!sourceOnWhite || !sourceOnBlack) {
        NS_WARNING("Missing texture source(s)!");
        return;
      }


      SetSamplerForSamplingFilter(effectComponentAlpha->mSamplingFilter);

      pTexCoordRect = &effectComponentAlpha->mTextureCoords;

      ID3D11ShaderResourceView* srViews[2] = {
          sourceOnBlack->GetShaderResourceView(),
          sourceOnWhite->GetShaderResourceView()};
      mContext->PSSetShaderResources(TexSlot::RGB, 1, &srViews[0]);
      restoreBlendMode = true;
      mContext->PSSetShaderResources(TexSlot::RGBWhite, 1, &srViews[1]);

      mContext->OMSetBlendState(mAttachments->mComponentBlendState,
                                sBlendFactor, 0xFFFFFFFF);
      restoreBlendMode = true;
    } break;
    default:
  Draw(aGeometry, pTexCoordRect);
      NS_WARNING("Unknown shader type");
      return;
  }

  Draw(aGeometry, pTexCoordRect);
  }

  if (restoreBlendMode) {
    mContext->OMSetBlendState(mAttachments->mPremulBlendState, sBlendFactor,
                              0xFFFFFFFF);
  }
    const IntRect& aRenderBounds, const nsIntRegion& aOpaqueRegion) {
}

Maybe<IntRect> CompositorD3D11::BeginFrameForWindow(
    const nsIntRegion& aInvalidRegion, const Maybe<IntRect>& aClipRect,
    const IntRect& aRenderBounds, const nsIntRegion& aOpaqueRegion) {
Maybe<IntRect> CompositorD3D11::BeginFrameForTarget(
  MOZ_RELEASE_ASSERT(!mTarget, "mTarget not cleared properly");
  return BeginFrame(aInvalidRegion, aClipRect, aRenderBounds, aOpaqueRegion);
}

Maybe<IntRect> CompositorD3D11::BeginFrameForTarget(
  mTarget = aTarget;  // Will be cleared in EndFrame().
    const nsIntRegion& aInvalidRegion, const Maybe<IntRect>& aClipRect,
    const IntRect& aRenderBounds, const nsIntRegion& aOpaqueRegion,
    DrawTarget* aTarget, const IntRect& aTargetBounds) {
  MOZ_RELEASE_ASSERT(!mTarget, "mTarget not cleared properly");
  mTarget = aTarget;  // Will be cleared in EndFrame().
  mTargetBounds = aTargetBounds;
  Maybe<IntRect> result =
      BeginFrame(aInvalidRegion, aClipRect, aRenderBounds, aOpaqueRegion);
  if (!result) {
    // Composition has been aborted. Reset mTarget.
}
    mTarget = nullptr;
  }
  return result;
}


void CompositorD3D11::BeginFrameForNativeLayers() {
  MOZ_CRASH("Native layers are not implemented on Windows.");
}
    const nsIntRegion& aOpaqueRegion, NativeLayer* aNativeLayer) {
  MOZ_CRASH("Native layers are not implemented on Windows.");

Maybe<gfx::IntRect> CompositorD3D11::BeginRenderingToNativeLayer(
    const nsIntRegion& aInvalidRegion, const Maybe<gfx::IntRect>& aClipRect,
void CompositorD3D11::EndRenderingToNativeLayer() {
    const nsIntRegion& aOpaqueRegion, NativeLayer* aNativeLayer) {
  MOZ_CRASH("Native layers are not implemented on Windows.");
}

void CompositorD3D11::EndRenderingToNativeLayer() {
                                           const Maybe<IntRect>& aClipRect,
  MOZ_CRASH("Native layers are not implemented on Windows.");
}

Maybe<IntRect> CompositorD3D11::BeginFrame(const nsIntRegion& aInvalidRegion,
                                           const Maybe<IntRect>& aClipRect,
  // cause a crash when we're restored.
                                           const IntRect& aRenderBounds,
                                           const nsIntRegion& aOpaqueRegion) {
  // Don't composite if we are minimised. Other than for the sake of efficency,
  // this is important because resizing our buffers when mimised will fail and
  // cause a crash when we're restored.
    ReadUnlockTextures();
  NS_ASSERTION(mHwnd, "Couldn't find an HWND when initialising?");
  if (mWidget->IsHidden()) {
    // We are not going to render, and not going to call EndFrame so we have to
    // read-unlock our textures to prevent them from accumulating.
    ReadUnlockTextures();
    ReadUnlockTextures();
    return Nothing();
  }

  if (mDevice->GetDeviceRemovedReason() != S_OK) {
      gfxCriticalNote << "GFX: D3D11 skip BeginFrame with device-removed.";
    ReadUnlockTextures();

    if (!mAttachments->IsDeviceReset()) {
      gfxCriticalNote << "GFX: D3D11 skip BeginFrame with device-removed.";

        GPUParent::GetSingleton()->NotifyDeviceReset();
      // If we are in the GPU process then the main process doesn't
      // know that a device reset has happened and needs to be informed
      if (XRE_IsGPUProcess()) {
        GPUParent::GetSingleton()->NotifyDeviceReset();
      }
  }
      mAttachments->SetDeviceReset();
    }
    return Nothing();
  }
  EnsureSize();

  LayoutDeviceIntSize oldSize = mSize;

  EnsureSize();


  IntRect rect = IntRect(IntPoint(0, 0), mSize.ToUnknownSize());
  // Sometimes the invalid region is larger than we want to draw.
  nsIntRegion invalidRegionSafe;

  if (mSize != oldSize) {
  }
    invalidRegionSafe = rect;
  } else {
    invalidRegionSafe.And(aInvalidRegion, rect);
  }

  if (aClipRect) {
  IntRect invalidRect = invalidRegionSafe.GetBounds();

  IntRect clipRect = invalidRect;
  if (aClipRect) {
    clipRect.IntersectRect(clipRect, *aClipRect);
    CancelFrame();
  }

  if (clipRect.IsEmpty()) {
    CancelFrame();
    return Nothing();

  }

    mFrontBufferInvalid.Or(mFrontBufferInvalid, invalidRegionSafe);
  PrepareStaticVertexBuffer();

  mBackBufferInvalid.Or(mBackBufferInvalid, invalidRegionSafe);
  if (mIsDoubleBuffered) {
    mFrontBufferInvalid.Or(mFrontBufferInvalid, invalidRegionSafe);
  if (!UpdateRenderTarget() || !mDefaultRT || !mDefaultRT->mRTView ||
  }

  // We have to call UpdateRenderTarget after we've determined the invalid regi
  // Failed to create a render target or the view.
  if (!UpdateRenderTarget() || !mDefaultRT || !mDefaultRT->mRTView ||
  }
      mSize.width <= 0 || mSize.height <= 0) {
    ReadUnlockTextures();
    return Nothing();
  }


  mCurrentClip = mBackBufferInvalid.GetBounds();

  mContext->RSSetState(mAttachments->mRasterizerState);

  SetRenderTarget(mDefaultRT);


  IntRegion regionToClear(mCurrentClip);
  regionToClear.Sub(regionToClear, aOpaqueRegion);


  ClearRect(Rect(regionToClear.GetBounds()));

  mContext->OMSetBlendState(mAttachments->mPremulBlendState, sBlendFactor,
                            0xFFFFFFFF);

      return Nothing();
  if (mAttachments->mSyncObject) {
    if (!mAttachments->mSyncObject->Synchronize()) {
      // It's timeout here. Since the timeout is related to the driver-removed,
      // skip this frame.
      return Nothing();
    uint32_t pixelsPerFrame = 0;
    }
  }

  if (StaticPrefs::layers_acceleration_draw_fps()) {
    uint32_t pixelsPerFrame = 0;
    mDiagnostics->Start(pixelsPerFrame);
    for (auto iter = mBackBufferInvalid.RectIter(); !iter.Done(); iter.Next()) {
      pixelsPerFrame += iter.Get().Width() * iter.Get().Height();
    }

    mDiagnostics->Start(pixelsPerFrame);

  }

  return Some(rect);
}

  if (!profiler_feature_active(ProfilerFeature::Screenshots) && mWindowRTCopy) {
void CompositorD3D11::NormalDrawingDone() { mDiagnostics->End(); }

void CompositorD3D11::EndFrame() {
  if (!profiler_feature_active(ProfilerFeature::Screenshots) && mWindowRTCopy) {
    mWindowRTCopy = nullptr;
    Compositor::EndFrame();
  }

  if (!mDefaultRT) {
    Compositor::EndFrame();
  if (XRE_IsParentProcess() && mDevice->GetDeviceRemovedReason() != S_OK) {
    mTarget = nullptr;
    return;
  }

  if (XRE_IsParentProcess() && mDevice->GetDeviceRemovedReason() != S_OK) {
    return;
    gfxCriticalNote << "GFX: D3D11 skip EndFrame with device-removed.";
    Compositor::EndFrame();
    mTarget = nullptr;
    mCurrentRT = nullptr;
    return;
  if (mSize.width <= 0 || mSize.height <= 0) {
  }

  LayoutDeviceIntSize oldSize = mSize;
  EnsureSize();
  if (mSize.width <= 0 || mSize.height <= 0) {

    Compositor::EndFrame();
    mTarget = nullptr;
    return;
  }

    mContext->End(query);
  RefPtr<ID3D11Query> query;
  CD3D11_QUERY_DESC desc(D3D11_QUERY_EVENT);
  mDevice->CreateQuery(&desc, getter_AddRefs(query));
  if (query) {
    mContext->End(query);
    if (StaticPrefs::gfx_compositor_clearstate()) {
  }

  if (oldSize == mSize) {
    Present();
    if (StaticPrefs::gfx_compositor_clearstate()) {
    mDiagnostics->Cancel();
      mContext->ClearState();
    }
  } else {
    mDiagnostics->Cancel();
  }
    BOOL result;

  // Block until the previous frame's work has been completed.
  if (mQuery) {
    BOOL result;
    WaitForFrameGPUQuery(mDevice, mContext, mQuery, &result);

  }
  // Store the query for this frame so we can flush it next time.
  mQuery = query;

  Compositor::EndFrame();

  mTarget = nullptr;
  mCurrentRT = nullptr;
}

void CompositorD3D11::Present() {
void CompositorD3D11::GetFrameStats(GPUStats* aStats) {
  mDiagnostics->Query(aStats);
}

void CompositorD3D11::Present() {
    // When we're using WARP we cannot present immediately as it causes us
  UINT presentInterval = 0;

  bool isWARP = DeviceManagerDx::Get()->IsWARP();
  if (isWARP) {
    // When we're using WARP we cannot present immediately as it causes us

    // to tear when rendering. When not using WARP it appears the DWM takes
    // care of tearing for us.
    presentInterval = 1;
  }

  // This must be called before present so our back buffer has the validated
  // window content.
  if (mTarget) {
  RefPtr<IDXGISwapChain1> chain;
    PaintToTarget();
  }

  RefPtr<IDXGISwapChain1> chain;
  RefPtr<IDXGIKeyedMutex> mutex;
  HRESULT hr =
      mSwapChain->QueryInterface((IDXGISwapChain1**)getter_AddRefs(chain));

  RefPtr<IDXGIKeyedMutex> mutex;
  if (mUseMutexOnPresent && mAttachments->mSyncObject) {
    MOZ_ASSERT(mutex);
    SyncObjectD3D11Host* d3dSyncObj =
        (SyncObjectD3D11Host*)mAttachments->mSyncObject.get();
    mutex = d3dSyncObj->GetKeyedMutex();
    MOZ_ASSERT(mutex);
  }
    PodZero(&params);

  if (SUCCEEDED(hr) && mAllowPartialPresents) {
    DXGI_PRESENT_PARAMETERS params;
    PodZero(&params);
    params.DirtyRectsCount = mBackBufferInvalid.GetNumRects();
    for (auto iter = mBackBufferInvalid.RectIter(); !iter.Done(); iter.Next()) {
    StackArray<RECT, 4> rects(params.DirtyRectsCount);

    uint32_t i = 0;
    for (auto iter = mBackBufferInvalid.RectIter(); !iter.Done(); iter.Next()) {
      rects[i].right = r.XMost();
      const IntRect& r = iter.Get();
      rects[i].left = r.X();
      rects[i].top = r.Y();
      rects[i].bottom = r.YMost();
      rects[i].right = r.XMost();

      i++;
    }

    params.pDirtyRects = params.DirtyRectsCount ? rects.data() : nullptr;


    if (mutex) {
      hr = mutex->AcquireSync(0, 2000);
      NS_ENSURE_TRUE_VOID(SUCCEEDED(hr));
    }

    chain->Present1(
        presentInterval,
        mDisableSequenceForNextFrame ? DXGI_PRESENT_DO_NOT_SEQUENCE : 0,
        &params);

  } else {
    if (mutex) {
      mutex->ReleaseSync(0);
    }
  } else {
    if (mutex) {

      hr = mutex->AcquireSync(0, 2000);
      NS_ENSURE_TRUE_VOID(SUCCEEDED(hr));
    }

    hr = mSwapChain->Present(
      mutex->ReleaseSync(0);
        0, mDisableSequenceForNextFrame ? DXGI_PRESENT_DO_NOT_SEQUENCE : 0);

    if (mutex) {
      mutex->ReleaseSync(0);
    }
      HandleError(hr);

    if (FAILED(hr)) {
      gfxCriticalNote << "D3D11 swap chain preset failed " << hexa(hr);
      HandleError(hr);
    mBackBufferInvalid = mFrontBufferInvalid;
    }
  }

  if (mIsDoubleBuffered) {
    mBackBufferInvalid = mFrontBufferInvalid;

    mFrontBufferInvalid.SetEmpty();
  } else {
    mBackBufferInvalid.SetEmpty();
  }

  ReadUnlockTextures();
  mDisableSequenceForNextFrame = false;
}

void CompositorD3D11::CancelFrame(bool aNeedFlush) {
  ReadUnlockTextures();
  // Flush the context, otherwise the driver might hold some resources alive
  // until the next flush or present.
  if (aNeedFlush) {

    mContext->Flush();
  }
}

void CompositorD3D11::PrepareViewport(const gfx::IntSize& aSize) {
  viewMatrix.PreScale(2.0f / float(aSize.width), 2.0f / float(aSize.height));
  // This view matrix translates coordinates from 0..width and 0..height to
  // -1..1 on the X axis, and -1..1 on the Y axis (flips the Y coordinate)
  Matrix viewMatrix = Matrix::Translation(-1.0, 1.0);
  viewMatrix.PreScale(2.0f / float(aSize.width), 2.0f / float(aSize.height));
  viewMatrix.PreScale(1.0f, -1.0f);

}
  Matrix4x4 projection = Matrix4x4::From2D(viewMatrix);
  projection._33 = 0.0f;

  PrepareViewport(aSize, projection, 0.0f, 1.0f);
}

  DXGI_SWAP_CHAIN_DESC desc;
void CompositorD3D11::ForcePresent() {
  LayoutDeviceIntSize size = mWidget->GetClientSize();

  DXGI_SWAP_CHAIN_DESC desc;
  mSwapChain->GetDesc(&desc);
    mSwapChain->Present(0, 0);

  if (desc.BufferDesc.Width == size.width &&
      desc.BufferDesc.Height == size.height) {
    mSwapChain->Present(0, 0);
    if (mIsDoubleBuffered) {
      mSwapChain->Present(0, 0);
      // Make sure we present what was the front buffer before that we know is
      // completely valid. This non v-synced present should be pretty much
      // 'free' for a flip chain.
      mSwapChain->Present(0, 0);
    }
void CompositorD3D11::PrepareViewport(const gfx::IntSize& aSize,
  }
}

void CompositorD3D11::PrepareViewport(const gfx::IntSize& aSize,
                                      const gfx::Matrix4x4& aProjection,
  viewport.MinDepth = aZNear;
                                      float aZNear, float aZFar) {
  D3D11_VIEWPORT viewport;
  viewport.TopLeftX = 0;
  viewport.MaxDepth = aZFar;
  viewport.MinDepth = aZNear;
  viewport.Width = aSize.width;
  viewport.Height = aSize.height;
  viewport.TopLeftX = 0;
  viewport.TopLeftY = 0;

}
  mContext->RSSetViewports(1, &viewport);

  memcpy(&mVSConstants.projection, &aProjection._11,
         sizeof(mVSConstants.projection));
}
  mWidget->AsWindows()->UpdateCompositorWndSizeIfNecessary();

void CompositorD3D11::EnsureSize() { mSize = mWidget->GetClientSize(); }

bool CompositorD3D11::VerifyBufferSize() {
  mWidget->AsWindows()->UpdateCompositorWndSizeIfNecessary();
  hr = mSwapChain->GetDesc(&swapDesc);

  DXGI_SWAP_CHAIN_DESC swapDesc;
  HRESULT hr;

  hr = mSwapChain->GetDesc(&swapDesc);
    return false;
  if (FAILED(hr)) {
    gfxCriticalError() << "Failed to get the description " << hexa(hr) << ", "
                       << mSize << ", " << (int)mVerifyBuffersFailed;
    HandleError(hr);
    return false;
       mSize.width <= 0 || mSize.height <= 0) &&
  }

  if (((swapDesc.BufferDesc.Width == mSize.width &&
        swapDesc.BufferDesc.Height == mSize.height) ||
       mSize.width <= 0 || mSize.height <= 0) &&
  ID3D11RenderTargetView* view = nullptr;
      !mVerifyBuffersFailed) {
    return true;
  }

    RefPtr<ID3D11RenderTargetView> rtView = mDefaultRT->mRTView;
  ID3D11RenderTargetView* view = nullptr;
  mContext->OMSetRenderTargets(1, &view, nullptr);

  if (mDefaultRT) {
    RefPtr<ID3D11RenderTargetView> rtView = mDefaultRT->mRTView;
    if (mCurrentRT == mDefaultRT) {
    RefPtr<ID3D11ShaderResourceView> srView = mDefaultRT->mSRV;

    // Make sure the texture, which belongs to the swapchain, is destroyed
    // before resizing the swapchain.

    if (mCurrentRT == mDefaultRT) {
    MOZ_ASSERT(mDefaultRT->hasOneRef());
      mCurrentRT = nullptr;
    }
    RefPtr<ID3D11Resource> resource;

    MOZ_ASSERT(mDefaultRT->hasOneRef());
    mDefaultRT = nullptr;

    RefPtr<ID3D11Resource> resource;
    if (newRefCnt > 0) {
    rtView->GetResource(getter_AddRefs(resource));

    ULONG newRefCnt = rtView.forget().take()->Release();

    if (newRefCnt > 0) {
      gfxCriticalError() << "mRTView not destroyed on final release! RefCnt: "
    if (srView) {
                         << newRefCnt;
    }

    if (srView) {
                           << newRefCnt;
      newRefCnt = srView.forget().take()->Release();

      if (newRefCnt > 0) {
        gfxCriticalError() << "mSRV not destroyed on final release! RefCnt: "
                           << newRefCnt;

      }
    }

    newRefCnt = resource.forget().take()->Release();

          << newRefCnt;
    if (newRefCnt > 0) {
      gfxCriticalError()
          << "Unexpecting lingering references to backbuffer! RefCnt: "
          << newRefCnt;
    }
                                 DXGI_FORMAT_B8G8R8A8_UNORM, 0);
  }

  if (mVerifyBuffersFailed) {
  hr = mSwapChain->ResizeBuffers(0, mSize.width, mSize.height,
                                 DXGI_FORMAT_B8G8R8A8_UNORM, 0);

    HandleError(hr);
  mVerifyBuffersFailed = FAILED(hr);
  }
  if (mVerifyBuffersFailed) {
    gfxCriticalNote << "D3D11 swap resize buffers failed " << hexa(hr) << " on "
                    << mSize;
      IntRect(0, 0, mSize.width, mSize.height);
    HandleError(hr);
  }

  mBackBufferInvalid = mFrontBufferInvalid =
      IntRect(0, 0, mSize.width, mSize.height);
bool CompositorD3D11::UpdateRenderTarget() {

  return !mVerifyBuffersFailed;
}

bool CompositorD3D11::UpdateRenderTarget() {
  if (!VerifyBufferSize()) {
  HRESULT hr;

  RefPtr<ID3D11Texture2D> backBuf;

  if (!VerifyBufferSize()) {

    gfxCriticalNote << "Failed VerifyBufferSize in UpdateRenderTarget "
                    << mSize;
    return false;
  }

  }
  if (mSize.width <= 0 || mSize.height <= 0) {
    gfxCriticalNote << "Invalid size in UpdateRenderTarget " << mSize << ", "
                    << (int)mVerifyBuffersFailed;
    return false;
  if (hr == DXGI_ERROR_INVALID_CALL) {
  }

  hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
                             (void**)backBuf.StartAssignment());
  if (hr == DXGI_ERROR_INVALID_CALL) {
    // This happens on some GPUs/drivers when there's a TDR.
    if (mDevice->GetDeviceRemovedReason() != S_OK) {
      gfxCriticalError() << "GetBuffer returned invalid call! " << mSize << ", "
                         << (int)mVerifyBuffersFailed;

      return false;
    }
  }

  if (FAILED(hr)) {
    return false;
    gfxCriticalNote << "Failed in UpdateRenderTarget " << hexa(hr) << ", "
                    << mSize << ", " << (int)mVerifyBuffersFailed;
    HandleError(hr);
    return false;

  }

  IntRegion validFront;
  validFront.Sub(mBackBufferInvalid, mFrontBufferInvalid);


  if (!validFront.IsEmpty()) {
    RefPtr<ID3D11Texture2D> frontBuf;
    hr = mSwapChain->GetBuffer(1, __uuidof(ID3D11Texture2D),
                               (void**)frontBuf.StartAssignment());

        D3D11_BOX box;
    if (SUCCEEDED(hr)) {
      for (auto iter = validFront.RectIter(); !iter.Done(); iter.Next()) {
        const IntRect& rect = iter.Get();

        box.left = rect.X();
        box.right = rect.XMost();
        D3D11_BOX box;
        box.back = 1;
        box.front = 0;
        box.left = rect.X();
        mContext->CopySubresourceRegion(backBuf, 0, rect.X(), rect.Y(), 0,
        box.right = rect.XMost();
        box.top = rect.Y();
        box.bottom = rect.YMost();
        mContext->CopySubresourceRegion(backBuf, 0, rect.X(), rect.Y(), 0,
                                        frontBuf, 0, &box);
  }
      }
      mBackBufferInvalid = mFrontBufferInvalid;
    }
  }

}
  mDefaultRT = new CompositingRenderTargetD3D11(backBuf, IntPoint(0, 0));
  mDefaultRT->SetSize(mSize.ToUnknownSize());

  return true;
}
  resource.pData = nullptr;

bool CompositorD3D11::UpdateConstantBuffers() {
  HRESULT hr;
  D3D11_MAPPED_SUBRESOURCE resource;
  resource.pData = nullptr;
    gfxCriticalError() << "Failed to map VSConstantBuffer. Result: " << hexa(hr)

  hr = mContext->Map(mAttachments->mVSConstantBuffer, 0,
                     D3D11_MAP_WRITE_DISCARD, 0, &resource);
  if (FAILED(hr) || !resource.pData) {
    gfxCriticalError() << "Failed to map VSConstantBuffer. Result: " << hexa(hr)
                       << ", " << (int)mVerifyBuffersFailed;
  *(VertexShaderConstants*)resource.pData = mVSConstants;
    HandleError(hr);
    return false;
  }
  hr = mContext->Map(mAttachments->mPSConstantBuffer, 0,
  *(VertexShaderConstants*)resource.pData = mVSConstants;
  mContext->Unmap(mAttachments->mVSConstantBuffer, 0);
  resource.pData = nullptr;

  hr = mContext->Map(mAttachments->mPSConstantBuffer, 0,
    HandleError(hr);
                     D3D11_MAP_WRITE_DISCARD, 0, &resource);
  if (FAILED(hr) || !resource.pData) {
    gfxCriticalError() << "Failed to map PSConstantBuffer. Result: " << hexa(hr)
                       << ", " << (int)mVerifyBuffersFailed;
    HandleError(hr);

    return false;
  }
  *(PixelShaderConstants*)resource.pData = mPSConstants;
  mContext->Unmap(mAttachments->mPSConstantBuffer, 0);

  buffer = mAttachments->mPSConstantBuffer;
  ID3D11Buffer* buffer = mAttachments->mVSConstantBuffer;

  mContext->VSSetConstantBuffers(0, 1, &buffer);

  buffer = mAttachments->mPSConstantBuffer;
  mContext->PSSetConstantBuffers(0, 1, &buffer);
void CompositorD3D11::SetSamplerForSamplingFilter(
  return true;
}

void CompositorD3D11::SetSamplerForSamplingFilter(
    SamplingFilter aSamplingFilter) {
      sampler = mAttachments->mPointSamplerState;
  ID3D11SamplerState* sampler;
  switch (aSamplingFilter) {
    case SamplingFilter::POINT:
      sampler = mAttachments->mPointSamplerState;
      break;
      break;
    case SamplingFilter::LINEAR:
    default:
      sampler = mAttachments->mLinearSamplerState;
      break;
  }


  mContext->PSSetSamplers(0, 1, &sampler);
}

void CompositorD3D11::PaintToTarget() {
  hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
  RefPtr<ID3D11Texture2D> backBuf;
  HRESULT hr;

  hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
        << "Failed in PaintToTarget 1";
                             (void**)backBuf.StartAssignment());
  if (FAILED(hr)) {
    gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
        << "Failed in PaintToTarget 1";
    HandleError(hr);
  D3D11_TEXTURE2D_DESC bbDesc;
    return;
  }

  D3D11_TEXTURE2D_DESC bbDesc;
  backBuf->GetDesc(&bbDesc);
  softDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;

  CD3D11_TEXTURE2D_DESC softDesc(bbDesc.Format, bbDesc.Width, bbDesc.Height);
  softDesc.MipLevels = 1;
  RefPtr<ID3D11Texture2D> readTexture;
  softDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  softDesc.Usage = D3D11_USAGE_STAGING;
  softDesc.BindFlags = 0;

  RefPtr<ID3D11Texture2D> readTexture;

    gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
  hr =
      mDevice->CreateTexture2D(&softDesc, nullptr, getter_AddRefs(readTexture));
  if (FAILED(hr)) {
    gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
        << "Failed in PaintToTarget 2";
  mContext->CopyResource(readTexture, backBuf);
    HandleError(hr);
    return;
  }
  mContext->CopyResource(readTexture, backBuf);

    gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
  D3D11_MAPPED_SUBRESOURCE map;
  hr = mContext->Map(readTexture, 0, D3D11_MAP_READ, 0, &map);
  if (FAILED(hr)) {
    gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
        << "Failed in PaintToTarget 3";
  RefPtr<DataSourceSurface> sourceSurface =
    HandleError(hr);
    return;
  }
  RefPtr<DataSourceSurface> sourceSurface =
      Factory::CreateWrappingDataSourceSurface(
                       IntRect(0, 0, bbDesc.Width, bbDesc.Height),
          (uint8_t*)map.pData, map.RowPitch,
          IntSize(bbDesc.Width, bbDesc.Height), SurfaceFormat::B8G8R8A8);
  mTarget->CopySurface(sourceSurface,
                       IntRect(0, 0, bbDesc.Width, bbDesc.Height),
}
                       IntPoint(-mTargetBounds.X(), -mTargetBounds.Y()));

  mTarget->Flush();
  mContext->Unmap(readTexture, 0);
}
  gfxCriticalNote << "[D3D11] " << aContext << " failed: " << hexa(hr) << ", "

bool CompositorD3D11::Failed(HRESULT hr, const char* aContext) {
  if (SUCCEEDED(hr)) return false;
  return true;

  gfxCriticalNote << "[D3D11] " << aContext << " failed: " << hexa(hr) << ", "
                  << (int)mVerifyBuffersFailed;
  if (SUCCEEDED(hr)) {
  return true;
}

void CompositorD3D11::HandleError(HRESULT hr, Severity aSeverity) {
  if (SUCCEEDED(hr)) {
    MOZ_CRASH("GFX: Unrecoverable D3D11 error");
    return;
  }

  if (aSeverity == Critical) {
    MOZ_CRASH("GFX: Unrecoverable D3D11 error");
  }
                    << (int)mVerifyBuffersFailed;

  if (mDevice && DeviceManagerDx::Get()->GetCompositorDevice() != mDevice) {
    gfxCriticalNote << "Out of sync D3D11 devices in HandleError, "
                    << (int)mVerifyBuffersFailed;
  }


  HRESULT hrOnReset = S_OK;
  bool deviceRemoved = hr == DXGI_ERROR_DEVICE_REMOVED;

  if (deviceRemoved && mDevice) {
    if (hrOnReset != S_OK) {
    hrOnReset = mDevice->GetDeviceRemovedReason();
  } else if (hr == DXGI_ERROR_INVALID_CALL && mDevice) {
    hrOnReset = mDevice->GetDeviceRemovedReason();
    if (hrOnReset != S_OK) {
      deviceRemoved = true;
  // Device reset may not be an error on our side, but can mess things up so
    }
  }

  // Device reset may not be an error on our side, but can mess things up so
  // it's useful to see it in the reports.
      << hexa(hr) << ", " << hexa(hrOnReset) << ", "
  gfxCriticalError(CriticalLog::DefaultOptions(!deviceRemoved))
      << (deviceRemoved ? "[CompositorD3D11] device removed with error code: "
  // Crash if we are making invalid calls outside of device removal
                        : "[CompositorD3D11] error code: ")
      << hexa(hr) << ", " << hexa(hrOnReset) << ", "
      << (int)mVerifyBuffersFailed;

  // Crash if we are making invalid calls outside of device removal
  if (hr == DXGI_ERROR_INVALID_CALL) {
  }
    gfxDevCrash(deviceRemoved ? LogReason::D3D11InvalidCallDeviceRemoved
                              : LogReason::D3D11InvalidCall)
        << "Invalid D3D11 api call";
  }
}

  if (aSeverity == Recoverable) {
    NS_WARNING("Encountered a recoverable D3D11 error");
  }
}

}  // namespace layers
}  // namespace mozilla