void GL3CalculateCubeShadowMapMatrix(Vector3D light_position, Vector3D zdir, Vector3D cube_s_vector, Vector3D cube_t_vector, float zmin, float zmax) { MatrixTransform M; M.Set( cube_s_vector.x, cube_s_vector.y, cube_s_vector.z, 0.0f, cube_t_vector.x, cube_t_vector.y, cube_t_vector.z, 0.0f, - zdir.x, - zdir.y, - zdir.z, 0.0f); MatrixTransform T; T.AssignTranslation(- light_position); // Calculate the projection matrix with a field of view of 90 degrees. float aspect = 1.0; float e = 1 / tanf((90.0f * M_PI / 180) / 2); float n = zmin; float f = zmax; float l = - n / e; float r = n / e; float b = - (1.0f / aspect) * n / e; float t = (1.0f / aspect) * n / e; Matrix4D shadow_map_projection_matrix; shadow_map_projection_matrix.Set( 2 * n / (r - l), 0.0f, (r + l) / (r - l), 0.0f, 0.0f, 2 * n / (t - b), (t + b) / (t - b), 0.0f, 0.0f, 0.0f, - (f + n) / (f - n), - 2 * n * f / (f - n), 0.0f, 0.0f, - 1.0f, 0.0f); cube_shadow_map_matrix = shadow_map_projection_matrix * (M * T); }
void sreLookAt(float viewpx, float viewpy, float viewpz, float lookx, float looky, float lookz, float upx, float upy, float upz) { Vector3D F = Vector3D(lookx, looky, lookz) - Vector3D(viewpx, viewpy, viewpz); Vector3D Up = Vector3D(upx, upy, upz); Vector3D f = F.Normalize(); sre_internal_camera_vector = f; Up.Normalize(); sre_internal_up_vector = Up; Vector3D s = Cross(f, Up); Vector3D u = Cross(s, f); MatrixTransform M; M.Set( s.x, s.y, s.z, 0.0f, u.x, u.y, u.z, 0.0f, - f.x, - f.y, - f.z, 0.0f); MatrixTransform T; T.AssignTranslation(Vector3D(- viewpx, - viewpy, -viewpz)); sre_internal_view_matrix = M * T; sre_internal_view_projection_matrix = sre_internal_projection_matrix * sre_internal_view_matrix; // printf("View-projection matrix:\n"); // for (int row = 0; row < 4; row++) // for (int column = 0; column < 4; column++) // printf("%f, ", sre_internal_view_projection_matrix(row, column)); // printf("\n"); }
Transform* PatchSet::createPatch(const std::string& filename, PatchOptions* poptions) { Patch* patch = new Patch; patch->setPatchSet(this); Vec2d ll, ur; poptions->getPatchExtents(ll, ur); Vec2d range = (ur - ll); ref_ptr<Patch::Data> data = new Patch::Data; int patchDim = _resolution + 1; Vec3Array* verts = new Vec3Array(patchDim * patchDim); for (int j = 0; j < patchDim; ++j) for (int i = 0; i < patchDim; ++i) (*verts)[patchDim * j + i] = Vec3((ll.x() + i * range.x() / static_cast<float>(_resolution)) * 81920.0, (ll.y() + j * range.y() / static_cast<float>(_resolution)) * 81920.0, 0.0); data->vertexData.array = verts; data->vertexData.binding = Geometry::BIND_PER_VERTEX; Vec3Array* norms = new Vec3Array(1); (*norms)[0] = Vec3d(0.0, 0.0, 1.0); data->normalData.array = norms; data->normalData.binding = Geometry::BIND_OVERALL; Vec4Array* colors = new Vec4Array(1); (*colors)[0] = Vec4(1.0, 1.0, 1.0, 1.0); data->colorData.array = colors; data->colorData.binding = Geometry::BIND_OVERALL; patch->setData(data); MatrixTransform* transform = new MatrixTransform; transform->addChild(patch); return transform; }
void updateTransform () { m_transform.localToParent() = Matrix4::getIdentity(); m_transform.localToParent().translateBy(m_origin); m_ray.direction = matrix4_transformed_direction(matrix4_rotation_for_z(degrees_to_radians(m_angle)), Vector3(1, 0, 0)); m_transformChanged(); }
ref_ptr<Group> VBSPEntity::createModelGeometry() { std::string modelFile; ref_ptr<Node> modelNode; ref_ptr<Group> entityGroup; // Try to load the model modelNode = osgDB::readRefNodeFile(entity_model); if (modelNode.valid()) { // Create a group and add the model to it if (entity_transformed) { // Create a matrix transform MatrixTransform * entityXform = new MatrixTransform(); // Set it up with the entity's transform information (scale // the position from inches to meters) Matrixf transMat, rotMat; Quat roll, yaw, pitch; transMat.makeTranslate(entity_origin * 0.0254); pitch.makeRotate(osg::DegreesToRadians(entity_angles.x()), Vec3f(0.0, 1.0, 0.0)); yaw.makeRotate(osg::DegreesToRadians(entity_angles.y()), Vec3f(0.0, 0.0, 1.0)); roll.makeRotate(osg::DegreesToRadians(entity_angles.z()), Vec3f(1.0, 0.0, 0.0)); rotMat.makeRotate(roll * pitch * yaw); // Set the transform matrix entityXform->setMatrix(rotMat * transMat); // Use the transform node as the main entity group entityGroup = entityXform; } else { // Create a group to represent the entire entity entityGroup = new Group(); } // Add the model node to the group entityGroup->addChild(modelNode.get()); // Set the group's name entityGroup->setName(class_name + std::string(":") + entity_model); } else { OSG_WARN << "Couldn't find prop \"" << entity_model << "\"."; OSG_WARN << std::endl; // Leave the group empty (no model to show) entityGroup = NULL; } return entityGroup; }
void CollisionVisitor::ApplyMatrixTransform(MatrixTransform &m) { matrix4x4f matrix = matrix4x4f::Identity(); if (!m_matrixStack.empty()) matrix = m_matrixStack.back(); m_matrixStack.push_back(matrix * m.GetTransform()); m.Traverse(*this); m_matrixStack.pop_back(); }
void GL3CalculateShadowMapMatrix(Vector3D viewp, Vector3D light_direction, Vector3D x_direction, Vector3D y_direction, Vector3D dim_min, Vector3D dim_max) { MatrixTransform M; // Note that the y direction has to be negated in order to preserve the handedness of // triangles when rendering the shadow map. #if 0 M.Set( x_direction.x, y_direction.x, - light_direction.x, 0.0f, x_direction.x, y_direction.y, - light_direction.y, 0.0f, x_direction.z, y_direction.z, - light_direction.z, 0.0f); #else M.Set( x_direction.x, x_direction.y, x_direction.z, 0.0f, - y_direction.x, - y_direction.y, - y_direction.z, 0.0f, - light_direction.x, - light_direction.y, - light_direction.z, 0.0f); #endif MatrixTransform T; T.AssignTranslation(- viewp); // Set orthographic projection matrix. MatrixTransform orthographic_shadow_map_projection_matrix; orthographic_shadow_map_projection_matrix.Set( 2.0f / (dim_max.x - dim_min.x), 0.0f, 0.0f, - (dim_max.x + dim_min.x) / (dim_max.x - dim_min.x), 0.0f, 2.0f / (dim_max.y - dim_min.y), 0.0f, - (dim_max.y + dim_min.y) / (dim_max.y - dim_min.y), 0.0f, 0.0f, - 2.0f / dim_max.z, - 1.0f); shadow_map_matrix = orthographic_shadow_map_projection_matrix * (M * T); // Calculate viewport matrix for lighting pass with shadow map. MatrixTransform shadow_map_viewport_matrix; shadow_map_viewport_matrix.Set( 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f); shadow_map_lighting_pass_matrix = shadow_map_viewport_matrix * shadow_map_matrix; #if 0 char *dim_max_str = dim_max.GetString(); sreMessage(SRE_MESSAGE_LOG, "dim_max = %s", dim_max_str); delete [] dim_max_str; Point3D P1 = viewp + light_direction * dim_max.z; Point3D P2 = viewp; Point3D P3 = viewp + x_direction * dim_max.x + y_direction * dim_max.y; Vector4D P1_proj = shadow_map_matrix * P1; Vector4D P2_proj = shadow_map_matrix * P2; Vector4D P3_proj = shadow_map_matrix * P3; Vector3D P1_norm = P1_proj.GetVector3D(); Vector3D P2_norm = P2_proj.GetVector3D(); Vector3D P3_norm = P3_proj.GetVector3D(); char *P1_norm_str = P1_norm.GetString(); char *P2_norm_str = P2_norm.GetString(); char *P3_norm_str = P3_norm.GetString(); sreMessage(SRE_MESSAGE_LOG, "CalculateShadowMapMatrix: Point transformations " "%s, %s and %s.", P1_norm_str, P2_norm_str, P3_norm_str); delete P1_norm_str; delete P2_norm_str; delete P3_norm_str; #endif }
/*************************************************************** * Function: acceptCAVEGeodeShape() * * 'refShapeCenter' is reference center of 'CAVEGeodeShape', use * this vector as reference center in design object space, which * is associated with center of BoundingBox. Apply the offset of * 'shapeCenter - refShapeCenter' on top level of scene graph and * then rescale them in lower levels to fit into the scale of * surface icon space. * ***************************************************************/ void CAVEGroupEditGeodeWireframe::acceptCAVEGeodeShape(CAVEGeodeShape *shapeGeode, const osg::Vec3 &refShapeCenter) { mRefShapeCenter = refShapeCenter; updateCAVEGeodeShape(shapeGeode); /* create 'MOVE' operational wireframe geode[0] */ MatrixTransform *moveTrans = new MatrixTransform; CAVEGeodeEditWireframeMove *moveGeode = new CAVEGeodeEditWireframeMove; mMoveSwitch->addChild(moveTrans); mMoveMatTransVector.push_back(moveTrans); moveTrans->addChild(moveGeode); moveTrans->setMatrix(mBoundBoxScaleMat * mAccRootMat); /* create 'ROTATE' operational wireframe geode[0] */ MatrixTransform *rotateTrans = new MatrixTransform; CAVEGeodeEditWireframeRotate *rotateGeode = new CAVEGeodeEditWireframeRotate; mRotateSwitch->addChild(rotateTrans); mRotateMatTransVector.push_back(rotateTrans); rotateTrans->addChild(rotateGeode); rotateTrans->setMatrix(mBoundSphereScaleMat * mAccRootMat); /* create 'MANIPULATE' operational wireframe geode[0] */ MatrixTransform *manipulateTrans = new MatrixTransform; CAVEGeodeEditWireframeManipulate *manipulateGeode = new CAVEGeodeEditWireframeManipulate; mManipulateSwitch->addChild(manipulateTrans); mManipulateMatTransVector.push_back(manipulateTrans); manipulateTrans->addChild(manipulateGeode); manipulateTrans->setMatrix(mBoundBoxScaleMat * mAccRootMat); }
bool MatrixTransform::equals(const MatrixTransform & other) const { if (this == &other) return true; if (getImpl()->dir_ != other.getImpl()->dir_) { return false; } return *getImpl() == *(other.getImpl()); }
void EgoMovement::update(const int delta_time) { move(delta_time); rotate(); MatrixTransform* transform = (MatrixTransform*)parent; glm::mat4 parent_matrix = transform->getMatrix(); glm::mat4 delta_matrix = glm::translate(glm::mat4(), position) * glm::rotate(glm::mat4(), rotation.y, glm::vec3(0, 1, 0)) * glm::rotate(glm::mat4(), rotation.x, glm::vec3(1, 0, 0)); transform->setMatrix(delta_matrix); }
void updateTransform() { m_transform.localToParent() = g_matrix4_identity; if(isModel()) { matrix4_translate_by_vec3(m_transform.localToParent(), m_originKey.m_origin); matrix4_multiply_by_matrix4(m_transform.localToParent(), rotation_toMatrix(m_rotationKey.m_rotation)); } m_transformChanged(); if(!isModel()) { m_funcStaticOrigin.originChanged(); } }
MatrixTransform* ChessUtils::loadOSGModel(string name, float modelSize, Material* material, bool overrideMaterial, Vec3 modelCenterShift, double rotationAngle, Vec3 rotationAxis, Vec3 modelCenterOffsetPercentage) { // create a new node by reading in model from file Node* modelNode = osgDB::readNodeFile(name); if (modelNode != NULL) { // apply material if (material != NULL) { if (overrideMaterial) { modelNode->getOrCreateStateSet()->setAttributeAndModes(material, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } else { modelNode->getOrCreateStateSet()->setAttributeAndModes(material, osg::StateAttribute::ON); } } //put model in origin //osg::BoundingSphere bound = modelNode->getBound(); osg::ComputeBoundsVisitor cbVisitorOrigin; modelNode->accept(cbVisitorOrigin); osg::BoundingBox bound = cbVisitorOrigin.getBoundingBox(); double scaleRatio = modelSize / bound.radius(); MatrixTransform* unitTransform = new MatrixTransform(); unitTransform->postMult(Matrix::translate(-bound.center().x(), -bound.center().y(), -bound.center().z())); unitTransform->postMult(Matrix::rotate(rotationAngle, rotationAxis)); unitTransform->postMult(Matrix::scale(scaleRatio, scaleRatio, scaleRatio)); unitTransform->addChild(modelNode); // put model in specified location osg::ComputeBoundsVisitor cbVisitor; unitTransform->accept(cbVisitor); osg::BoundingBox boundingBox = cbVisitor.getBoundingBox(); float modelXOffset = (boundingBox.xMax() - boundingBox.xMin()) * modelCenterOffsetPercentage.x(); float modelYOffset = (boundingBox.yMax() - boundingBox.yMin()) * modelCenterOffsetPercentage.y(); float modelZOffset = (boundingBox.zMax() - boundingBox.zMin()) * modelCenterOffsetPercentage.z(); unitTransform->postMult(Matrix::translate(modelXOffset, modelYOffset, modelZOffset)); MatrixTransform* modelPositionTransform = new MatrixTransform(); modelPositionTransform->postMult(Matrix::translate(modelCenterShift)); modelPositionTransform->addChild(unitTransform); return modelPositionTransform; } return NULL; }
void BuildMatrixOps(OpRcPtrVec & ops, const Config& /*config*/, const MatrixTransform & transform, TransformDirection dir) { TransformDirection combinedDir = CombineTransformDirections(dir, transform.getDirection()); float matrix[16]; float offset[4]; transform.getValue(matrix, offset); CreateMatrixOffsetOp(ops, matrix, offset, combinedDir); }
void GL3CalculateShadowMapMatrixAlwaysLight() { // Set a matrix that produces shadow map coordinates that are out of bounds in x and y, with w coordinate 1 // and a z-coordinate of 0.5. In the pixel shader, this produces no shadow. shadow_map_lighting_pass_matrix.Set( 0.0f, 0.0f, 0.0f, -2.0f, 0.0f, 0.0f, 0.0f, -2.0, 0.0f, 0.0f, 0.0f, 0.5f); }
Shields::Shields(SceneGraph::Model *model) : m_enabled(false) { assert(s_initialised); using SceneGraph::Node; using SceneGraph::MatrixTransform; using SceneGraph::StaticGeometry; using SceneGraph::CollisionGeometry; //This will find all matrix transforms meant for shields. SceneGraph::FindNodeVisitor shieldFinder(SceneGraph::FindNodeVisitor::MATCH_NAME_ENDSWITH, s_matrixTransformName); model->GetRoot()->Accept(shieldFinder); const std::vector<Node*> &results = shieldFinder.GetResults(); //Store pointer to the shields for later. for (unsigned int i=0; i < results.size(); i++) { MatrixTransform *mt = dynamic_cast<MatrixTransform*>(results.at(i)); assert(mt); for(Uint32 iChild=0 ; iChild<mt->GetNumChildren() ; ++iChild) { Node* node = mt->GetChildAt(iChild); if (node) { RefCountedPtr<StaticGeometry> sg(dynamic_cast<StaticGeometry*>(node)); assert(sg.Valid()); sg->SetNodeMask(SceneGraph::NODE_TRANSPARENT); Graphics::RenderStateDesc rsd; rsd.blendMode = Graphics::BLEND_ALPHA; rsd.depthWrite = false; sg->SetRenderState(sg->GetRenderer()->CreateRenderState(rsd)); // set the material for (Uint32 iMesh = 0; iMesh < sg->GetNumMeshes(); ++iMesh) { StaticGeometry::Mesh &rMesh = sg->GetMeshAt(iMesh); rMesh.material = GetGlobalShieldMaterial(); } m_shields.push_back(Shield(Color3ub(255), mt->GetTransform(), sg.Get())); } } } }
virtual void apply(MatrixTransform& mt) { Matrix matrix; if (_useInverseMatrix) _cp.getInverse(matrix); else _cp.getMatrix(matrix); mt.setMatrix(osg::Matrix::translate(-_pivotPoint)*matrix); }
// // INIT // bool MathematicPlugin::init() { if (plugin) return false; if (cover->debugLevel(3)) fprintf(stderr, "\nMathematicPlugin::MathematicPlugin\n"); // set plugin MathematicPlugin::plugin = this; // rotate scene so that x axis is in front MatrixTransform *trafo = VRSceneGraph::instance()->getTransform(); Matrix m; m.makeRotate(inDegrees(-90.0), 0.0, 0.0, 1.0); trafo->setMatrix(m); // bounding box boundary_ = (double)coCoviseConfig::getFloat("max", "COVER.Plugin.Mathematic.Boundary", boundary_); boundingBox_ = new BoundingBox(-boundary_, -boundary_, -boundary_, boundary_, boundary_, boundary_); coVRPoint::setBoundingBox(boundingBox_); coVRLine::setBoundingBox(boundingBox_); coVRPlane::setBoundingBox(boundingBox_); coVRDirection::setBoundingBox(boundingBox_); coVRDistance::setBoundingBox(boundingBox_); drawBoundingBox(boundingBox_); // mathematics menu makeMathematicsMenu(); // make the menus state label, it shows which objects intersects, etc stateLabel_ = new coLabelMenuItem(" "); mathematicsMenu_->insert(stateLabel_, mainMenuSepPos_ - 1); // colored axis axis_ = new coVRCoordinateAxis(0.07, boundary_, true); // zoom scene VRSceneGraph::instance()->viewAll(); return true; }
MatrixTransform* loadModel(std::string name, float scale, float rotX, float rotY, float rotZ, osg::Vec3 translate) { __FUNCTION_HEADER__ Node* n = NULL; //did we already load (or try to load) this one? std::map<std::string, osg::ref_ptr<osg::Node> >::iterator i; bool haz = false; for(i = gLoadedModels.begin(); i != gLoadedModels.end(); i++) { if(i->first == name) { haz = true; // printf("We already have %s\n", name.c_str()); n = i->second; } } if(!haz) //if we didn't try to laod it before, do so now { n = osgDB::readNodeFile(findDataFile(name)); gLoadedModels[name] = n; if(!n) logError("Unable to load model %s\n", name.c_str()); else printf("Loaded %s\n", name.c_str()); } if(!n) return NULL; MatrixTransform* m = new MatrixTransform(); m->setName(name); m->addChild(n); Matrix mat = Matrix::scale(scale, scale, scale); mat = mat * Matrix::rotate(rotX / 57.296, Vec3(1, 0, 0)); mat = mat * Matrix::rotate(rotY / 57.296, Vec3(0, 1, 0)); mat = mat * Matrix::rotate(rotZ / 57.296, Vec3(0, 0, 1)); mat = mat * Matrix::translate(translate); m->setMatrix(mat); return m; }
NavLights::NavLights(SceneGraph::Model *model, float period) : m_time(0.f) , m_period(period) , m_enabled(false) { PROFILE_SCOPED(); assert(g_initted); Graphics::Renderer *renderer = model->GetRenderer(); using SceneGraph::Node; using SceneGraph::MatrixTransform; using SceneGraph::Billboard; //This will find all matrix transforms meant for navlights. SceneGraph::FindNodeVisitor lightFinder(SceneGraph::FindNodeVisitor::MATCH_NAME_STARTSWITH, "navlight_"); model->GetRoot()->Accept(lightFinder); const std::vector<Node*> &results = lightFinder.GetResults(); //attach light billboards for (unsigned int i=0; i < results.size(); i++) { MatrixTransform *mt = dynamic_cast<MatrixTransform*>(results.at(i)); assert(mt); Billboard *bblight = new Billboard(model, renderer, BILLBOARD_SIZE); Uint32 group = 0; Uint8 mask = 0xff; //always on Uint8 color = NAVLIGHT_BLUE; if (mt->GetName().substr(9, 3) == "red") { mask = 0x0f; color = NAVLIGHT_RED; } else if (mt->GetName().substr(9, 5) == "green") { mask = 0xf0; color = NAVLIGHT_GREEN; } else if (mt->GetName().substr(9, 3) == "pad") { //group by pad number // due to this problem: http://stackoverflow.com/questions/15825254/why-is-scanfhhu-char-overwriting-other-variables-when-they-are-local // where MSVC is still using a C89 compiler the format identifer %hhu is not recognised. Therefore I've switched to Uint32 for group. PiVerify(1 == sscanf(mt->GetName().c_str(), "navlight_pad%u", &group)); mask = 0xf0; } bblight->SetColorUVoffset(get_color(color)); GroupLightsVecIter glit = std::find_if(m_groupLights.begin(), m_groupLights.end(), GroupMatch(group)); if(glit == m_groupLights.end()) { // didn't find group, create a new one m_groupLights.push_back(TGroupLights(group)); // now use it glit = (m_groupLights.end() - 1); } assert(glit != m_groupLights.end()); glit->m_lights.push_back(LightBulb(group, mask, color, bblight)); mt->SetNodeMask(SceneGraph::NODE_TRANSPARENT); mt->AddChild(bblight); } }
int Tree::generate(MatrixTransform *curr, int start, int level){ //Node *curr = root; printf("before: %d\n", start); int index_jump; i=start; while(i < result.size()){ printf("level is: %d\n", level); if(result[i] == '['){ MatrixTransform *tmp = new MatrixTransform(); //tmp->M = glm::scale(glm::mat4(1.0f), glm::vec3(0.5f, 0.5f, 0.5f)); curr->addChild(tmp); generate(tmp, i+1, level+1); i++; //i += index_jump; } else if(result[i] == ']'){ i++; return i-start+1; } else if(result[i] == 'F'){ MatrixTransform *tmp = new MatrixTransform(); tmp->M = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 1.0f, 0.0f))*tmp->M; curr->addChild(tmp); Geode *child = new Geode(obj); tmp->addChild(child); index_jump = generate(tmp, i+1, level+1); i++; //i += index_jump; } else if(result[i] == '+'){ i++; curr->M = glm::rotate(glm::mat4(1.0f), 20.0f/180.0f*glm::pi<float>(), glm::vec3(0.0f, 0.0f, 1.0f))*curr->M; } else if(result[i] == '-'){ i++; curr->M = glm::rotate(glm::mat4(1.0f), -20.0f/180.0f*glm::pi<float>(), glm::vec3(0.0f, 0.0f, 1.0f))*curr->M; } } printf("after: %d\n", i); return 0; }
//---------------------------------------------------------------------------- // Callback method called when system is idle. void Window::idleCallback() { Matrix4 transform; Matrix4 temp; Matrix4 reverseTemp; temp = leftArmRotation.get(); reverseTemp = temp; if (walk) { if (forw) { temp.makeRotateX(degree); reverseTemp.makeRotateX(-degree); degree++; if (degree == 20) forw = !forw; } else { temp.makeRotateX(degree); reverseTemp.makeRotateX(-degree); std::cout << "ASD" << std::endl; degree--; if (degree == -20) forw = !forw; } } else { degree = 0; temp.identity(); reverseTemp.identity(); } transform.makeTranslate(0, -1.5, 0); temp = temp * transform; reverseTemp = reverseTemp * transform; transform.makeTranslate(0, 1.5, 0); temp = transform * temp; reverseTemp = transform * reverseTemp; leftArmRotation.set(temp); rightLegRotation.set(temp); rightArmRotation.set(reverseTemp); leftLegRotation.set(reverseTemp); displayCallback(); // call display routine to show the object }
Boat::Boat() { mT = 0; mTV = 0.1; MatrixTransform* modelTransform = new MatrixTransform(); mPat->addChild(modelTransform); //load a boat model MatrixTransform* n = Util::loadModel("jetski.3DS", 1.0/12 / 4, -90); if(n) { // Util::setTint(n, Vec4(1, 0, 0, 1)); //the texture doesn't apply automatically for some reason, so let's do it manually Image* image = osgDB::readImageFile(Util::findDataFile("jetski.jpg")); Texture2D* tex = new Texture2D(image); n->getOrCreateStateSet()->setTextureAttributeAndModes(0, tex); } modelTransform->addChild(n); }
TextureWidget::TextureWidget(Interaction* interaction, float width, float height) : Widget(), Events() { StateSet* stateSet; _interaction = interaction; _width = width; _height = height; createBackground(); createTexturesGeometry(); initLabels(); initTextures(); _texture[0] = new Geode(); _texture[0]->addDrawable(_geom); _texture[0]->addDrawable(_label0); _texture[0]->addDrawable(_texGeom0); stateSet = _texGeom0->getOrCreateStateSet(); stateSet->setMode(GL_LIGHTING, StateAttribute::OFF); stateSet->setRenderingHint(StateSet::TRANSPARENT_BIN); stateSet->setTextureAttributeAndModes(StateAttribute::TEXTURE, _tex0, StateAttribute::ON); _texture[1] = new Geode(); _texture[1]->addDrawable(_geom); _texture[1]->addDrawable(_label1); _texture[1]->addDrawable(_texGeom1); stateSet = _texGeom1->getOrCreateStateSet(); stateSet->setMode(GL_LIGHTING, StateAttribute::OFF); stateSet->setRenderingHint(StateSet::TRANSPARENT_BIN); stateSet->setTextureAttributeAndModes(StateAttribute::TEXTURE, _tex1, StateAttribute::ON); _swTexture = new Switch(); _swTexture->addChild(_texture[0]); _swTexture->addChild(_texture[1]); _swTexture->setSingleChildOn(0); _node->addChild(_swTexture.get()); _leftGeode = new Geode(); _rightGeode = new Geode(); MatrixTransform* transLeft = new MatrixTransform(); MatrixTransform* transRight = new MatrixTransform(); Matrix trans; trans.makeTranslate(Vec3(-_width/2.0, -_height/2.0 - DEFAULT_LABEL_HEIGHT/2.0, 3*EPSILON_Z)); transLeft->setMatrix(trans); transLeft->addChild(_leftGeode); trans.makeTranslate(Vec3(+_width/2.0, -_height/2.0 - DEFAULT_LABEL_HEIGHT/2.0, 3*EPSILON_Z)); transRight->setMatrix(trans); transRight->addChild(_rightGeode); _node->addChild(transLeft); _node->addChild(transRight); _interaction->addListener(this, this); }
bool MatrixTransform::equals(const MatrixTransform & other) const { const float abserror = 1e-9f; for(int i=0; i<16; ++i) { if(!equalWithAbsError(getImpl()->matrix_[i], other.getImpl()->matrix_[i], abserror)) { return false; } } for(int i=0; i<4; ++i) { if(!equalWithAbsError(getImpl()->offset_[i], other.getImpl()->offset_[i], abserror)) { return false; } } return true; }
NavLights::NavLights(SceneGraph::Model *model, float period) : m_time(0.f) , m_period(period) , m_enabled(false) { assert(g_initted); Graphics::Renderer *renderer = model->GetRenderer(); using SceneGraph::Node; using SceneGraph::MatrixTransform; using SceneGraph::Billboard; //This will find all matrix transforms meant for navlights. SceneGraph::FindNodeVisitor lightFinder(SceneGraph::FindNodeVisitor::MATCH_NAME_STARTSWITH, "navlight_"); model->GetRoot()->Accept(lightFinder); const std::vector<Node*> &results = lightFinder.GetResults(); //attach light billboards for (unsigned int i=0; i < results.size(); i++) { MatrixTransform *mt = dynamic_cast<MatrixTransform*>(results.at(i)); assert(mt); Billboard *bblight = new Billboard(renderer, matBlue, vector3f(0.f), BILLBOARD_SIZE); Uint8 group = 0; Uint8 mask = 0xff; //always on Uint8 color = NAVLIGHT_BLUE; if (mt->GetName().substr(9, 3) == "red") { bblight->SetMaterial(matRed); mask = 0x0f; color = NAVLIGHT_RED; } else if (mt->GetName().substr(9, 5) == "green") { mask = 0xf0; color = NAVLIGHT_GREEN; } else if (mt->GetName().substr(9, 3) == "pad") { //group by pad number group = atoi(mt->GetName().substr(12, 1).c_str()); mask = 0xf0; } bblight->SetMaterial(get_material(color)); m_lights.push_back(LightBulb(group, mask, color, bblight)); mt->SetNodeMask(SceneGraph::NODE_TRANSPARENT); mt->AddChild(bblight); } }
MatrixTransform* LevelManager::LoadTrees(int amount) { MatrixTransform *forestMT = new MatrixTransform(); LTree TreeGenerator = LTree(0, LSysParam()); treeGrammars = new LSysParam[3]; std::string fernTree = "Tree::Fern Grammar"; std::string niceTree = "Tree::Nice Grammar"; std::string bushTree = "Tree::Bush Grammar"; std::string stalkyTree = "Tree::StalkyTree"; treeGrammars[0].iterations = 5; treeGrammars[0].length = 0.12f; treeGrammars[0].rules['X'] = "F[+X]F[-X]+X"; treeGrammars[0].rules['F'] = "FF"; treeGrammars[0].startRule = 'X'; LSysParam bushTreeProp; treeGrammars[1].iterations = 3; treeGrammars[1].length = 0.5f; treeGrammars[1].radius = 0.009f; treeGrammars[1].rules['F'] = "FF-[-F+F+F]+[+F-F-F]"; treeGrammars[1].startRule = 'F'; treeGrammars[2].iterations = 4; treeGrammars[2].length = 0.3f; treeGrammars[2].radius = 0.08f; treeGrammars[2].rules['F'] = "F[+F]F[-F]F";; treeGrammars[2].startRule = 'F'; // Default LSysParam is a fern grammar EntityNode *fernTreeNode = TreeGenerator.generate(); fernTreeNode->name = fernTree; refES->insert(fernTreeNode); TreeGenerator.setProperties(treeGrammars[0]); EntityNode *niceTreeNode = TreeGenerator.generate(); niceTreeNode->name = niceTree; refES->insert(niceTreeNode); TreeGenerator.setProperties(treeGrammars[1]); EntityNode *bushTreeNode = TreeGenerator.generate(); bushTreeNode->name = bushTree; refES->insert(bushTreeNode); TreeGenerator.setProperties(treeGrammars[2]); EntityNode *stalkyTreeNode = TreeGenerator.generate(); stalkyTreeNode->name = stalkyTree; refES->insert(stalkyTreeNode); int type = 0; MatrixTransform **treeMT = new MatrixTransform*[amount]; Tree **tree = new Tree*[amount]; for(int i = 0; i < amount; ++i) { treeMT[i] = new MatrixTransform(); if( i % 4 == 0 ){ tree[i] = new Tree(fernTree, 0, 0); }else if(i % 4 == 1){ tree[i] = new Tree(niceTree, 0, 0); }else if(i % 4 == 2){ tree[i] = new Tree(bushTree, 0, 0); }else{ tree[i] = new Tree(stalkyTree, 0, 0); } int rx = 0, height = 0, rz = 0; if( refSG->terrain != nullptr ) { rx = (rand() % refSG->terrain->terrainGridWidth) - refSG->terrain->terrainGridWidth/2; rz = (rand() % refSG->terrain->terrainGridLength) - refSG->terrain->terrainGridLength/2; height = refSG->terrain->terrainGetHeight(rx,rz); } treeMT[i]->setMatrix( mat4().translate( vec3(rx,(float)(height) - 0.3f, rz)) ); treeMT[i]->setMatrix( mat4().translate( vec3(rx,(float)(height) - 0.3f, rz)) ); treeMT[i]->addChild(tree[i]); forestMT->addChild(treeMT[i]); } return forestMT; }
/*************************************************************** * Function: applyScaling() * * 'gridUnitScaleVect' is guranteed to be non-negative vector * ***************************************************************/ void CAVEGroupEditGeodeWireframe::applyScaling( const short &nOffsetSegs, const Vec3 &gridUnitScaleVect, const std::string &gridUnitScaleInfo) { mManipulateSwitch->setAllChildrenOn(); /* scale to other direction: clear all children of 'mManipulateSwitch' except child[0], rebuild offset tree */ if (mScaleNumSegs * nOffsetSegs <= 0) { unsigned int numChildren = mManipulateSwitch->getNumChildren(); if (numChildren > 1) { mManipulateSwitch->removeChildren(1, numChildren - 1); MatrixTransVector::iterator itrMatTrans = mManipulateMatTransVector.begin(); mManipulateMatTransVector.erase(itrMatTrans + 1, itrMatTrans + numChildren); } mScaleNumSegs = 0; } /* decide unit offset vector and start/end index of children under 'mManipulateSwitch' */ short idxStart = 0, idxEnd = 0; if (nOffsetSegs != 0) { idxStart = mScaleNumSegs; idxEnd = nOffsetSegs; } idxStart = idxStart > 0 ? idxStart: -idxStart; idxEnd = idxEnd > 0 ? idxEnd : -idxEnd; /* update the first wireframe with global translation and rotation */ if (idxStart == 0) mManipulateMatTransVector[0]->setMatrix(mBoundBoxScaleMat * mAccRootMat); /* create or remove a sequence of extra children under 'mMoveSwitch' */ if (idxStart < idxEnd) { for (short i = idxStart + 1; i <= idxEnd; i++) { /* generate scaling vector with non-negative values */ Vec3 scaleVect = Vec3(1, 1, 1); if (nOffsetSegs > 0) scaleVect += gridUnitScaleVect * i; else scaleVect -= gridUnitScaleVect * i; scaleVect.x() = scaleVect.x() > 0 ? scaleVect.x() : 0; scaleVect.y() = scaleVect.y() > 0 ? scaleVect.y() : 0; scaleVect.z() = scaleVect.z() > 0 ? scaleVect.z() : 0; Matrixd scaleMat; scaleMat.makeScale(scaleVect); MatrixTransform *scaleTrans = new MatrixTransform; CAVEGeodeEditWireframeManipulate *manipulateGeode = new CAVEGeodeEditWireframeManipulate; mManipulateSwitch->addChild(scaleTrans); mManipulateMatTransVector.push_back(scaleTrans); scaleTrans->addChild(manipulateGeode); scaleTrans->setMatrix(mBoundBoxScaleMat * mAccRootMat * scaleMat); } } else if (idxStart > idxEnd) { mManipulateSwitch->removeChildren(idxEnd + 1, idxStart - idxEnd); MatrixTransVector::iterator itrMatTrans = mManipulateMatTransVector.begin(); itrMatTrans += idxEnd + 1; mManipulateMatTransVector.erase(itrMatTrans, itrMatTrans + (idxStart - idxEnd)); } mScaleNumSegs = nOffsetSegs; mScaleUnitVect = gridUnitScaleVect; if (!mPrimaryFlag) return; /* update info text if 'this' wireframe is primary */ mEditInfoTextSwitch->setAllChildrenOn(); float scaleUnit = gridUnitScaleVect.x() > 0 ? gridUnitScaleVect.x() : gridUnitScaleVect.y(); scaleUnit = scaleUnit > 0 ? scaleUnit : gridUnitScaleVect.z(); char info[128]; float scaleval = scaleUnit * nOffsetSegs + 1.0f; scaleval = scaleval > 0 ? scaleval:0; sprintf(info, "Scale = %3.2f \nSnapping = ", scaleval); mEditInfoText->setText(info + gridUnitScaleInfo); }
/*************************************************************** * Function: applyRotation() * * 'axisSVect': rotational snapping values around each axis, * for instance, Vec3(2, 0, 0) means rotation around X-axis by * two times of 'gridUnitAngle' * only one component of 'axisIntVect' is supposed to be non-zero * ***************************************************************/ void CAVEGroupEditGeodeWireframe::applyRotation(const osg::Vec3s &axisSVect, const float &gridUnitAngle, const string &gridUnitAngleInfo) { if (!mPrimaryFlag) return; mRotateSwitch->setAllChildrenOn(); /* rotate in other direction: clear all children of 'mRotateSwitch' except child[0], rebuild offset tree */ if ((mRotateSVect.x() * axisSVect.x() + mRotateSVect.y() * axisSVect.y() + mRotateSVect.z() * axisSVect.z()) <= 0) { unsigned int numChildren = mRotateSwitch->getNumChildren(); if (numChildren > 1) { mRotateSwitch->removeChildren(1, numChildren - 1); MatrixTransVector::iterator itrMatTrans = mRotateMatTransVector.begin(); mRotateMatTransVector.erase(itrMatTrans + 1, itrMatTrans + numChildren); } mRotateSVect = Vec3s(0, 0, 0); } /* decide unit rotation quat and start/end index of children under 'mRotateSwitch' */ Vec3 gridRotationAxis; short idxStart = 0, idxEnd = 0; if (axisSVect.x() != 0) { idxStart = mRotateSVect.x(); idxEnd = axisSVect.x(); if (axisSVect.x() > 0) gridRotationAxis = Vec3(1, 0, 0); else gridRotationAxis = Vec3(-1, 0, 0); } else if (axisSVect.y() != 0) { idxStart = mRotateSVect.y(); idxEnd = axisSVect.y(); if (axisSVect.y() > 0) gridRotationAxis = Vec3(0, 1, 0); else gridRotationAxis = Vec3(0, -1, 0); } else if (axisSVect.z() != 0) { idxStart = mRotateSVect.z(); idxEnd = axisSVect.z(); if (axisSVect.z() > 0) gridRotationAxis = Vec3(0, 0, 1); else gridRotationAxis = Vec3(0, 0, -1); } idxStart = idxStart > 0 ? idxStart: -idxStart; idxEnd = idxEnd > 0 ? idxEnd : -idxEnd; /* create or remove a sequence of extra children under 'mRotateSwitch' */ if (idxStart < idxEnd) { for (short i = idxStart + 1; i <= idxEnd; i++) { Matrixd rotMat; rotMat.makeRotate(gridUnitAngle * i, gridRotationAxis); MatrixTransform *rotateTrans = new MatrixTransform; CAVEGeodeEditWireframeRotate *rotateGeode = new CAVEGeodeEditWireframeRotate; mRotateSwitch->addChild(rotateTrans); mRotateMatTransVector.push_back(rotateTrans); rotateTrans->addChild(rotateGeode); rotateTrans->setMatrix(mBoundSphereScaleMat * rotMat); } } else if (idxStart > idxEnd) { mRotateSwitch->removeChildren(idxEnd + 1, idxStart - idxEnd); MatrixTransVector::iterator itrMatTrans = mRotateMatTransVector.begin(); itrMatTrans += idxEnd + 1; mRotateMatTransVector.erase(itrMatTrans, itrMatTrans + (idxStart - idxEnd)); } mRotateSVect = axisSVect; /* update info text if 'this' wireframe is primary */ mEditInfoTextSwitch->setAllChildrenOn(); char info[128]; const float gridUnitAngleDegree = gridUnitAngle * 180 / M_PI; sprintf(info, "Angle = %3.2f\nSnapping = ", gridUnitAngleDegree * idxEnd); mEditInfoText->setText(info + gridUnitAngleInfo); }
/*************************************************************** * Function: applyTranslation() * * 'gridSVect': number of snapping segments along each direction * 'gridUnitLegnth': actual length represented by each segment, * only one component of 'gridSVect' is supposed to be non-zero * ***************************************************************/ void CAVEGroupEditGeodeWireframe::applyTranslation(const osg::Vec3s &gridSVect, const float &gridUnitLegnth, const string &gridUnitLegnthInfo) { mMoveSwitch->setAllChildrenOn(); /* move to other direction: clear all children of 'mMoveSwitch' except child[0], rebuild offset tree */ if ((mMoveSVect.x() * gridSVect.x() + mMoveSVect.y() * gridSVect.y() + mMoveSVect.z() * gridSVect.z()) <= 0) { unsigned int numChildren = mMoveSwitch->getNumChildren(); if (numChildren > 1) { mMoveSwitch->removeChildren(1, numChildren - 1); MatrixTransVector::iterator itrMatTrans = mMoveMatTransVector.begin(); mMoveMatTransVector.erase(itrMatTrans + 1, itrMatTrans + numChildren); } mMoveSVect = Vec3s(0, 0, 0); } /* decide unit offset vector and start/end index of children under 'mMoveSwitch' */ Vec3 gridOffsetVect; short idxStart = 0, idxEnd = 0; if (gridSVect.x() != 0) { idxStart = mMoveSVect.x(); idxEnd = gridSVect.x(); if (gridSVect.x() > 0) gridOffsetVect = Vec3(gridUnitLegnth, 0, 0); else gridOffsetVect = Vec3(-gridUnitLegnth, 0, 0); } else if (gridSVect.y() != 0) { idxStart = mMoveSVect.y(); idxEnd = gridSVect.y(); if (gridSVect.y() > 0) gridOffsetVect = Vec3(0, gridUnitLegnth, 0); else gridOffsetVect = Vec3(0, -gridUnitLegnth, 0); } else if (gridSVect.z() != 0) { idxStart = mMoveSVect.z(); idxEnd = gridSVect.z(); if (gridSVect.z() > 0) gridOffsetVect = Vec3(0, 0, gridUnitLegnth); else gridOffsetVect = Vec3(0, 0, -gridUnitLegnth); } idxStart = idxStart > 0 ? idxStart: -idxStart; idxEnd = idxEnd > 0 ? idxEnd : -idxEnd; /* update the first wireframe with global translation and rotation */ if (idxStart == 0) mMoveMatTransVector[0]->setMatrix(mBoundBoxScaleMat * mAccRootMat); /* create or remove a sequence of extra children under 'mMoveSwitch' */ if (idxStart < idxEnd) { for (short i = idxStart + 1; i <= idxEnd; i++) { Matrixd transMat; transMat.makeTranslate(gridOffsetVect * i); MatrixTransform *moveTrans = new MatrixTransform; CAVEGeodeEditWireframeMove *moveGeode = new CAVEGeodeEditWireframeMove; mMoveSwitch->addChild(moveTrans); mMoveMatTransVector.push_back(moveTrans); moveTrans->addChild(moveGeode); moveTrans->setMatrix(mBoundBoxScaleMat * mAccRootMat * transMat); } } else if (idxStart > idxEnd) { mMoveSwitch->removeChildren(idxEnd + 1, idxStart - idxEnd); MatrixTransVector::iterator itrMatTrans = mMoveMatTransVector.begin(); itrMatTrans += idxEnd + 1; mMoveMatTransVector.erase(itrMatTrans, itrMatTrans + (idxStart - idxEnd)); } mMoveSVect = gridSVect; if (!mPrimaryFlag) return; /* update info text if 'this' wireframe is primary */ mEditInfoTextSwitch->setAllChildrenOn(); char info[128]; sprintf(info, "Offset = %3.2f m\nSnapping = ", gridUnitLegnth * idxEnd); mEditInfoText->setText(info + gridUnitLegnthInfo); }
void Window::loadCharacter() { Matrix4 temp; Matrix4 id; id.identity(); //Setting up Controller temp.makeTranslate(0, 0, 10); control = MatrixTransform(temp); //Setting up Head headCube = Cube(2); headCube.setTexture(head); headRotation = MatrixTransform(id); headScaling = MatrixTransform(id); temp.makeTranslate(0, 7, 0); headTranslation = MatrixTransform(temp); headRotation.addChild(&headCube); headScaling.addChild(&headRotation); headTranslation.addChild(&headScaling); control.addChild(&headTranslation); //Setting up body bodyCube = Cube(1); bodyCube.setTexture(body); bodyRotation = MatrixTransform(id); temp.makeScale(2, 3, 1); bodyScaling = MatrixTransform(temp); temp.makeTranslate(0, 4.5, 0); bodyTranslation = MatrixTransform(temp); bodyRotation.addChild(&bodyCube); bodyScaling.addChild(&bodyRotation); bodyTranslation.addChild(&bodyScaling); control.addChild(&bodyTranslation); //Setting up Arms armCube = Cube(1); armCube.setTexture(arm); leftArmRotation = MatrixTransform(id); rightArmRotation = MatrixTransform(id); temp.makeScale(1, 3, 1); leftArmScaling = MatrixTransform(temp); rightArmScaling = MatrixTransform(temp); temp.makeTranslate(1.5, 4.5, 0); leftArmTranslation = MatrixTransform(temp); temp.makeTranslate(-(1.5), 4.5, 0); rightArmTranslation = MatrixTransform(temp); leftArmScaling.addChild(&armCube); rightArmScaling.addChild(&armCube); leftArmRotation.addChild(&leftArmScaling); rightArmRotation.addChild(&rightArmScaling); leftArmTranslation.addChild(&leftArmRotation); rightArmTranslation.addChild(&rightArmRotation); control.addChild(&leftArmTranslation); control.addChild(&rightArmTranslation); //Setting up Legs legCube = Cube(1); legCube.setTexture(leg); leftLegRotation = MatrixTransform(id); rightLegRotation = MatrixTransform(id); temp.makeScale(1, 3, 1); leftLegScaling = MatrixTransform(temp); rightLegScaling = MatrixTransform(temp); temp.makeTranslate(.5, 1.5, 0); leftLegTranslation = MatrixTransform(temp); temp.makeTranslate(-.5, 1.5, 0); rightLegTranslation = MatrixTransform(temp); leftLegScaling.addChild(&legCube); rightLegScaling.addChild(&legCube); leftLegRotation.addChild(&leftLegScaling); rightLegRotation.addChild(&rightLegScaling); leftLegTranslation.addChild(&leftLegRotation); rightLegTranslation.addChild(&rightLegRotation); control.addChild(&leftLegTranslation); control.addChild(&rightLegTranslation); character.addChild(&control); }