BsScenePicking.cpp 15 KB

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