BsScenePicking.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Scene/BsScenePicking.h"
  4. #include "Scene/BsSceneManager.h"
  5. #include "Image/BsColor.h"
  6. #include "Math/BsMatrix4.h"
  7. #include "Debug/BsDebug.h"
  8. #include "Math/BsMath.h"
  9. #include "Components/BsCRenderable.h"
  10. #include "Scene/BsSceneObject.h"
  11. #include "Mesh/BsMesh.h"
  12. #include "Math/BsConvexVolume.h"
  13. #include "Components/BsCCamera.h"
  14. #include "CoreThread/BsCoreThread.h"
  15. #include "RenderAPI/BsRenderAPI.h"
  16. #include "Material/BsMaterial.h"
  17. #include "Material/BsPass.h"
  18. #include "RenderAPI/BsRasterizerState.h"
  19. #include "RenderAPI/BsRenderTexture.h"
  20. #include "Image/BsPixelData.h"
  21. #include "RenderAPI/BsGpuParams.h"
  22. #include "Material/BsGpuParamsSet.h"
  23. #include "Utility/BsBuiltinEditorResources.h"
  24. #include "Material/BsShader.h"
  25. #include "Renderer/BsRenderer.h"
  26. #include "Scene/BsGizmoManager.h"
  27. #include "Renderer/BsRendererUtility.h"
  28. using namespace std::placeholders;
  29. namespace bs
  30. {
  31. ScenePicking::ScenePicking()
  32. {
  33. mCore = bs_new<ct::ScenePicking>();
  34. for (UINT32 i = 0; i < 3; i++)
  35. {
  36. HMaterial matPicking = BuiltinEditorResources::instance().createPicking((CullingMode)i);
  37. HMaterial matPickingAlpha = BuiltinEditorResources::instance().createPickingAlpha((CullingMode)i);
  38. mCore->mMaterials[i] = matPicking->getCore();
  39. mCore->mMaterials[3 + i] = matPickingAlpha->getCore();
  40. }
  41. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::initialize, mCore));
  42. }
  43. ScenePicking::~ScenePicking()
  44. {
  45. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::destroy, mCore));
  46. }
  47. HSceneObject ScenePicking::pickClosestObject(const SPtr<Camera>& cam, const Vector2I& position, const Vector2I& area,
  48. Vector<HSceneObject>& ignoreRenderables, SnapData* data)
  49. {
  50. Vector<HSceneObject> selectedObjects = pickObjects(cam, position, area, ignoreRenderables, data);
  51. if (selectedObjects.size() == 0)
  52. return HSceneObject();
  53. if (data != nullptr)
  54. {
  55. Matrix3 rotation;
  56. selectedObjects[0]->getTransform().getRotation().toRotationMatrix(rotation);
  57. data->normal = rotation.inverse().transpose().transform(data->normal);
  58. }
  59. return selectedObjects[0];
  60. }
  61. Vector<HSceneObject> ScenePicking::pickObjects(const SPtr<Camera>& cam, const Vector2I& position, const Vector2I& area,
  62. Vector<HSceneObject>& ignoreRenderables, SnapData* data)
  63. {
  64. auto comparePickElement = [&] (const ScenePicking::RenderablePickData& a, const ScenePicking::RenderablePickData& b)
  65. {
  66. // Sort by alpha setting first, then by cull mode, then by index
  67. if (a.alpha == b.alpha)
  68. {
  69. if (a.cullMode == b.cullMode)
  70. return a.index > b.index;
  71. else
  72. return (UINT32)a.cullMode > (UINT32)b.cullMode;
  73. }
  74. else
  75. return (UINT32)a.alpha > (UINT32)b.alpha;
  76. };
  77. Matrix4 viewProjMatrix = cam->getProjectionMatrixRS() * cam->getViewMatrix();
  78. Vector<HRenderable> renderables = gSceneManager().findComponents<CRenderable>(true);
  79. RenderableSet pickData(comparePickElement);
  80. Map<UINT32, HSceneObject> idxToRenderable;
  81. for (auto& renderable : renderables)
  82. {
  83. HSceneObject so = renderable->SO();
  84. HMesh mesh = renderable->getMesh();
  85. if (!mesh.isLoaded())
  86. continue;
  87. bool found = false;
  88. for (UINT32 i = 0; i < (UINT32)ignoreRenderables.size(); i++)
  89. {
  90. if (ignoreRenderables[i] == so)
  91. {
  92. found = true;
  93. break;
  94. }
  95. }
  96. if (found)
  97. continue;
  98. Bounds worldBounds = mesh->getProperties().getBounds();
  99. Matrix4 worldTransform = so->getWorldMatrix();
  100. worldBounds.transformAffine(worldTransform);
  101. const ConvexVolume& frustum = cam->getWorldFrustum();
  102. if (frustum.intersects(worldBounds.getSphere()))
  103. {
  104. // More precise with the box
  105. if (frustum.intersects(worldBounds.getBox()))
  106. {
  107. for (UINT32 i = 0; i < mesh->getProperties().getNumSubMeshes(); i++)
  108. {
  109. UINT32 idx = (UINT32)pickData.size();
  110. bool useAlphaShader = false;
  111. SPtr<RasterizerState> rasterizerState;
  112. HMaterial originalMat = renderable->getMaterial(i);
  113. if (originalMat != nullptr && originalMat->getNumPasses() > 0)
  114. {
  115. SPtr<Pass> firstPass = originalMat->getPass(0); // Note: We only ever check the first pass, problem?
  116. useAlphaShader = firstPass->hasBlending();
  117. if (firstPass->getRasterizerState() == nullptr)
  118. rasterizerState = RasterizerState::getDefault();
  119. else
  120. rasterizerState = firstPass->getRasterizerState();
  121. }
  122. else
  123. rasterizerState = RasterizerState::getDefault();
  124. CullingMode cullMode = rasterizerState->getProperties().getCullMode();
  125. HTexture mainTexture;
  126. if (useAlphaShader)
  127. mainTexture = originalMat->getTexture("gAlbedoTex");
  128. idxToRenderable[idx] = so;
  129. Matrix4 wvpTransform = viewProjMatrix * worldTransform;
  130. pickData.insert({ mesh->getCore(), idx, wvpTransform, useAlphaShader, cullMode, mainTexture });
  131. }
  132. }
  133. }
  134. }
  135. UINT32 firstGizmoIdx = (UINT32)pickData.size();
  136. SPtr<ct::RenderTarget> target = cam->getViewport()->getTarget()->getCore();
  137. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::corePickingBegin, mCore, target,
  138. cam->getViewport()->getArea(), std::cref(pickData), position, area));
  139. GizmoManager::instance().renderForPicking(cam, [&](UINT32 inputIdx) { return encodeIndex(firstGizmoIdx + inputIdx); });
  140. AsyncOp op = gCoreThread().queueReturnCommand(std::bind(&ct::ScenePicking::corePickingEnd, mCore, target,
  141. cam->getViewport()->getArea(), position, area, data != nullptr, _1));
  142. gCoreThread().submit(true);
  143. assert(op.hasCompleted());
  144. PickResults pickResults = op.getReturnValue<PickResults>();
  145. if (data != nullptr)
  146. {
  147. data->pickPosition = cam->screenToWorldPointDeviceDepth(position, pickResults.depth);
  148. data->normal = pickResults.normal;
  149. }
  150. Vector<UINT32> selectedObjects = pickResults.objects;
  151. Vector<HSceneObject> results;
  152. for (auto& selectedObjectIdx : selectedObjects)
  153. {
  154. if (selectedObjectIdx < firstGizmoIdx)
  155. {
  156. auto iterFind = idxToRenderable.find(selectedObjectIdx);
  157. if (iterFind != idxToRenderable.end())
  158. results.push_back(iterFind->second);
  159. }
  160. else
  161. {
  162. UINT32 gizmoIdx = selectedObjectIdx - firstGizmoIdx;
  163. HSceneObject so = GizmoManager::instance().getSceneObject(gizmoIdx);
  164. if (so)
  165. results.push_back(so);
  166. }
  167. }
  168. return results;
  169. }
  170. Color ScenePicking::encodeIndex(UINT32 index)
  171. {
  172. Color encoded;
  173. encoded.r = (index & 0xFF) / 255.0f;
  174. encoded.g = ((index >> 8) & 0xFF) / 255.0f;
  175. encoded.b = ((index >> 16) & 0xFF) / 255.0f;
  176. encoded.a = 1.0f;
  177. if (((index >> 24) & 0xFF))
  178. LOGERR("Index when picking out of valid range.");
  179. return encoded;
  180. }
  181. UINT32 ScenePicking::decodeIndex(Color color)
  182. {
  183. UINT32 r = Math::roundToInt(color.r * 255.0f);
  184. UINT32 g = Math::roundToInt(color.g * 255.0f);
  185. UINT32 b = Math::roundToInt(color.b * 255.0f);
  186. return (r & 0xFF) | ((g & 0xFF) << 8) | ((b & 0xFF) << 16);
  187. }
  188. namespace ct
  189. {
  190. const float ScenePicking::ALPHA_CUTOFF = 0.5f;
  191. PickingParamBlockDef gPickingParamBlockDef;
  192. void ScenePicking::initialize()
  193. {
  194. // Do nothing
  195. }
  196. void ScenePicking::destroy()
  197. {
  198. bs_delete(this);
  199. }
  200. void ScenePicking::corePickingBegin(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  201. const bs::ScenePicking::RenderableSet& renderables, const Vector2I& position, const Vector2I& area)
  202. {
  203. RenderAPI& rs = RenderAPI::instance();
  204. SPtr<RenderTexture> rtt = std::static_pointer_cast<RenderTexture>(target);
  205. SPtr<Texture> outputTexture = rtt->getColorTexture(0);
  206. TextureProperties outputTextureProperties = outputTexture->getProperties();
  207. TEXTURE_DESC normalTexDesc;
  208. normalTexDesc.type = TEX_TYPE_2D;
  209. normalTexDesc.width = outputTextureProperties.getWidth();
  210. normalTexDesc.height = outputTextureProperties.getHeight();
  211. normalTexDesc.format = PF_RG11B10F;
  212. normalTexDesc.usage = TU_RENDERTARGET;
  213. SPtr<Texture> normalsTexture = Texture::create(normalTexDesc);
  214. SPtr<Texture> depthTexture = rtt->getDepthStencilTexture();
  215. RENDER_TEXTURE_DESC pickingMRT;
  216. pickingMRT.colorSurfaces[0].face = 0;
  217. pickingMRT.colorSurfaces[0].texture = outputTexture;
  218. pickingMRT.colorSurfaces[1].face = 0;
  219. pickingMRT.colorSurfaces[1].texture = normalsTexture;
  220. pickingMRT.depthStencilSurface.face = 0;
  221. pickingMRT.depthStencilSurface.texture = depthTexture;
  222. mPickingTexture = RenderTexture::create(pickingMRT);
  223. rs.setRenderTarget(mPickingTexture);
  224. rs.setViewport(viewportArea);
  225. rs.clearRenderTarget(FBT_COLOR | FBT_DEPTH | FBT_STENCIL, Color::White);
  226. rs.setScissorRect(position.x, position.y, position.x + area.x, position.y + area.y);
  227. gRendererUtility().setPass(mMaterials[0]);
  228. UINT32 numEntries = (UINT32)renderables.size();
  229. UINT32* renderableIndices = bs_stack_alloc<UINT32>(numEntries);
  230. UINT32 typeCounters[6];
  231. bs_zero_out(typeCounters);
  232. UINT32 idx = 0;
  233. for (auto& renderable : renderables)
  234. {
  235. UINT32 typeIdx;
  236. if (!renderable.alpha)
  237. typeIdx = 0;
  238. else
  239. typeIdx = 3;
  240. typeIdx += (UINT32)renderable.cullMode;
  241. UINT32 renderableIdx = typeCounters[typeIdx];
  242. renderableIndices[idx] = renderableIdx;
  243. SPtr<GpuParamsSet> paramsSet;
  244. if (renderableIdx >= mParamSets[typeIdx].size())
  245. {
  246. paramsSet = mMaterials[typeIdx]->createParamsSet();
  247. mParamSets[typeIdx].push_back(paramsSet);
  248. }
  249. else
  250. paramsSet = mParamSets[typeIdx][renderableIdx];
  251. SPtr<GpuParamBlockBuffer> paramBuffer;
  252. if (idx >= mParamBuffers.size())
  253. {
  254. paramBuffer = gPickingParamBlockDef.createBuffer();
  255. mParamBuffers.push_back(paramBuffer);
  256. }
  257. else
  258. paramBuffer = mParamBuffers[idx];
  259. paramsSet->setParamBlockBuffer("Uniforms", paramBuffer, true);
  260. Color color = bs::ScenePicking::encodeIndex(renderable.index);
  261. gPickingParamBlockDef.gMatViewProj.set(paramBuffer, renderable.wvpTransform);
  262. gPickingParamBlockDef.gAlphaCutoff.set(paramBuffer, ALPHA_CUTOFF);
  263. gPickingParamBlockDef.gColorIndex.set(paramBuffer, color);
  264. typeCounters[typeIdx]++;
  265. idx++;
  266. }
  267. UINT32 activeMaterialIdx = 0;
  268. idx = 0;
  269. for (auto& renderable : renderables)
  270. {
  271. UINT32 typeIdx;
  272. if (!renderable.alpha)
  273. typeIdx = 0;
  274. else
  275. typeIdx = 3;
  276. typeIdx += (UINT32)renderable.cullMode;
  277. if (activeMaterialIdx != typeIdx)
  278. {
  279. gRendererUtility().setPass(mMaterials[typeIdx]);
  280. activeMaterialIdx = typeIdx;
  281. }
  282. UINT32 renderableIdx = renderableIndices[idx];
  283. gRendererUtility().setPassParams(mParamSets[typeIdx][renderableIdx]);
  284. UINT32 numSubmeshes = renderable.mesh->getProperties().getNumSubMeshes();
  285. for (UINT32 i = 0; i < numSubmeshes; i++)
  286. gRendererUtility().draw(renderable.mesh, renderable.mesh->getProperties().getSubMesh(i));
  287. idx++;
  288. }
  289. bs_stack_free(renderableIndices);
  290. }
  291. void ScenePicking::corePickingEnd(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  292. const Vector2I& position, const Vector2I& area, bool gatherSnapData, AsyncOp& asyncOp)
  293. {
  294. const RenderTargetProperties& rtProps = target->getProperties();
  295. RenderAPI& rs = RenderAPI::instance();
  296. rs.setRenderTarget(nullptr);
  297. rs.submitCommandBuffer(nullptr);
  298. if (rtProps.isWindow)
  299. {
  300. BS_EXCEPT(NotImplementedException, "Picking is not supported on render windows as framebuffer readback methods aren't implemented");
  301. }
  302. SPtr<Texture> outputTexture = mPickingTexture->getColorTexture(0);
  303. SPtr<Texture> normalsTexture = mPickingTexture->getColorTexture(1);
  304. SPtr<Texture> depthTexture = mPickingTexture->getDepthStencilTexture();
  305. if (position.x < 0 || position.x >= (INT32)outputTexture->getProperties().getWidth() ||
  306. position.y < 0 || position.y >= (INT32)outputTexture->getProperties().getHeight())
  307. {
  308. mPickingTexture = nullptr;
  309. asyncOp._completeOperation(Vector<UINT32>());
  310. return;
  311. }
  312. SPtr<PixelData> outputPixelData = outputTexture->getProperties().allocBuffer(0, 0);
  313. SPtr<PixelData> normalsPixelData;
  314. SPtr<PixelData> depthPixelData;
  315. if (gatherSnapData)
  316. {
  317. normalsPixelData = normalsTexture->getProperties().allocBuffer(0, 0);
  318. depthPixelData = depthTexture->getProperties().allocBuffer(0, 0);
  319. }
  320. outputTexture->readData(*outputPixelData);
  321. Vector2I pickPosition = position;
  322. if(rtProps.requiresTextureFlipping)
  323. pickPosition.y = rtProps.height - (position.y + area.y);
  324. UINT32 maxWidth = std::min((UINT32)(pickPosition.x + area.x), outputPixelData->getWidth());
  325. UINT32 maxHeight = std::min((UINT32)(pickPosition.y + area.y), outputPixelData->getHeight());
  326. Map<UINT32, UINT32> selectionScores;
  327. for (UINT32 y = (UINT32)pickPosition.y; y < maxHeight; y++)
  328. {
  329. for (UINT32 x = (UINT32)pickPosition.x; x < maxWidth; x++)
  330. {
  331. Color color = outputPixelData->getColorAt(x, y);
  332. UINT32 index = bs::ScenePicking::decodeIndex(color);
  333. if (index == 0x00FFFFFF) // Nothing selected
  334. continue;
  335. auto iterFind = selectionScores.find(index);
  336. if (iterFind == selectionScores.end())
  337. selectionScores[index] = 1;
  338. else
  339. iterFind->second++;
  340. }
  341. }
  342. // Sort by score
  343. struct SelectedObject { UINT32 index; UINT32 score; };
  344. Vector<SelectedObject> selectedObjects(selectionScores.size());
  345. UINT32 idx = 0;
  346. for (auto& selectionScore : selectionScores)
  347. {
  348. selectedObjects[idx++] = { selectionScore.first, selectionScore.second };
  349. }
  350. std::sort(selectedObjects.begin(), selectedObjects.end(),
  351. [&](const SelectedObject& a, const SelectedObject& b)
  352. {
  353. return b.score < a.score;
  354. });
  355. Vector<UINT32> objects;
  356. for (auto& selectedObject : selectedObjects)
  357. objects.push_back(selectedObject.index);
  358. PickResults result;
  359. if (gatherSnapData)
  360. {
  361. depthTexture->readData(*depthPixelData);
  362. normalsTexture->readData(*normalsPixelData);
  363. Vector2I samplePixel = position;
  364. if (rtProps.requiresTextureFlipping)
  365. samplePixel.y = depthPixelData->getHeight() - samplePixel.y;
  366. float depth = depthPixelData->getDepthAt(samplePixel.x, samplePixel.y);
  367. Color normal = normalsPixelData->getColorAt(samplePixel.x, samplePixel.y);
  368. const RenderAPIInfo& rapiInfo = rs.getAPIInfo();
  369. float max = rapiInfo.getMaximumDepthInputValue();
  370. float min = rapiInfo.getMinimumDepthInputValue();
  371. depth = depth * Math::abs(max - min) + min;
  372. result.depth = depth;
  373. result.normal = Vector3((normal.r * 2) - 1, (normal.g * 2) - 1, (normal.b * 2) - 1);
  374. }
  375. else
  376. result.depth = 0;
  377. mPickingTexture = nullptr;
  378. result.objects = objects;
  379. asyncOp._completeOperation(result);
  380. }
  381. }
  382. }