本文整理汇总了C++中Renderer类的典型用法代码示例。如果您正苦于以下问题:C++ Renderer类的具体用法?C++ Renderer怎么用?C++ Renderer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Renderer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: coords
int
NineNodeMixedQuad::displaySelf(Renderer &theViewer, int displayMode, float fact)
{
// first determine the end points of the quad based on
// the display factor (a measure of the distorted image)
// store this information in 4 3d vectors v1 through v4
const Vector &end1Crd = nodePointers[0]->getCrds();
const Vector &end2Crd = nodePointers[4]->getCrds();
const Vector &end3Crd = nodePointers[1]->getCrds();
const Vector &end4Crd = nodePointers[5]->getCrds();
const Vector &end5Crd = nodePointers[2]->getCrds();
const Vector &end6Crd = nodePointers[6]->getCrds();
const Vector &end7Crd = nodePointers[3]->getCrds();
const Vector &end8Crd = nodePointers[7]->getCrds();
const Vector &end1Disp = nodePointers[0]->getDisp();
const Vector &end2Disp = nodePointers[4]->getDisp();
const Vector &end3Disp = nodePointers[1]->getDisp();
const Vector &end4Disp = nodePointers[5]->getDisp();
const Vector &end5Disp = nodePointers[2]->getDisp();
const Vector &end6Disp = nodePointers[6]->getDisp();
const Vector &end7Disp = nodePointers[3]->getDisp();
const Vector &end8Disp = nodePointers[7]->getDisp();
static Matrix coords(8,3) ;
static Vector values(8) ;
static Vector P(8) ;
coords.Zero( ) ;
values(0) = 1 ;
values(1) = 1 ;
values(2) = 1 ;
values(3) = 1 ;
values(4) = 1 ;
values(5) = 1 ;
values(6) = 1 ;
values(7) = 1 ;
if (displayMode < 3 && displayMode > 0)
P = this->getResistingForce();
for (int i = 0; i < 2; i++) {
coords(0,i) = end1Crd(i) + end1Disp(i)*fact;
coords(1,i) = end2Crd(i) + end2Disp(i)*fact;
coords(2,i) = end3Crd(i) + end3Disp(i)*fact;
coords(3,i) = end4Crd(i) + end4Disp(i)*fact;
coords(4,i) = end5Crd(i) + end5Disp(i)*fact;
coords(5,i) = end6Crd(i) + end6Disp(i)*fact;
coords(6,i) = end7Crd(i) + end7Disp(i)*fact;
coords(7,i) = end8Crd(i) + end8Disp(i)*fact;
/* if (displayMode < 3 && displayMode > 0)
values(i) = P(displayMode*2+i);
else
values(i) = 1; */
}
//opserr << coords;
int error = 0;
error += theViewer.drawPolygon (coords, values);
return error;
}
示例2: goTo
void Url::goTo()
{
Selection sel;
if (urlStr == "")
return;
Simulation *sim = appCore->getSimulation();
Renderer *renderer = appCore->getRenderer();
std::string::size_type pos;
sim->update(0.0);
switch(type) {
case Absolute:// Intentional Fall-Through
case Relative:
sim->setFrame(ref.getCoordinateSystem(), ref.getRefObject(), ref.getTargetObject());
sim->getActiveObserver()->setFOV(degToRad(fieldOfView));
appCore->setZoomFromFOV();
sim->setTimeScale(timeScale);
sim->setPauseState(pauseState);
appCore->setLightDelayActive(lightTimeDelay);
if (selectedStr != "")
{
pos = 0;
while(pos != std::string::npos)
{
pos = selectedStr.find(":", pos + 1);
if (pos != std::string::npos) selectedStr[pos]='/';
}
sel = sim->findObjectFromPath(selectedStr);
sim->setSelection(sel);
}
else
{
sim->setSelection(Selection());
}
if (trackedStr != "")
{
pos = 0;
while(pos != std::string::npos)
{
pos = trackedStr.find(":", pos + 1);
if (pos != std::string::npos) trackedStr[pos]='/';
}
sel = sim->findObjectFromPath(trackedStr);
sim->setTrackedObject(sel);
}
else
{
if (!sim->getTrackedObject().empty())
sim->setTrackedObject(Selection());
}
// Intentional Fall-Through
case Settings:
renderer->setRenderFlags(renderFlags);
renderer->setLabelMode(labelMode);
break;
}
if (version >= 3)
{
switch (timeSource)
{
case UseUrlTime:
sim->setTime((double) date);
break;
case UseSimulationTime:
// Leave the current simulation time unmodified
break;
case UseSystemTime:
sim->setTime(astro::UTCtoTDB(astro::Date::systemDate()));
break;
default:
break;
}
// Position and orientation stored in frame coordinates; convert them
// to universal and set the observer position.
double tdb = sim->getTime();
coord = sim->getObserver().getFrame()->convertToUniversal(coord, tdb);
Quatd q(orientation.w, orientation.x, orientation.y, orientation.z);
q = sim->getObserver().getFrame()->convertToUniversal(q, tdb);
sim->setObserverPosition(coord);
sim->setObserverOrientation(Quatf((float) q.w, (float) q.x, (float) q.y, (float) q.z));
}
else
{
switch(type) {
case Absolute:
sim->setTime((double) date);
sim->setObserverPosition(coord);
sim->setObserverOrientation(orientation);
break;
case Relative:
sim->gotoSelectionLongLat(0, astro::kilometersToLightYears(distance), (float) (longitude * PI / 180), (float) (latitude * PI / 180), Vec3f(0, 1, 0));
break;
case Settings:
break;
//.........这里部分代码省略.........
示例3: Done
void TextureShader::Done()
{
Renderer* renderer = GraphicSubsystem::Instance()->GetRenderer();
renderer->GetTextureStage(0)->ResetTexture();
renderer->SetMaterial( Material() );
}
示例4: main
int main(int argc, char* args[]) {
Renderer* renderer = new Renderer();
if(!renderer->init()) {
printf( "Failed to initialize!\n" );
} else {
Character* c = new Character(new Texture("res/img/dot.bmp", 200, 200));
renderer->addTexture(new Texture("res/img/waterlevel2.png", 0, 0));
renderer->render();
renderer->addTexture(c->getTexture());
bool quit = false;
SDL_Event e;
LoadCollisionMap lcm;
list<Circle> circlesList;
circlesList = lcm.load();
list<Circle> l;
Circle c1(200,0,10);
l.push_back(c1);
CollisionDetector cd;
int y = 0;
while(!cd.hasCollision(circlesList, l)) {
l.pop_back();
y += 1;
Circle c1(200,y,10);
l.push_back(c1);
}
y -= 1;
c->setPosX(200);
c->setPosY(y);
renderer->render();
int mVelX = 0;
int DOT_VEL = 1;
while(!quit) {
while(SDL_PollEvent(&e) != 0) {
if(e.type == SDL_QUIT) {
quit = true;
}
if(e.type == SDL_KEYDOWN && e.key.repeat == 0) {
switch(e.key.keysym.sym) {
case SDLK_LEFT: mVelX -= DOT_VEL; break;
case SDLK_RIGHT: mVelX += DOT_VEL; break;
}
} else if(e.type == SDL_KEYUP && e.key.repeat == 0) {
switch(e.key.keysym.sym) {
case SDLK_LEFT: mVelX += DOT_VEL; break;
case SDLK_RIGHT: mVelX -= DOT_VEL; break;
}
}
}
c->setPosX(c->getPosX() + mVelX);
LoadCollisionMap lcm;
list<Circle> circlesList;
circlesList = lcm.load();
int mPosX = c->getPosX();
int mPosY = c->getPosY();
list<Circle> l;
Circle c1(mPosX,mPosY,10);
l.push_back(c1);
CollisionDetector cd;
int y = mPosY;
while(cd.hasCollision(circlesList, l)) {
l.pop_back();
y -= 1;
Circle c1(mPosX,y,10);
l.push_back(c1);
};
while(!cd.hasCollision(circlesList, l)) {
l.pop_back();
y += 1;
Circle c1(mPosX,y,10);
l.push_back(c1);
};
c->setPosY(y);
renderer->render();
}
}
return 0;
}
示例5: HELIUM_TRACE
/// @copydoc RendererInitialization::Initialize()
bool RendererInitializationWin::Initialize()
{
WindowManager* pWindowManager = WindowManager::GetStaticInstance();
if( !pWindowManager )
{
HELIUM_TRACE(
TraceLevels::Info,
( TXT( "RendererInitializationWin::Initialize(): No window manager created. A window manager is necessary for " )
TXT( "RendererInitializationWin execution.\n" ) ) );
return false;
}
if( !D3D9Renderer::CreateStaticInstance() )
{
return false;
}
Renderer* pRenderer = D3D9Renderer::GetStaticInstance();
HELIUM_ASSERT( pRenderer );
if( !pRenderer->Initialize() )
{
Renderer::DestroyStaticInstance();
return false;
}
// Create the main application window.
Config& rConfig = Config::GetStaticInstance();
StrongPtr< GraphicsConfig > spGraphicsConfig(
rConfig.GetConfigObject< GraphicsConfig >( Name( TXT( "GraphicsConfig" ) ) ) );
HELIUM_ASSERT( spGraphicsConfig );
uint32_t displayWidth = spGraphicsConfig->GetWidth();
uint32_t displayHeight = spGraphicsConfig->GetHeight();
bool bFullscreen = spGraphicsConfig->GetFullscreen();
bool bVsync = spGraphicsConfig->GetVsync();
Window::Parameters windowParameters;
windowParameters.pTitle = TXT( "Helium" );
windowParameters.width = displayWidth;
windowParameters.height = displayHeight;
windowParameters.bFullscreen = bFullscreen;
m_pMainWindow = pWindowManager->Create( windowParameters );
HELIUM_ASSERT( m_pMainWindow );
if( !m_pMainWindow )
{
HELIUM_TRACE( TraceLevels::Error, TXT( "Failed to create main application window.\n" ) );
return false;
}
m_pMainWindow->SetOnDestroyed( Delegate<Window*>( this, &RendererInitializationWin::OnMainWindowDestroyed ) );
Renderer::ContextInitParameters contextInitParams;
contextInitParams.pWindow = m_pMainWindow->GetHandle();
contextInitParams.displayWidth = displayWidth;
contextInitParams.displayHeight = displayHeight;
contextInitParams.bFullscreen = bFullscreen;
contextInitParams.bVsync = bVsync;
bool bContextCreateResult = pRenderer->CreateMainContext( contextInitParams );
HELIUM_ASSERT( bContextCreateResult );
if( !bContextCreateResult )
{
HELIUM_TRACE( TraceLevels::Error, TXT( "Failed to create main renderer context.\n" ) );
return false;
}
// Create and initialize the render resource manager.
RenderResourceManager& rRenderResourceManager = RenderResourceManager::GetStaticInstance();
rRenderResourceManager.Initialize();
// Create and initialize the dynamic drawing interface.
DynamicDrawer& rDynamicDrawer = DynamicDrawer::GetStaticInstance();
if( !rDynamicDrawer.Initialize() )
{
HELIUM_TRACE( TraceLevels::Error, TXT( "Failed to initialize dynamic drawing support.\n" ) );
return false;
}
return true;
}
示例6: renderMeshLocally
void SceneMesh::renderMeshLocally() {
Renderer *renderer = CoreServices::getInstance()->getRenderer();
if(skeleton) {
for(int i=0; i < mesh->getPolygonCount(); i++) {
Polygon *polygon = mesh->getPolygon(i);
unsigned int vCount = polygon->getVertexCount();
for(int j=0; j < vCount; j++) {
Vertex *vert = polygon->getVertex(j);
Vector3 norm;
Vector3 aPos = vert->restPosition;
Vector3 tPos;
Number mult = 1;
/*
Number mult = 0;
for(int b =0; b < vert->getNumBoneAssignments(); b++) {
BoneAssignment *bas = vert->getBoneAssignment(b);
mult += bas->weight;
}
mult = 1.0f/mult;
*/
for(int b =0; b < vert->getNumBoneAssignments(); b++) {
BoneAssignment *bas = vert->getBoneAssignment(b);
Bone *bone = bas->bone;
if(bone) {
Matrix4 restMatrix = bone->getRestMatrix();
Matrix4 finalMatrix = bone->getFinalMatrix();
Vector3 vec = restMatrix * aPos;
tPos += finalMatrix * vec * (bas->weight*mult);
Vector3 nvec = vert->restNormal;
nvec = restMatrix.rotateVector(nvec);
nvec = finalMatrix.rotateVector(nvec);
norm += nvec * (bas->weight*mult);
}
}
vert->x = tPos.x;
vert->y = tPos.y;
vert->z = tPos.z;
norm.Normalize();
vert->setNormal(norm.x, norm.y, norm.z);
}
}
mesh->arrayDirtyMap[RenderDataArray::VERTEX_DATA_ARRAY] = true;
mesh->arrayDirtyMap[RenderDataArray::NORMAL_DATA_ARRAY] = true;
mesh->arrayDirtyMap[RenderDataArray::TANGENT_DATA_ARRAY] = true;
}
if(mesh->useVertexColors) {
renderer->pushDataArrayForMesh(mesh, RenderDataArray::COLOR_DATA_ARRAY);
}
renderer->pushDataArrayForMesh(mesh, RenderDataArray::VERTEX_DATA_ARRAY);
renderer->pushDataArrayForMesh(mesh, RenderDataArray::NORMAL_DATA_ARRAY);
renderer->pushDataArrayForMesh(mesh, RenderDataArray::TANGENT_DATA_ARRAY);
renderer->pushDataArrayForMesh(mesh, RenderDataArray::TEXCOORD_DATA_ARRAY);
renderer->drawArrays(mesh->getMeshType());
}
示例7: engine
FilamentApp::CView::CView(Renderer& renderer, std::string name)
: engine(*renderer.getEngine()), mName(name) {
view = engine.createView();
view->setClearColor({ 0 });
view->setName(name.c_str());
}
示例8: drawFilter
void Screen::drawFilter() {
if(!filterShaderMaterial)
return;
Renderer *renderer = CoreServices::getInstance()->getRenderer();
renderer->bindFrameBufferTexture(originalSceneTexture);
Render();
renderer->unbindFramebuffers();
ShaderBinding* materialBinding;
for(int i=0; i < filterShaderMaterial->getNumShaders(); i++) {
materialBinding = filterShaderMaterial->getShaderBinding(i);
for(int j=0; j < materialBinding->getNumColorTargetBindings(); j++) {
RenderTargetBinding *colorBinding = materialBinding->getColorTargetBinding(j);
materialBinding->clearTexture(colorBinding->name);
materialBinding->addTexture(colorBinding->name, originalSceneTexture);
}
renderer->applyMaterial(filterShaderMaterial, localShaderOptions[i], i);
if(i==filterShaderMaterial->getNumShaders()-1) {
renderer->loadIdentity();
renderer->drawScreenQuad(renderer->getXRes(), renderer->getYRes());
} else {
for(int j=0; j < materialBinding->getNumOutTargetBindings(); j++) {
renderer->bindFrameBufferTexture(materialBinding->getOutTargetBinding(j)->texture);
renderer->drawScreenQuad(materialBinding->getOutTargetBinding(j)->width, materialBinding->getOutTargetBinding(j)->height);
renderer->unbindFramebuffers();
}
}
renderer->clearShader();
renderer->loadIdentity();
renderer->setOrthoMode();
}
}
示例9: main
int main()
{
initCrashSystem();
initMemorySystem();
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window *window = SDL_CreateWindow("",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640,
640,
SDL_WINDOW_OPENGL
|SDL_WINDOW_RESIZABLE
|SDL_WINDOW_SHOWN);
SDL_GLContext context = createContext(window);
SDL_GL_SetSwapInterval(1);
bool running = true;
float frametime = 0.0f;
Renderer *renderer = NEW(Renderer, NEW(GLBackend));
ResourceManager *resMgr = renderer->getResourceManager();
Scene *scene = NEW(Scene, renderer);
Scene *quadScene = NEW(Scene, renderer);
RenderTarget *target = NEW(RenderTarget, renderer);
RenderTarget *textureTarget = NEW(RenderTarget, renderer);
Framebuffer *framebuffer = textureTarget->addFramebuffer();
framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBAU8_Norm_InternalFormat);
framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::Red32F_InternalFormat);
framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBU8_Norm_InternalFormat);
framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBAU8_Norm_InternalFormat);
framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBU8_Norm_InternalFormat);
framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBU8_Norm_InternalFormat);
framebuffer->finish();
ResPtr<Model> model = resMgr->load("res/models/dragon.json").cast<Model>();
ResPtr<Mesh> quadMesh = resMgr->createMesh(resMgr->load("res/shaders/quad vertex.json").cast<Shader>(), Mesh::Triangles, 6);
VertexBuffer *quadVB = quadMesh->addPositions(renderer, MeshComponent(2, MeshComponent::Float32))->getVertexBuffer();
quadVB->alloc(sizeof(glm::vec2)*6);
glm::vec2 *quadPositions = (glm::vec2 *)quadVB->map(false, true);
quadPositions[0] = glm::vec2(-1.0f, -1.0f);
quadPositions[1] = glm::vec2( 1.0f, -1.0f);
quadPositions[2] = glm::vec2(-1.0f, 1.0f);
quadPositions[3] = glm::vec2(-1.0f, 1.0f);
quadPositions[4] = glm::vec2( 1.0f, -1.0f);
quadPositions[5] = glm::vec2( 1.0f, 1.0f);
quadVB->unmap();
ResPtr<Material> quadMaterial = resMgr->createMaterial(
resMgr->load("res/shaders/quad fragment.json").cast<Shader>());
quadMaterial->mUniforms["colorTexture"] = framebuffer->getColorTexture(0);
quadMaterial->mUniforms["depthTexture"] = framebuffer->getColorTexture(1);
quadMaterial->mUniforms["normalTexture"] = framebuffer->getColorTexture(2);
quadMaterial->mUniforms["materialTexture"] = framebuffer->getColorTexture(3);
quadMaterial->mUniforms["ambientTexture"] = framebuffer->getColorTexture(4);
quadMaterial->mUniforms["specularTexture"] = framebuffer->getColorTexture(5);
quadMaterial->mUniforms["lightDirection"] = glm::vec3(0.0f);
ResPtr<Model> quadModel = resMgr->createModel();
quadModel->mLODs.push_back(LOD(quadMesh, quadMaterial, 0.0f));
quadModel->sortLODs();
quadScene->createEntity(quadModel);
scene->mSkyboxTexture = resMgr->load("res/textures/enviroment texture.json").cast<Texture>();
Entity *entity = scene->createEntity(model);
float t = 0.0f;
bool fullscreen = false;
glm::vec3 cameraPosition(0.0f, 0.0f, 5.0f);
glm::vec2 cameraAngle(3.1415f, 0.0f);
float cameraSpeed = 3.0f;
float cameraRotateSpeed = 1.0f;
while (running)
{
Uint64 start = SDL_GetPerformanceCounter();
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
//.........这里部分代码省略.........
示例10: pOld
int ElTawil2D::displaySelf(Renderer &theViewer, int displayMode, float fact)
{
this->YieldSurface_BC2D::displaySelf(theViewer, displayMode, fact);
Vector pOld(3), pCurr(3);
Vector rgb(3);
rgb(0) = 0.1; rgb(1) = 0.5; rgb(2) = 0.5;
if(displayMode == this->SurfOnly)
{
rgb(0) = 0.7; rgb(1) = 0.7; rgb(2) = 1.0;
}
// double incr = ((yPosCap/capY) - (yNegCap/capY)) / 10;
double incr = fabs(0.33333333*yNegCap/capY);
if(fact < 1) incr = fact;
double xOld = 0;
double yOld = yNegCap/capY;
// hModel->toDeformedCoord(xOld, yOld);
double err = 1e-4;
for(double yc = yNegCap/capY; yc <= yPosCap/capY + err; yc = yc+incr)
{
double y = yc;
double yVal = y*capY;
double xVal;
if(y < 0)
{
xVal = xBal*(1 - pow( fabs(yVal/yNegCap) , ty));
}
else
{
xVal = xBal*(1 - pow( (yVal/yPosCap) , cz));
}
double x = xVal/capX;
if(displayMode==100)
opserr << "(undeformed) x = " << x << ", y = " << y;
double x1 = x;
double y1 = y;
double x2 = -x;
double y2 = y;
double x1Old = xOld;
double y1Old = yOld;
double x2Old = -xOld;
double y2Old = yOld;
hModel->toDeformedCoord(x1, y1);
hModel->toDeformedCoord(x1Old, y1Old);
hModel->toDeformedCoord(x2, y2);
hModel->toDeformedCoord(x2Old, y2Old);
// if(displayMode==100)
// opserr << " (deformed) x = " << x << ", y = " << y << endln;
pCurr(0) = x1;
pCurr(1) = y1;
pOld(0) = x1Old;
pOld(1) = y1Old;
theViewer.drawLine(pOld, pCurr, rgb, rgb);
pCurr(0) = x2;
pCurr(1) = y2;
pOld(0) = x2Old;
pOld(1) = y2Old;
theViewer.drawLine(pOld, pCurr, rgb, rgb);
xOld = x;
yOld = y;
}
// displayForcePoint(theViewer, displayMode, fact);
return 0;
}
示例11: ShaderRenderCommand
RCBindShader::RCBindShader( const Shader* shader, Renderer& renderer )
: ShaderRenderCommand( *renderer.rtMemPool() )
, m_shader( shader )
{
}
示例12: customRender
void ListBox::customRender()
{
Renderer* r = &Control::r_texturedRectRenderer;
Renderer* hlr = &Control::r_listBoxHighlightRenderer;
for(int y = 0; y < m_curRowNum; y++)
{
for(int x = 0; x < m_colNum; x++)
{
int i = y * m_colNum + x;
if( i == m_items.size())
break;
/*
// render texture
int offset_x = m_rect.x + x * m_itemWidth;
int offset_y = m_rect.y + y * m_itemHeight;
Rect itemRect(offset_x, offset_y, m_itemWidth, m_itemHeight);
*/
Rect itemRect = m_items[i].rect;
if (i == m_curIndex && m_curIndex >= 0)
{
float gap = 2;
hlr->enableShader();
hlr->setData(RENDER_PASS1, "u_x1", itemRect.x + gap);
hlr->setData(RENDER_PASS1, "u_x2", itemRect.x + itemRect.w - gap);
hlr->setData(RENDER_PASS1, "u_y1", Control::toGUICoord(itemRect.y + itemRect.h - gap) );
hlr->setData(RENDER_PASS1, "u_y2", Control::toGUICoord(itemRect.y + gap) );
updatePipeline(hlr, itemRect);
m_quadModel.render();
hlr->disableShader();
}
r->enableShader();
Rect tempRect = m_items[i].modelRect;
r->setData(RENDER_PASS1, "u_texture", 0, GL_TEXTURE0, m_items[i].textureID);
updatePipeline(r, tempRect);
m_quadModel.render();
r->disableShader();
// render text
Control::m_textEngine.render(m_items[i].text, m_items[i].textStartingX, m_items[i].textStartingY,
m_itemFont.size, m_itemFont.color, m_items[i].lineBreakInfo.lineBreaks);
}
}
}
示例13: Draw
void BatchGroup::Draw(View* view) const
{
Graphics* graphics = view->GetGraphics();
Renderer* renderer = view->GetRenderer();
if (instances_.Size() && !geometry_->IsEmpty())
{
// Draw as individual objects if instancing not supported
VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
if (!instanceBuffer || geometryType_ != GEOM_INSTANCED)
{
Batch::Prepare(view, false);
graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
for (unsigned i = 0; i < instances_.Size(); ++i)
{
if (graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, instances_[i].worldTransform_))
graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
geometry_->GetVertexStart(), geometry_->GetVertexCount());
}
}
else
{
Batch::Prepare(view, false);
// Get the geometry vertex buffers, then add the instancing stream buffer
// Hack: use a const_cast to avoid dynamic allocation of new temp vectors
Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
(geometry_->GetVertexBuffers());
PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
elementMasks.Push(instanceBuffer->GetElementMask());
// No stream offset support, instancing buffer not pre-filled with transforms: have to fill now
if (startIndex_ == M_MAX_UNSIGNED)
{
unsigned startIndex = 0;
while (startIndex < instances_.Size())
{
unsigned instances = instances_.Size() - startIndex;
if (instances > instanceBuffer->GetVertexCount())
instances = instanceBuffer->GetVertexCount();
// Copy the transforms
Matrix3x4* dest = (Matrix3x4*)instanceBuffer->Lock(0, instances, true);
if (dest)
{
for (unsigned i = 0; i < instances; ++i)
dest[i] = *instances_[i + startIndex].worldTransform_;
instanceBuffer->Unlock();
graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
graphics->SetVertexBuffers(vertexBuffers, elementMasks);
graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(),
geometry_->GetIndexCount(), geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
}
startIndex += instances;
}
}
// Stream offset supported and instancing buffer has been already filled, so just draw
else
{
graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
}
// Remove the instancing buffer & element mask now
vertexBuffers.Pop();
elementMasks.Pop();
}
}
}
示例14: Prepare
void Batch::Prepare(View* view, bool setModelTransform) const
{
if (!vertexShader_ || !pixelShader_)
return;
Graphics* graphics = view->GetGraphics();
Renderer* renderer = view->GetRenderer();
Node* cameraNode = camera_ ? camera_->GetNode() : 0;
Light* light = lightQueue_ ? lightQueue_->light_ : 0;
Texture2D* shadowMap = lightQueue_ ? lightQueue_->shadowMap_ : 0;
// Set pass / material-specific renderstates
if (pass_ && material_)
{
bool isShadowPass = pass_->GetType() == PASS_SHADOW;
BlendMode blend = pass_->GetBlendMode();
// Turn additive blending into subtract if the light is negative
if (light && light->IsNegative())
{
if (blend == BLEND_ADD)
blend = BLEND_SUBTRACT;
else if (blend == BLEND_ADDALPHA)
blend = BLEND_SUBTRACTALPHA;
}
graphics->SetBlendMode(blend);
renderer->SetCullMode(isShadowPass ? material_->GetShadowCullMode() : material_->GetCullMode(), camera_);
if (!isShadowPass)
{
const BiasParameters& depthBias = material_->GetDepthBias();
graphics->SetDepthBias(depthBias.constantBias_, depthBias.slopeScaledBias_);
}
graphics->SetDepthTest(pass_->GetDepthTestMode());
graphics->SetDepthWrite(pass_->GetDepthWrite());
}
// Set shaders first. The available shader parameters and their register/uniform positions depend on the currently set shaders
graphics->SetShaders(vertexShader_, pixelShader_);
// Set global (per-frame) shader parameters
if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0))
view->SetGlobalShaderParameters();
// Set camera shader parameters
unsigned cameraHash = overrideView_ ? (unsigned)(size_t)camera_ + 4 : (unsigned)(size_t)camera_;
if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<void*>(cameraHash)))
view->SetCameraShaderParameters(camera_, true, overrideView_);
// Set viewport shader parameters
IntVector2 rtSize = graphics->GetRenderTargetDimensions();
IntRect viewport = graphics->GetViewport();
unsigned viewportHash = (viewport.left_) | (viewport.top_ << 8) | (viewport.right_ << 16) | (viewport.bottom_ << 24);
if (graphics->NeedParameterUpdate(SP_VIEWPORT, reinterpret_cast<void*>(viewportHash)))
{
float rtWidth = (float)rtSize.x_;
float rtHeight = (float)rtSize.y_;
float widthRange = 0.5f * viewport.Width() / rtWidth;
float heightRange = 0.5f * viewport.Height() / rtHeight;
#ifdef URHO3D_OPENGL
Vector4 bufferUVOffset(((float)viewport.left_) / rtWidth + widthRange,
1.0f - (((float)viewport.top_) / rtHeight + heightRange), widthRange, heightRange);
#else
Vector4 bufferUVOffset((0.5f + (float)viewport.left_) / rtWidth + widthRange,
(0.5f + (float)viewport.top_) / rtHeight + heightRange, widthRange, heightRange);
#endif
graphics->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
float sizeX = 1.0f / rtWidth;
float sizeY = 1.0f / rtHeight;
graphics->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
}
// Set model or skinning transforms
if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, worldTransform_))
{
if (geometryType_ == GEOM_SKINNED)
{
graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_),
12 * numWorldTransforms_);
}
else
graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
// Set the orientation for billboards, either from the object itself or from the camera
if (geometryType_ == GEOM_BILLBOARD)
{
if (numWorldTransforms_ > 1)
graphics->SetShaderParameter(VSP_BILLBOARDROT, worldTransform_[1].RotationMatrix());
else
graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix());
}
}
// Set zone-related shader parameters
BlendMode blend = graphics->GetBlendMode();
// If the pass is additive, override fog color to black so that shaders do not need a separate additive path
bool overrideFogColorToBlack = blend == BLEND_ADD || blend == BLEND_ADDALPHA;
//.........这里部分代码省略.........
示例15: Matrix44Inverse
void LightList::QueueTiledLightCulling(Renderer& rRenderer, const Camera& rCamera)
{
RdrResourceCommandList* pResCommandList = rRenderer.GetActionCommandList();
Vec2 viewportSize = rRenderer.GetViewportSize();
uint tileCountX = RdrComputeOp::getThreadGroupCount((uint)viewportSize.x, TILEDLIGHTING_TILE_SIZE);
uint tileCountY = RdrComputeOp::getThreadGroupCount((uint)viewportSize.y, TILEDLIGHTING_TILE_SIZE);
bool tileCountChanged = false;
if (m_tiledLightData.tileCountX != tileCountX || m_tiledLightData.tileCountY != tileCountY)
{
m_tiledLightData.tileCountX = tileCountX;
m_tiledLightData.tileCountY = tileCountY;
tileCountChanged = true;
}
//////////////////////////////////////
// Depth min max
if (tileCountChanged)
{
if (m_tiledLightData.hDepthMinMaxTex)
pResCommandList->ReleaseResource(m_tiledLightData.hDepthMinMaxTex);
m_tiledLightData.hDepthMinMaxTex = pResCommandList->CreateTexture2D(tileCountX, tileCountY, RdrResourceFormat::R16G16_FLOAT, RdrResourceUsage::Default, nullptr);
}
// Update constants
Matrix44 viewMtx;
Matrix44 invProjMtx;
rCamera.GetMatrices(viewMtx, invProjMtx);
invProjMtx = Matrix44Inverse(invProjMtx);
invProjMtx = Matrix44Transpose(invProjMtx);
uint constantsSize = sizeof(Vec4) * 4;
Vec4* pConstants = (Vec4*)RdrFrameMem::AllocAligned(constantsSize, 16);
for (int i = 0; i < 4; ++i)
{
pConstants[i].x = invProjMtx.m[i][0];
pConstants[i].y = invProjMtx.m[i][1];
pConstants[i].z = invProjMtx.m[i][2];
pConstants[i].w = invProjMtx.m[i][3];
}
m_tiledLightData.hDepthMinMaxConstants = pResCommandList->CreateUpdateConstantBuffer(m_tiledLightData.hDepthMinMaxConstants,
pConstants, constantsSize, RdrCpuAccessFlags::Write, RdrResourceUsage::Dynamic);
// Fill draw op
RdrComputeOp* pDepthOp = RdrFrameMem::AllocComputeOp();
pDepthOp->shader = RdrComputeShader::TiledDepthMinMax;
pDepthOp->threads[0] = tileCountX;
pDepthOp->threads[1] = tileCountY;
pDepthOp->threads[2] = 1;
pDepthOp->ahWritableResources.assign(0, m_tiledLightData.hDepthMinMaxTex);
pDepthOp->ahResources.assign(0, rRenderer.GetPrimaryDepthBuffer());
pDepthOp->ahConstantBuffers.assign(0, m_tiledLightData.hDepthMinMaxConstants);
rRenderer.AddComputeOpToPass(pDepthOp, RdrPass::LightCulling);
//////////////////////////////////////
// Light culling
if (tileCountChanged)
{
if (m_tiledLightData.hLightIndices)
pResCommandList->ReleaseResource(m_tiledLightData.hLightIndices);
m_tiledLightData.hLightIndices = pResCommandList->CreateDataBuffer(nullptr, tileCountX * tileCountY * TILEDLIGHTING_BLOCK_SIZE, RdrResourceFormat::R16_UINT, RdrResourceUsage::Default);
}
// Update constants
constantsSize = sizeof(TiledLightCullingParams);
TiledLightCullingParams* pParams = (TiledLightCullingParams*)RdrFrameMem::AllocAligned(constantsSize, 16);
Matrix44 mtxProj;
rCamera.GetMatrices(pParams->mtxView, mtxProj);
pParams->mtxView = Matrix44Transpose(pParams->mtxView);
pParams->proj_11 = mtxProj._11;
pParams->proj_22 = mtxProj._22;
pParams->cameraNearDist = rCamera.GetNearDist();
pParams->cameraFarDist = rCamera.GetFarDist();
pParams->screenSize = viewportSize;
pParams->fovY = rCamera.GetFieldOfViewY();
pParams->aspectRatio = rCamera.GetAspectRatio();
pParams->spotLightCount = m_spotLights.size();
pParams->pointLightCount = m_pointLights.size();
pParams->tileCountX = tileCountX;
pParams->tileCountY = tileCountY;
m_tiledLightData.hCullConstants = pResCommandList->CreateUpdateConstantBuffer(m_tiledLightData.hCullConstants,
pParams, constantsSize, RdrCpuAccessFlags::Write, RdrResourceUsage::Dynamic);
// Fill draw op
RdrComputeOp* pCullOp = RdrFrameMem::AllocComputeOp();
pCullOp->threads[0] = tileCountX;
pCullOp->threads[1] = tileCountY;
pCullOp->threads[2] = 1;
pCullOp->ahWritableResources.assign(0, m_tiledLightData.hLightIndices);
pCullOp->ahResources.assign(0, m_hSpotLightListRes);
pCullOp->ahResources.assign(1, m_hPointLightListRes);
pCullOp->ahResources.assign(2, m_tiledLightData.hDepthMinMaxTex);
pCullOp->ahConstantBuffers.assign(0, m_tiledLightData.hCullConstants);
//.........这里部分代码省略.........