SpaceShooter::SpaceShooter() { Renderer::Get().Initialize(); // Create the player's view. Quaternion viewRotation( Vector3::Right, Pi / 2.f ); mCamera = ViewPtr( new View( Vector3( 0.f, 60.f, 0.f ), viewRotation, 1.04719755f, 1920.0f / 1080.0f, 0.1f, 100.f, false ) ); Renderer::Get().SetCamera( mCamera ); // Create the background. MaterialPtr backgroundMaterial = MaterialPtr( new Material( L"Resources\\Shaders\\tangent.hlsl", L"Resources\\Textures\\starfield.dds" ) ); RawMeshPtr backgroundMesh = RawMeshPtr( new RawMesh() ); GenerateQuadVerticies( *backgroundMesh.get(), 90.f, 45.f ); MeshPrimitivePtr background = MeshPrimitivePtr( new MeshPrimitive( backgroundMesh, backgroundMaterial, GetTangentSpaceVertexSource() ) ); mBackground = GameObjectPtr( new GameObject( background ) ); Matrix4 backgroundOffset; backgroundOffset.CreateFromQuaternion( Quaternion( Vector3::Right, Pi / 2.f ) ); mBackground->SetOffset( backgroundOffset ); mBackground->SetTranslation( Vector3( 0.f, -10.f, 0.f ) ); mBackground->Attach(); // Load the player's ship. MaterialPtr playerShipMaterial = MaterialPtr( new Material( L"Resources\\Shaders\\tangent.hlsl", L"Resources\\Textures\\frigate.dds" ) ); RawMeshPtr shipMesh = RawMeshPtr( new RawMesh() ); LoadMeshFromObjFile( "Resources\\Meshes\\frigate_normal.obj", *shipMesh.get() ); CalculateTangents( *shipMesh.get() ); MeshPrimitivePtr player = MeshPrimitivePtr( new MeshPrimitive( shipMesh, playerShipMaterial, GetTangentSpaceVertexSource() ) ); mPlayerObject = PlayerShipPtr( new PlayerShip( player ) ); mPlayerObject->SetScale( 0.3f ); mPlayerObject->SetBounds( 6.5f ); Matrix4 playerOffset; playerOffset.CreateFromQuaternion( Quaternion( Vector3::Up, Pi / 2.f ) ); mPlayerObject->SetOffset( playerOffset ); mPlayerObject->SetFrictionFactor( 0.5f ); mPlayerObject->Attach(); // Load asteroids MaterialPtr asteroidMaterial = MaterialPtr( new Material( L"Resources\\Shaders\\tangent.hlsl", L"Resources\\Textures\\asteroid.dds" ) ); RawMeshPtr asteroidMesh = RawMeshPtr( new RawMesh() ); LoadMeshFromObjFile( "Resources\\Meshes\\asteroid1.obj", *asteroidMesh.get() ); CalculateTangents( *asteroidMesh.get() ); for ( int i = 0; i < 5; i++ ) { MeshPrimitivePtr asteroid = MeshPrimitivePtr( new MeshPrimitive( asteroidMesh, asteroidMaterial, GetTangentSpaceVertexSource() ) ); GameObjectPtr newAsteroid = GameObjectPtr( new Asteroid( asteroid ) ); newAsteroid->SetScale( 1.f ); newAsteroid->SetBounds( 4.f ); newAsteroid->SetTranslation( Vector3( RandomFloat( -40.f, 40.f ), 0.f, RandomFloat( -40.f, 40.f ) ) ); mAsteroids.push_back( newAsteroid ); newAsteroid->Attach(); } // Load the player's jet particles. playerJetParticles = ParticleSystemPtr( new ParticleSystem() ); ParticleSystemLoader loader; loader.LoadFromFile( "Resources\\ParticleSystems\\jet_fuel.part", playerJetParticles ); playerJetParticles->SetEmitterState( false ); // turn the particles off to start with Renderer::Get().AddTranslucentPrimitive( playerJetParticles ); }
MaterialPtr CMaterialManager::LoadMaterial(xst_castring& strName, xst_castring& strGroupName) { LuaScriptPtr pScript = CLuaScriptManager::GetSingletonPtr()->LoadScript( strName, strGroupName, &m_LuaApi ); if( pScript.IsNull() ) { return MaterialPtr(); } xst_assert( 0, "(CMaterialManager::LoadMaterial) Not implemented" ); return MaterialPtr(); }
MaterialPtr MaterialManagerClass::getMaterialByName(std::string name) { //printf("name = %s\n", name.c_str()); for(int key = 0; key < materials.size(); key++) { //printf("available: %s\n", materials[key].name.c_str()); if(materials[key].name == name) { //printf("Found!\n"); return MaterialPtr(key); } } //printf("dammit, nothing ;_;\n"); return MaterialPtr(666666); }
void Renderer::RenderablesSort(vector<Entity*>* renderables) { if (renderables->size() <= 2) return; // Sort by depth (front to back) if (m_camera) { sort(renderables->begin(), renderables->end(), [this](Entity* a, Entity* b) { // Get renderable component auto a_renderable = a->GetRenderable_PtrRaw(); auto b_renderable = b->GetRenderable_PtrRaw(); if (!a_renderable || !b_renderable) return false; // Get materials const auto a_material = a_renderable->MaterialPtr(); const auto b_material = b_renderable->MaterialPtr(); if (!a_material || !b_material) return false; const auto a_depth = (a_renderable->GeometryAabb().GetCenter() - m_camera->GetTransform()->GetPosition()).LengthSquared(); const auto b_depth = (b_renderable->GeometryAabb().GetCenter() - m_camera->GetTransform()->GetPosition()).LengthSquared(); return a_depth < b_depth; }); } // Sort by material sort(renderables->begin(), renderables->end(), [](Entity* a, Entity* b) { // Get renderable component const auto a_renderable = a->GetRenderable_PtrRaw(); const auto b_renderable = b->GetRenderable_PtrRaw(); if (!a_renderable || !b_renderable) return false; // Get materials const auto a_material = a_renderable->MaterialPtr(); const auto b_material = b_renderable->MaterialPtr(); if (!a_material || !b_material) return false; // Order doesn't matter, as long as they are not mixed return a_material->GetResourceId() < b_material->GetResourceId(); }); }
i32 CMaterialManager::Init() { m_mDefaultMaterials.clear(); //Create default material Resources::CMaterial* pMat = xst_new Resources::CMaterial( m_pShaderMgr, DEFAULT_TECHNIQUE, this, 0, "xse_default_material", XST::ResourceType::MATERIAL, XST::ResourceStates::CREATED/*, xst_null*/ ); if( pMat == xst_null ) { return XST_FAIL; } IPass* pPass = pMat->GetCurrentTechnique()->GetPass( 0 ); pPass->SetVertexShader( m_pShaderMgr->GetDefaultVertexShader( ) ); pPass->SetPixelShader( m_pShaderMgr->GetDefaultPixelShader() ); m_pDefaultMat = MaterialPtr( pMat ); //Create default simple use materials xst_astring strShaderCode; strShaderCode.reserve( 2048 ); { MaterialPtr pMat = CreateMaterial( DEFAULT_MAT_COLOR, DEFAULT_GROUP ); // TODO: implement case if pMat is null if( !pMat ) this resource should be destroyed IPass* pPass = pMat->CreateTechnique( DEFAULT_TECHNIQUE, true )->GetPass( 0 ); strShaderCode = m_pShaderMgr->CreateShaderCode( ILE::POSITION | ILE::COLOR, ILE::POSITION | ILE::COLOR ); VertexShaderPtr pVS = m_pShaderMgr->CompileVertexShader( "xse_default_color_vs", "vs_main", ILE::POSITION | ILE::COLOR, strShaderCode ); PixelShaderPtr pPS = m_pShaderMgr->CompilePixelShader( "xse_default_color_ps", "ps_main", strShaderCode ); pPass->SetVertexShader( pVS ); pPass->SetPixelShader( pPS ); } return XST_OK; }
void SGLFlObj::resetMaterial(MaterialPtr NewMaterial) { Mat= NewMaterial ? NewMaterial : MaterialPtr (new SGLMaterial); /* if(Mat && Mat->tex && Mat->tex->valid) resetTexKoord();*/ //nicht mehr nötig, da ALLE Texturkoordinaten haben }
MaterialPtr CMaterialManager::GetDefaultMaterial(const IInputLayout *pIL) { xst_assert( pIL != xst_null, "(CMaterialManager::GetDefaultMaterial) Input layout must be set" ); //Get or create default material for this input layout DefaultMatMap::iterator Itr; //If resource not found if( XST::MapUtils::FindPlace( m_mDefaultMaterials, pIL, &Itr ) ) { //Create new material u32 uILHandle = pIL->GetHandle(); Resources::CMaterial* pMat = xst_new Resources::CMaterial( m_pShaderMgr, DEFAULT_TECHNIQUE, this, uILHandle, XST::StringUtil::EmptyAString, XST::ResourceType::MATERIAL, XST::ResourceStates::CREATED/*, xst_null*/ ); if( pMat == xst_null ) { XST_LOG_ERR( "Default material creation failed. Memory error." ); return MaterialPtr(); } //Set defaults IPass* pPass = pMat->GetCurrentTechnique()->GetPass( 0 ); pPass->SetVertexShader( pIL->GetVertexShader() ); pPass->SetPixelShader( pIL->GetPixelShader() ); //Add material to the buffer MaterialPtr pMaterial( pMat ); XST::MapUtils::InsertOnPlace( m_mDefaultMaterials, pIL, pMaterial, Itr ); return pMaterial; } //If resource found returns it return Itr->second; }
const MaterialPtr Material::GetFallback() { if (fallbackMat) return fallbackMat; // @TODO resolve fallback to material, cache and return it. return MaterialPtr(); }
bool Triangle::Intersect(const Ray &ray, IntersectInfo &info) const { glm::vec3 normal = glm::normalize(glm::cross(point2 - point1, point3 - point1)); // this is the angle between the normal and the ray direction float angle = glm::dot(ray.direction, normal); // if the Triangle is perpendicular to the view then it does not intersect if (angle != 0) { float depth = glm::dot((point1 - ray.origin), normal) / angle; if (depth > 0) { glm::vec3 hitPoint = ray.origin + depth * ray.direction; glm::vec3 hit1 = hitPoint - point1; glm::vec3 hit2 = hitPoint - point2; glm::vec3 hit3 = hitPoint - point3; // check if the ray was on the inside of each line of the triangle float determinant1 = glm::dot(normal, glm::cross(point2 - point1, hit1)); float determinant2 = glm::dot(normal, glm::cross(point3 - point2, hit2)); float determinant3 = glm::dot(normal, glm::cross(point1 - point3, hit3)); if(determinant1 >= 0 && determinant2 >= 0 && determinant3 >= 0) { info.hitPoint = hitPoint; info.normal = normal; info.material = MaterialPtr(); info.time = glm::length(ray.origin - info.hitPoint); return true; } } } return false; }
bool Sphere::Intersect(const Ray &ray, IntersectInfo &info) const { // solve the quadratic equation float a = glm::dot(ray.direction, ray.direction); float b = glm::dot(2.0f*ray.direction, (ray.origin - origin)); float c = glm::dot((ray.origin - origin), (ray.origin - origin)) - pow(radius, 2); float discriminant = pow(b, 2) - 4*a*c; if(discriminant < 0) { // here the ray did not intersect with the object return false; } else if (discriminant >= 0){ // here the ray passes through 2 surfaces of the sphere, or touches the edge // we want to use the closest intersection point and since the sqrt is always positive, // we can just use the negative version of the quadratic solution function. float depth = (-b -sqrt(discriminant)) / (2.0f*a); // ignore intersection if it is behind the camera // we make the assumption that if we are on the inside of the object then it is not displayed if(depth < 0){ return false; } info.hitPoint = ray.origin + (depth * ray.direction); } info.material = MaterialPtr(); // calculate the normal on the sphere where the ray intersects it info.normal = glm::normalize(info.hitPoint - origin); info.time = glm::length(ray.origin - info.hitPoint); return true; }
SGLFlObj::SGLFlObj(MaterialPtr Material,GLdouble PosX,GLdouble PosY,GLdouble PosZ,GLdouble SizeFact): SGLObj(PosX,PosY,PosZ,SizeFact) { VisMode=GL_FALSE; resetMaterial(MaterialPtr(Material)); priority=flstd; twoSideRender=false; }
Shape::Shape(Vector<3,float> c) : center(c), reflection(0.0), transparent(false), refraction(1.0) { mat = MaterialPtr(new Material()); mat->diffuse = Vector<4,float>(1); }
MaterialPtr Compiler::CompileFromFile(Sys_GraphicsPtr pGraphics, const boost::filesystem::path& strFile) { DataStream_File file; if(false == file.OpenStream(strFile.string().c_str())) { return MaterialPtr(); } return CompileFromStream(pGraphics, &file, strFile); }
MaterialPtr CMaterialManager::CreateMaterial(xst_castring &strName, xst_castring &strGroupName) { MaterialPtr pMat = this->CreateResource( strName, strGroupName ); if( pMat.IsNull() ) { return MaterialPtr(); } return pMat; }
//------------------------------------------------------ MaterialPtr MaterialService::getWorldMaterialTemplate(unsigned int idx) { // look for material per slot, return if found WorldMaterialMap::iterator it = mTemplateMaterials.find(idx); if (it != mTemplateMaterials.end()) { return it->second; } LOG_FATAL("MaterialService::getWorldMaterialTemplate: Could not find material for index %u", idx); return MaterialPtr(); }
void Renderer::RenderablesAcquire(const Variant& entities_variant) { TIME_BLOCK_START_CPU(m_profiler); // Clear previous state m_entities.clear(); m_camera = nullptr; m_skybox = nullptr; auto entities_vec = entities_variant.Get<vector<shared_ptr<Entity>>>(); for (const auto& entitieshared : entities_vec) { auto entity = entitieshared.get(); if (!entity) continue; // Get all the components we are interested in auto renderable = entity->GetComponent<Renderable>(); auto light = entity->GetComponent<Light>(); auto skybox = entity->GetComponent<Skybox>(); auto camera = entity->GetComponent<Camera>(); if (renderable) { const auto is_transparent = !renderable->MaterialExists() ? false : renderable->MaterialPtr()->GetColorAlbedo().w < 1.0f; if (!skybox) // Ignore skybox { m_entities[is_transparent ? Renderable_ObjectTransparent : Renderable_ObjectOpaque].emplace_back(entity); } } if (light) { m_entities[Renderable_Light].emplace_back(entity); } if (skybox) { m_skybox = skybox; } if (camera) { m_entities[Renderable_Camera].emplace_back(entity); m_camera = camera; } } RenderablesSort(&m_entities[Renderable_ObjectOpaque]); RenderablesSort(&m_entities[Renderable_ObjectTransparent]); TIME_BLOCK_END(m_profiler); }
bool SkyLight::Create(Sys_GraphicsPtr pGraphics) { m_pMaterial = pGraphics->CreateMaterialFromFile("./assets/standard/material/dr_render_directional_light.fx"); VertexFormat vf; vf.AddElement(VertexElement(0, VertexElement::POSITION, G_FORMAT_R32G32B32_FLOAT)); m_pMaterial->SetVertexFormat(vf); if(m_pMaterial == MaterialPtr()) { return false; } return true; }
void GLProgram::link(State* state) { glCheck("GLProgram::link"); m_relink = false; GLint prog = 0; glRun(glGetIntegerv(GL_CURRENT_PROGRAM, &prog)); if (isLinked()) { glRun(glUseProgram(m_prog)); /// @todo Do we need this? m_uniformList = getUniformList(); } ShaderErrorList errors(state ? state->material() : MaterialPtr(), name()); if (!m_transformFeedback.isEmpty()) { const char* names[10]; int m = std::min(m_transformFeedback.size(), 10); for (int i = 0; i < m; ++i) { names[i] = m_transformFeedback[i].data(); } glRun(glTransformFeedbackVaryings(m_prog, m, names, GL_SEPARATE_ATTRIBS)); } glRun(glLinkProgram(m_prog)); GLint ok = 0; glRun(glGetProgramiv(m_prog, GL_LINK_STATUS, &ok)); GLint len = 0; glRun(glGetProgramiv(m_prog, GL_INFO_LOG_LENGTH, &len)); // len may include the zero byte if (len > 1) { std::vector<GLchar> log(len); GLsizei size = len; glRun(glGetProgramInfoLog(m_prog, size, &size, &log[0])); ShaderCompilerOutputParser::instance().parse(QString::fromUtf8(&log[0], size), errors); } if (ok) { glRun(glUseProgram(m_prog)); /// @todo Do we need this? setUniform(m_uniformList); } emit linked(errors); glRun(glUseProgram(prog)); }
MaterialPtr Compiler::Compile(Sys_GraphicsPtr pGraphics, const std::string& src, const boost::filesystem::path& filename) { m_file = filename; logger() << "-- compiling material(" << m_file << "): \n"; Lexer lexer(src); MaterialParser parser(nullptr, logger()); if(false == parser.Parse(&lexer, m_file == "" ? "./" : m_file.parent_path())) { logger() << "== failed.\n"; return MaterialPtr(); } logger() << "== ok.\n"; return parser.CreateObject(pGraphics); }
bool Plane::Intersect(const Ray &ray, IntersectInfo &info) const { float angle = glm::dot(ray.direction, normal); // this prevents divide by 0 error if (angle != 0) { float depth = glm::dot((point - ray.origin), normal) / angle; // check if the intercection is infront of the camera if (depth > 0) { info.hitPoint = ray.origin + depth * ray.direction; info.normal = normal; info.material = MaterialPtr(); info.time = glm::length(ray.origin - info.hitPoint); return true; } // here the intercection is behind the camera return false; } return false; }
void GLWidget::initializeGL() { connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &GLWidget::cleanup); m_func = context()->versionFunctions<QOpenGLFunctions_4_3_Core>(); m_func->initializeOpenGLFunctions(); // CLManager::getSingletonPtr()->setSource("bpatch.cl"); m_mainCam = CameraPtr(new Camera(m_swidth, m_sheight)); m_comp = new Compositer(m_func, m_swidth, m_sheight); m_func->glClearColor(0, 0, 0, 1); m_phong = MaterialPtr(new Material(m_func)); m_phong->setShader("res/shaders/shader.vert", "res/shaders/shader.frag"); m_phong->shader()->setUniformValue("lightPos", QVector3D(0, 0, 70)); cube = new Model(m_func); cube->initWithName("res/models/toonface.obj"); cube->setMaterial(m_phong); cube->setCamera(m_mainCam); QVector3D cam_trans(0,1,0); m_mainCam->translate(cam_trans); SamplerPtr sampler(new Sampler(m_func)); sampler->create(); sampler->setMinFilter(GL_LINEAR); sampler->setMaxFilter(GL_LINEAR); sampler->setWrapMode(Sampler::S, GL_CLAMP_TO_EDGE); sampler->setWrapMode(Sampler::T, GL_CLAMP_TO_EDGE); QImage diffuseImg("res/textures/face.dds"); m_func->glActiveTexture(GL_TEXTURE0); TexturePtr diffuseMap(new Texture(m_func)); diffuseMap->create(); diffuseMap->bind(); diffuseMap->initializeWithImage(diffuseImg); m_phong->setTextureUnitConfiguration(0, diffuseMap, sampler, QByteArrayLiteral("textureSampler")); }
//------------------------------------------------------------------------ MaterialPtr MaterialUtil::generateMaterial(const MtlPtr& _mtl, const MatGenParams& _matGenParams) { MaterialPtr material; Mtl::MaterialHandles::iterator it = _mtl->mMaterialHandles.find(_matGenParams); if(it != _mtl->mMaterialHandles.end()) { // Material was generated already, just return it // (Materials can be shared.) ResourceHandle handle = it->second; material = MaterialManager::getSingleton().getByHandle(handle); } else { // Generate a new material String materialName = s_MaterialNameGenerator.generate(); material = MaterialManager::getSingleton().create(materialName, StringUtil::BLANK); // We need a material generator. MaterialGenerator* generator = MaterialGeneratorRegistration::getSingleton().getGenerator(); // Initalise the material with the specified params. generator->_updateMaterial(material, _mtl, _matGenParams); // Store the smart pointer to the mtl and the material generation params // in the material's "user any" member. if(!material->getNumTechniques()) { MaterialManager::getSingleton().remove( (ResourcePtr) material); return MaterialPtr(); } Technique* technique = material->getTechnique(0); UserObjectBindings& uob = technique->getUserObjectBindings(); uob.setUserAny( USER_MTL, (Any) _mtl ); uob.setUserAny( USER_MAT_GEN_PARAMS, (Any) _matGenParams ); // Store the handle to the new material in the mtl. ResourceHandle handle = material->getHandle(); _mtl->mMaterialHandles.insert(std::make_pair(_matGenParams, handle)); } return material; }
void TerrainTessellationScene::initialise() { m_material = MaterialPtr( new Material ); m_material->setShaders( ":/shaders/terraintessellation.vert", ":/shaders/terraintessellation.tcs", ":/shaders/terraintessellation.tes", ":/shaders/terraintessellation.geom", ":/shaders/terraintessellation.frag" ); QImage heightMapImage( "../../../opengl/assets/textures/heightmap-1024x1024.png" ); TexturePtr heightMap( new Texture ); heightMap->create(); heightMap->bind(); heightMap->setImage( heightMapImage ); SamplerPtr sampler( new Sampler ); sampler->create(); sampler->setMinificationFilter( GL_LINEAR ); sampler->setMagnificationFilter( GL_LINEAR ); sampler->setWrapMode( Sampler::DirectionS, GL_CLAMP_TO_EDGE ); sampler->setWrapMode( Sampler::DirectionT, GL_CLAMP_TO_EDGE ); m_material->setTextureUnitConfiguration( 0, heightMap, sampler, QByteArrayLiteral( "heightMap" ) ); // Create a renderable object prepareVertexBuffers( heightMapImage.size() ); prepareVertexArrayObject(); // Enable depth testing glEnable( GL_DEPTH_TEST ); m_funcs = m_context->versionFunctions<QOpenGLFunctions_4_0_Core>(); if ( !m_funcs ) qFatal( "Could not obtain required OpenGL context version" ); m_funcs->initializeOpenGLFunctions(); }
FilledQuadForegroundBase::FilledQuadForegroundBase(void) : _sfMaterial (MaterialPtr(NullFC)), Inherited() { }
MaterialPtr State::material() const { if (m_materials.isEmpty()) return MaterialPtr(); return m_materials.back(); }
Material::Material(const std::string name, const std::string fallback) : name(name), shadings(std::list<Shading>()), fallback(fallback), fallbackMat(MaterialPtr()) { }
MaterialPtr DT_SelectionBox::BoxRenderData::GetMaterial() { return MaterialPtr(); }
MaterialPtr MaterialManagerClass::addMaterial(Material mtl) { materials.push_back(mtl); return MaterialPtr(materials.size()-1); }
MaterialPtr Material::create(const gl::ShaderType &the_type) { return MaterialPtr(new Material(gl::create_shader(the_type))); }
MaterialPtr Material::create(const Shader &theShader) { return MaterialPtr(new Material(theShader)); }