예제 #1
0
CircleShape::CircleShape(std::string command, std::string name) 
{
    _type = SimpleShape::CIRCLE;

    BasicShape::setName(name);
    _numFaces = 20;
    
    _vertices = new osg::Vec3Array(_numFaces + 2);
    _colors = new osg::Vec4Array(_numFaces + 2);
    
    setPosition(osg::Vec3(0.0, 0.0, 0.0), 1.0);
    setColor(osg::Vec4(1.0, 0.0, 0.0, 1.0),osg::Vec4(0.0, 1.0, 0.0, 1.0));
    update(command);
    
    setVertexArray(_vertices); 
    setColorArray(_colors); 
    setColorBinding(osg::Geometry::BIND_PER_VERTEX);
    addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_FAN,0,_numFaces + 2));

    osg::StateSet* state = getOrCreateStateSet();
    state->setMode(GL_BLEND, osg::StateAttribute::ON);
    state->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    //osg::Material* mat = new osg::Material();
    //mat->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
    //state->setAttributeAndModes(mat, osg::StateAttribute::ON);
}
예제 #2
0
void OpenGLRenderer::drawIndexed(Primitive primitive, const TexturedVertex * vertices, size_t nvertices, unsigned short * indices, size_t nindices) {
	
	beforeDraw<TexturedVertex>();
	
	if(useVertexArrays && shader) {
		
		glBindBuffer(GL_ARRAY_BUFFER, GL_NONE);
		
		setVertexArray(vertices, vertices);
		
		glDrawRangeElements(arxToGlPrimitiveType[primitive], 0, nvertices - 1, nindices, GL_UNSIGNED_SHORT, indices);
		
	} else {
		
		glBegin(arxToGlPrimitiveType[primitive]);
		
		for(size_t i = 0; i < nindices; i++) {
			renderVertex(vertices[indices[i]]);
		}
		
		glEnd();
		
	}
	
	CHECK_GL;
}
예제 #3
0
//==============================================================================
void LineSegmentShapeDrawable::refresh(bool firstTime)
{
  if(mLineSegmentShape->getDataVariance() == dart::dynamics::Shape::STATIC)
    setDataVariance(osg::Object::STATIC);
  else
    setDataVariance(osg::Object::DYNAMIC);

  const std::vector<Eigen::Vector3d>& vertices =
      mLineSegmentShape->getVertices();

  const Eigen::aligned_vector<Eigen::Vector2i>& connections =
      mLineSegmentShape->getConnections();

  if(   mLineSegmentShape->checkDataVariance(dart::dynamics::Shape::DYNAMIC_ELEMENTS)
     || firstTime)
  {
    osg::ref_ptr<osg::DrawElementsUInt> elements =
        new osg::DrawElementsUInt(GL_LINES);
    elements->reserve(2*connections.size());

    for(size_t i=0; i < connections.size(); ++i)
    {
      const Eigen::Vector2i& c = connections[i];
      elements->push_back(c[0]);
      elements->push_back(c[1]);
    }

    addPrimitiveSet(elements);
  }

  if(   mLineSegmentShape->checkDataVariance(dart::dynamics::Shape::DYNAMIC_VERTICES)
     || mLineSegmentShape->checkDataVariance(dart::dynamics::Shape::DYNAMIC_ELEMENTS)
     || firstTime)
  {
    if(mVertices->size() != vertices.size())
      mVertices->resize(vertices.size());

    for(size_t i=0; i<vertices.size(); ++i)
      (*mVertices)[i] = eigToOsgVec3(vertices[i]);

    setVertexArray(mVertices);
  }

  if(   mLineSegmentShape->checkDataVariance(dart::dynamics::Shape::DYNAMIC_COLOR)
     || firstTime)
  {
    if(mColors->size() != 1)
      mColors->resize(1);

    (*mColors)[0] = eigToOsgVec4(mLineSegmentShape->getRGBA());

    setColorArray(mColors, osg::Array::BIND_OVERALL);
  }
}
//------------------------------------------------------------------------------
void HudTextureElement::updateVb()
{
    Vector2d pos;
    float size;
    getPositionAndSize(pos, size);

    osg::Vec3Array * vertex = new osg::Vec3Array(4); // vec3 or computeBounds will complain
    setVertexArray(vertex);
    
    (*vertex)[0].set(pos.x_,                    pos.y_,      0.0f);
    (*vertex)[1].set(pos.x_+size*aspect_ratio_, pos.y_,      0.0f);
    (*vertex)[2].set(pos.x_+size*aspect_ratio_, pos.y_+size, 0.0f);
    (*vertex)[3].set(pos.x_,                    pos.y_+size, 0.0f);
}
예제 #5
0
파일: Widget.cpp 프로젝트: BodyViz/osg
Widget::Widget(const std::string& name, point_type w, point_type h):
_parent    (0),
_index     (0),
_layer     (LAYER_LOW),
_padLeft   (0.0f),
_padRight  (0.0f),
_padTop    (0.0f),
_padBottom (0.0f),
_valign    (VA_CENTER),
_halign    (HA_CENTER),
_coordMode (CM_ABSOLUTE),
_canFill   (false),
_canClone  (true),
_isManaged (false),
_isStyled  (false),
_minWidth  (0.0f),
_minHeight (0.0f) {
    _name = name.size() ? name : generateRandomName("Widget");

    if(!_norms.valid()) {
        _norms = new PointArray(1);

        (*_norms)[0].set(0.0f, 0.0f, 1.0f);
        (*_norms)[0].normalize();
    }

    TexCoordArray* texs = new TexCoordArray(4);

    // Fill our texture coordinates with null stuff for now, since we aren't using them
    // until an Image is set at some later point.
    std::fill(texs->begin(), texs->end(), osg::Vec2(0.0f, 0.0f));

    setUseDisplayList(false);
    setDataVariance(osg::Object::DYNAMIC);
    setVertexArray(new PointArray(4));
    setColorArray(new ColorArray(4));
    setNormalArray(_norms.get());
    setTexCoordArray(0, texs);
    setNormalBinding(osg::Geometry::BIND_OVERALL);
    setColorBinding(osg::Geometry::BIND_PER_VERTEX);
    addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, 4));

    setDimensions(0.0f, 0.0f, w, h);
    setColor(1.0f, 1.0f, 1.0f, 1.0f);
}
예제 #6
0
void HeightmapShapeDrawable<S>::refresh(bool /*firstTime*/)
{
  if (mHeightmapShape->getDataVariance() == dynamics::Shape::STATIC)
    setDataVariance(::osg::Object::STATIC);
  else
    setDataVariance(::osg::Object::DYNAMIC);

  // Row major matrix where top left corner is the height at (0, 0), and bottom
  // right corner is the height at (rows, -cols) in (x, y) coordinates.
  const auto& heightmap = mHeightmapShape->getHeightField();

  // This function is called whenever the heightmap version is increased, and
  // the heightmap could be updated in the version up. So we always update the
  // heightmap.
  {
    assert(mElements);
    assert(mNormals);
    setVertices<S>(
        heightmap,
        *mVertices,
        *mElements,
        *mNormals,
        mHeightmapShape->getScale());
    addPrimitiveSet(mElements);

    setVertexArray(mVertices);
    setNormalArray(mNormals, ::osg::Array::BIND_PER_VERTEX);
  }

  // This function is called whenever the heightmap version is increased, and
  // the color could be updated in the version up. So we always update the
  // color.
  {
    if (mColors->size() != 1)
      mColors->resize(1);

    (*mColors)[0] = eigToOsgVec4d(mVisualAspect->getRGBA());

    setColorArray(mColors, ::osg::Array::BIND_OVERALL);
  }
}
예제 #7
0
    WidgetBorder::WidgetBorder(const Widget & widget) : widget(widget)
    {
        if (osg::Vec3Array * data = new osg::Vec3Array(4))
        {
            const Rect & rect = widget.getRect();
            const int padding = widget.getBorderPadding();
            const float z = widget.getZ();

            spdlog::get("log")->info("initializing WidgetBorder with rect {}, {}, {}, {}", rect.x1, rect.y1, rect.x2, rect.y2);

            (*data)[0].set(rect.x1 - padding, rect.y2 + padding, z);
            (*data)[1].set(rect.x1 - padding, rect.y1 - padding, z);
            (*data)[2].set(rect.x2 + padding, rect.y1 - padding, z);
            (*data)[3].set(rect.x2 + padding, rect.y2 + padding, z);

            setVertexArray(data);
        }

        if (osg::Vec3Array * data = new osg::Vec3Array(1))
        {
            (*data)[0].set(0.f, 0.f, 1.f);

            setNormalArray(data, osg::Array::BIND_OVERALL);
        }

        if (osg::Vec4Array * data = new osg::Vec4Array(1))
        {
            /*
            const osg::Color & color = widget.getBorderColor();

            (*data)[0].set(widget.getBorderColor().r, widget.getBorderColor().g, widget.getBorderColor().b, widget.getBorderColor().a);
            */

            (*data)[0].set(1.f, 1.f, 1.f, 1.f);

            setColorArray(data, osg::Array::BIND_OVERALL);
        }

        addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINE_LOOP, 0, 4));
        // TODO: getOrCreateStateSet()->setAttribute(new osg::LineWidth(widget.getBorderPadding()));
    }
예제 #8
0
    SomePointsRenderer(SomePointsGenerator*_generator)
    {

        setUseVertexBufferObjects(true);

        osg::Vec4Array* vAry2 = new osg::Vec4Array;
        vAry2->resize(_generator->getNumPrimitivesGenerated());
        setVertexArray(vAry2);
        addPrimitiveSet( new osg::DrawArrays( GL_LINES, 0,_generator->getNumPrimitivesGenerated()));

        osg::StateSet* sset = getOrCreateStateSet();
        ///hacking rendering order
        /*osg::BlendFunc* bf = new
        osg::BlendFunc(osg::BlendFunc::SRC_ALPHA,
        osg::BlendFunc::ONE_MINUS_SRC_ALPHA );
        sset->setAttributeAndModes(bf);*/

        sset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
        getOrCreateVertexBufferObject();
        sset->setAttribute( createRenderShader() );

    }
예제 #9
0
SomePointsGenerator::SomePointsGenerator():osg::Geometry()
{

    setUseVertexBufferObjects(true);

    osg::StateSet* sset = getOrCreateStateSet();
    sset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
    vAry = new osg::Vec4Array;;
    vAry->push_back( osg::Vec4(0,0,0,1) );
    vAry->push_back( osg::Vec4(0,1,0,1) );
    vAry->push_back( osg::Vec4(1,0,0,1) );
    vAry->push_back( osg::Vec4(1,1,0,1 ));
    addPrimitiveSet( new osg::DrawArrays( GL_POINTS, 0, vAry->size() ) );
    setVertexArray( vAry );

    _program=createGeneratorShader() ;
    sset->setAttribute(_program );

    // a generic cyclic animation value
    osg::Uniform* u_anim1( new osg::Uniform( "u_anim1", 0.9f ) );
    u_anim1->setUpdateCallback( new SineAnimation( 4, 0.5, 0.5 ) );
    sset->addUniform( u_anim1 );

}
    SomePoints()
    {
        osg::Vec4Array* cAry = new osg::Vec4Array;
        setColorArray( cAry, osg::Array::BIND_OVERALL );
        cAry->push_back( osg::Vec4(1,1,1,1) );

        osg::Vec3Array* vAry = new osg::Vec3Array;
        setVertexArray( vAry );
        vAry->push_back( osg::Vec3(0,0,0) );
        vAry->push_back( osg::Vec3(0,1,0) );
        vAry->push_back( osg::Vec3(1,0,0) );
        vAry->push_back( osg::Vec3(1,1,0) );
        vAry->push_back( osg::Vec3(0,0,1) );
        vAry->push_back( osg::Vec3(0,1,1) );
        vAry->push_back( osg::Vec3(1,0,1) );
        vAry->push_back( osg::Vec3(1,1,1) );

        addPrimitiveSet( new osg::DrawArrays( GL_POINTS, 0, vAry->size() ) );

        osg::StateSet* sset = getOrCreateStateSet();
        sset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );

        // if things go wrong, fall back to big points
        osg::Point* p = new osg::Point;
        p->setSize(6);
        sset->setAttribute( p );

#ifdef ENABLE_GLSL
        sset->setAttribute( createShader() );

        // a generic cyclic animation value
        osg::Uniform* u_anim1( new osg::Uniform( "u_anim1", 0.0f ) );
        u_anim1->setUpdateCallback( new SineAnimation( 4, 0.5, 0.5 ) );
        sset->addUniform( u_anim1 );
#endif
    }
예제 #11
0
void Ellipsoid::subDraw()
{
	computeAssistVar();
	getPrimitiveSetList().clear();

	osg::ref_ptr<osg::Vec3Array> vertexArr = new osg::Vec3Array;
	osg::ref_ptr<osg::Vec3Array> normalArr = new osg::Vec3Array;
	setVertexArray(vertexArr);
	setNormalArray(normalArr, osg::Array::BIND_PER_VERTEX);
	osg::ref_ptr<osg::Vec4Array> colArr = new osg::Vec4Array();
	colArr->push_back(m_color);
	setColorArray(colArr, osg::Array::BIND_OVERALL);

	bool isFull = osg::equivalent(m_angle, 2 * M_PI, GetEpsilon());
	if (isFull)
	{
		m_angle = 2 * M_PI;
	}

	osg::Vec3 bottomNormal = -m_aLen;
	bottomNormal.normalize();
	osg::Quat localToWold;
	localToWold.makeRotate(osg::Z_AXIS, -bottomNormal);
	osg::Vec3 xVec = localToWold * osg::X_AXIS;
	osg::Vec3 yVec = xVec ^ bottomNormal;
	int hCount = m_bDivision;
	double hIncAng = 2 * M_PI / hCount;
	osg::Quat hQuat(hIncAng, bottomNormal);

	int vCount = (int)ceil(m_angle / (2 * M_PI / m_aDivision));
	if (vCount & 1) // 如果是奇数,则变成偶数
		++vCount;
	double vIncAng = m_angle / vCount;

	double currAngle = m_angle / 2.0;
	double b = m_bRadius;
	double a = m_aLen.length();
	osg::Vec3 vec1(b * sin(currAngle), 0, a * cos(currAngle));
	vec1 = localToWold * vec1;
	osg::Vec3 normal1(sin(currAngle) / b, 0, cos(currAngle) / a);
	normal1 = localToWold * normal1;
	normal1.normalize();

	currAngle -= vIncAng;
	osg::Vec3 vec2(b * sin(currAngle), 0, a * cos(currAngle));
	vec2 = localToWold * vec2;
	osg::Vec3 normal2(sin(currAngle) / b, 0, cos(currAngle) / a);
	normal2 = localToWold * normal2;
	normal2.normalize();

	const GLint first = vertexArr->size();
	for (int i = 0; i < vCount / 2; ++i)
	{
		osg::Vec3 hVec1 = vec1;
		osg::Vec3 hVec2 = vec2;
		osg::Vec3 hNormal1 = normal1;
		osg::Vec3 hNormal2 = normal2;
		const size_t hFirst = vertexArr->size();
		for (int j = 0; j < hCount; ++j)
		{
			vertexArr->push_back(m_center + hVec1);
			vertexArr->push_back(m_center + hVec2);
			normalArr->push_back(hNormal1);
			normalArr->push_back(hNormal2);

			hVec1 = hQuat * hVec1;
			hVec2 = hQuat * hVec2;

			hNormal1 = hQuat * hNormal1;
			hNormal2 = hQuat * hNormal2;
		}
		vertexArr->push_back((*vertexArr)[hFirst]);
		vertexArr->push_back((*vertexArr)[hFirst + 1]);
		normalArr->push_back((*normalArr)[hFirst]);
		normalArr->push_back((*normalArr)[hFirst + 1]);

		vec1 = vec2;
		currAngle -= vIncAng;
		vec2.set(b * sin(currAngle), 0, a * cos(currAngle));
		vec2 = localToWold * vec2;

		normal1 = normal2;
		normal2.set(sin(currAngle) / b, 0, cos(currAngle) / a);
		normal2 = localToWold * normal2;
		normal2.normalize();
	}
	addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP, first, vertexArr->size() - first));

	if (!isFull && m_bottomVis)
	{
		const GLint first = vertexArr->size();
		currAngle = m_angle / 2.0;
		osg::Vec3 vec1(b * sin(currAngle), 0, a * cos(currAngle));
		vec1 = localToWold * vec1;
		osg::Vec3 vec2(0, 0, a * cos(currAngle));
		vec2 = localToWold * vec2;

		vertexArr->push_back(m_center + vec2);
		normalArr->push_back(bottomNormal);
		for (int i = 0; i < hCount; ++i)
		{
			vertexArr->push_back(m_center + vec1);
			normalArr->push_back(bottomNormal);
			vec1 = hQuat * vec1;
		}
		vertexArr->push_back((*vertexArr)[first + 1]);
		normalArr->push_back(bottomNormal);
		addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_FAN, first, vertexArr->size() - first));
	}
}
예제 #12
0
void SCylinder::subDraw()
{
    getPrimitiveSetList().clear();
    osg::ref_ptr<osg::Vec3Array> vertexArr = new osg::Vec3Array;
    osg::ref_ptr<osg::Vec3Array> normalArr = new osg::Vec3Array;
    setVertexArray(vertexArr);
    setNormalArray(normalArr, osg::Array::BIND_PER_VERTEX);
    osg::ref_ptr<osg::Vec4Array> colArr = new osg::Vec4Array();
    colArr->push_back(m_color);
    setColorArray(colArr, osg::Array::BIND_OVERALL);

    int count = (int)getDivision();
    double incAng = 2 * M_PI / count;
    osg::Vec3 topNormal = m_height;
    topNormal.normalize();
    double angleCos = m_bottomNormal * (-topNormal) / m_bottomNormal.length() / topNormal.length();
    double angle = acos(angleCos);
    double a = m_radius;
    double b = m_radius / sin(M_PI_2 - angle);
    osg::Vec3 vec = m_bottomNormal ^ topNormal;
    vec.normalize();
    osg::Quat bottomQuat(incAng, m_bottomNormal);
    double currAngle = 0;
    osg::Quat localToWorldQuat;
    localToWorldQuat.makeRotate(osg::Z_AXIS, m_bottomNormal);
    osg::Vec3 yAxis = localToWorldQuat * osg::Y_AXIS;
    osg::Quat localToWorldQuat2;
    localToWorldQuat2.makeRotate(yAxis, vec);
    localToWorldQuat *= localToWorldQuat2;
    osg::Vec3 bottomVec(b * sin(currAngle), a * cos(currAngle), 0);
    bottomVec = localToWorldQuat * bottomVec;
    //bottomVec = localToWorldQuat2 * bottomVec;

    osg::Quat topQuat(incAng, topNormal);
    osg::Vec3 topVec = vec * m_radius;
    osg::Vec3 topCenter = m_org + m_height;
    size_t first = vertexArr->size();
    for (int i = 0; i < count; ++i)
    {
        vertexArr->push_back(topCenter + topVec);
        vertexArr->push_back(m_org + bottomVec);
        normalArr->push_back(topVec);
        normalArr->back().normalize();
        normalArr->push_back(normalArr->back());

        currAngle += incAng;
        bottomVec.set(b * sin(currAngle), a * cos(currAngle), 0);
        bottomVec = localToWorldQuat * bottomVec;
        //bottomVec = localToWorldQuat2 * bottomVec;
        topVec = topQuat * topVec;
    }
    vertexArr->push_back((*vertexArr)[first]);
    vertexArr->push_back((*vertexArr)[first + 1]);
    normalArr->push_back((*normalArr)[first]);
    normalArr->push_back((*normalArr)[first + 1]);
    addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_STRIP, first, vertexArr->size() - first));

    if (m_bottomVis)
    {
        first = vertexArr->size();
        vertexArr->push_back(m_org);
        normalArr->push_back(m_bottomNormal);
        for (int i = count; i >= 0; --i)
        {
            vertexArr->push_back((*vertexArr)[i * 2 + 1]);
            normalArr->push_back(m_bottomNormal);
        }
        addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_FAN, first, vertexArr->size() - first));
    }

    if (m_topVis)
    {
        first = vertexArr->size();
        vertexArr->push_back(topCenter);
        normalArr->push_back(topNormal);
        for (int i = 0; i < count + 1; ++i)
        {
            vertexArr->push_back((*vertexArr)[i * 2]);
            normalArr->push_back(topNormal);
        }
        addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_FAN, first, vertexArr->size() - first));
    }
}
예제 #13
0
void SuperShape3D::generate(void)
{
    const float lon_step =  2 * osg::PI / _resolution;
    const float lat_step =  osg::PI / _resolution;
    const float epsilon = std::numeric_limits<float>::epsilon();

    osg::Vec3Array* vAry = new osg::Vec3Array;
    vAry->reserve( _resolution * _resolution * 6 );
    setVertexArray( vAry );

    osg::Vec4Array* cAry = new osg::Vec4Array;
    setColorArray( cAry );
    setColorBinding( osg::Geometry::BIND_OVERALL );
    cAry->push_back( osg::Vec4(1,1,1,1) );

    for( int lat_count = 0; lat_count <_resolution; ++lat_count )
    {
        float phi1 = static_cast<float>(lat_count * lat_step - osg::PI_2);
        float phi2 = phi1 + lat_step;

        for( int lon_count = 0; lon_count < _resolution; ++lon_count )
        {
            float theta1 = static_cast<float>(lon_count * lon_step - osg::PI);
            float theta2 = theta1 + lon_step;

            bool tooSmall = false;

            float r1_1 = SS1(theta1);
            if(fabs(r1_1) < epsilon) tooSmall = true;

            float r2_1 = SS2(phi1);
            if(fabs(r2_1) < epsilon) tooSmall = true;

            float r1_2 = SS1(theta2);
            if(fabs(r1_2) < epsilon) tooSmall = true;

            float r2_2 = SS2(phi2);
            if(fabs(r2_2) < epsilon) tooSmall = true;

            if( !tooSmall )
            {
                r1_1 = 1.0f / r1_1;
                r1_2 = 1.0f / r1_2;
                r2_1 = 1.0f / r2_1;
                r2_2 = 1.0f / r2_2;

                osg::Vec3 pa = osg::Vec3(r1_1*cosf(theta1)*r2_1*cosf(phi1), r1_1*sinf(theta1)*r2_1*cosf(phi1), r2_1*sinf(phi1));
                osg::Vec3 pb = osg::Vec3(r1_2*cosf(theta2)*r2_1*cosf(phi1), r1_2*sinf(theta2)*r2_1*cosf(phi1), r2_1*sinf(phi1));
                osg::Vec3 pc = osg::Vec3(r1_2*cosf(theta2)*r2_2*cosf(phi2), r1_2*sinf(theta2)*r2_2*cosf(phi2), r2_2*sinf(phi2));
                osg::Vec3 pd = osg::Vec3(r1_1*cosf(theta1)*r2_2*cosf(phi2), r1_1*sinf(theta1)*r2_2*cosf(phi2), r2_2*sinf(phi2));

                if((pa - pb).length() > epsilon && (pa - pc).length() > epsilon)
                {
                    vAry->push_back( pa );
                    vAry->push_back( pb );
                    vAry->push_back( pc );
                }

                if((pc - pd).length() > epsilon && (pc - pa).length() > epsilon)
                {
                    vAry->push_back( pc );
                    vAry->push_back( pd );
                    vAry->push_back( pa );
                }
            }
        }
    }

    addPrimitiveSet( new osg::DrawArrays( GL_TRIANGLES, 0, vAry->size() ) );
    FacetingVisitor::facet( *this );
}
예제 #14
0
chaos::GameObject::GameObject(chaos::Renderer* ren, std::string vaoId, std::string shaderId)
:renderer(ren), material(glm::vec4(1, 0.1, 0.4, 1.0), glm::vec4(0,1,0,1), 32)
{
    setVertexArray(vaoId);
    setShader(shaderId);
}
예제 #15
0
int loadObj(const char *filename, OBJ *obj){

    /* buffers for data */
    GLfloat **normalBuffer, **textureBuffer, **vertexBuffer = NULL;

    /* texture and normal index buffers */
    GLint *indexBuffer, *normalIndexBuffer, *textureIndexBuffer = NULL;

    /* counters */
    GLint index = 0;
    GLint texture = 0;
    GLint normal = 0;
    GLint vertex = 0;

    /* record size required for index and vertex buffers */
     GLint indexSize = 0;
     GLint normalSize = 0;
     GLint textureSize = 0;
     GLint vertexSize = 0;

    /* 1. open and get sizes required for index and vertex arrays texture and normal sizes
     can be calculated easily from these when required
    */

    char *textHeaderLine;
    int headerLineCount = 0;
    char line[64];

    /* 1. loading file */

    FILE *file;
    if((file = fopen(filename, "r")) != NULL){

         while(fgets(line,64,file)!= NULL){


            if(line[0] == 'v'){

                /* vertex */
                if(line[1] == ' '){   vertexSize++;   }

                /* normals */
                if(line[1] == 'n'){   normalSize++;   }

                /* texture */
                if(line[1] == 't'){   textureSize++;   }
            }

			/* faces - three triangles are refereced per line */
            if(line[0] == 'f' && line[1] == ' '){   indexSize += 3;   }

         }

    }else{
        fprintf(stderr, "Error: Unable to read file %s", filename);
        exit(0);
    }

    if(indexSize == 0 || vertexSize == 0){
        fprintf(stderr, "Error: There are no indices or vertices in %s!", filename);
        exit(0);
    }

    /* ALLOCATE MEMORY FOR LOCAL ARRAY BUFFERS */

    if(normalSize > 0){

            normalBuffer = (GLfloat **)malloc(sizeof(GLfloat *) * normalSize);

            int i = 0;
            for(i = 0; i < normalSize; i++){
                normalBuffer[i] = (GLfloat *)malloc(sizeof(GLfloat) * 3);
                if(i == normalSize - 1){
                    printf("Normal Buffer allocated! %d\n", normalSize);
                }
            }

            normalIndexBuffer = (GLint *)malloc(indexSize * sizeof(GLint));
    }

    if(textureSize > 0){

            textureBuffer = (GLfloat **)malloc(sizeof(GLfloat *) * textureSize);

            int t = 0;
            for(t = 0; t < textureSize; t++){
                textureBuffer[t] = (GLfloat *)malloc(sizeof(GLfloat) * 2);
                if(t == textureSize - 1){
                    printf("Texture Buffer allocated! %d\n", textureSize);
                }
            }

            textureIndexBuffer = (GLint *)malloc(indexSize * sizeof(GLint));
    }

    //these should always be present - mandatory

    if(vertexSize > 0 && indexSize > 0){

            vertexBuffer = (GLfloat **)malloc(sizeof(GLfloat *) * vertexSize);

            int v = 0;
            for(v = 0; v < vertexSize; v++){
                vertexBuffer[v] = (GLfloat *)malloc(sizeof(GLfloat) * 3);
                if(v == (vertexSize - 1)){
                    printf("Vertex Buffer allocated! %d\n", vertexSize);
                }
            }

            if(indexSize > 0){
                printf("indexSize %d\n", indexSize * sizeof(GLint));
                indexBuffer = (GLint *)malloc(indexSize * sizeof(GLint));
            }else{
                fprintf(stderr,"File does not appear to have any indices!\n");
                exit(0);
            }
    }else{
    	fprintf(stderr,"File does not appear to have any vertices!\n");
    	//printf("vertexSize %d\n", vertexSize);
    	exit(0);
    }



    /* 2. now open and read data */

    rewind(file);

    while(fgets(line,64,file)!= NULL){

            // NULL if char not found
            if((textHeaderLine = strchr(line, '#')) != NULL){
                printf("Header Line: %s\n", textHeaderLine);
                headerLineCount++;
            }

            if(line[0] == 'v' && line[1] == ' '){

                //knock the first char out so we can use sscanf
                line[0] = ' ';

                float v[3];
                sscanf(line," %f %f %f", &v[0], &v[1], &v[2]);

                vertexBuffer[vertex][0] = v[0];
                vertexBuffer[vertex][1] = v[1];
                vertexBuffer[vertex][2] = v[2];

                #if OBJ_DEBUG == 1
                    printf("vertex buffer: %f %f %f\n", vertexBuffer[vertex][0],vertexBuffer[vertex][1],vertexBuffer[vertex][2]);
                #endif

                vertex++;
            }

            /* normals */

            if(line[0] == 'v' && line[1] == 'n'){

                //knock the first char out so we can use sscanf
                line[0] = ' ';
                line[1] = ' ';

                float v[3];
                sscanf(line, "%f %f %f", &v[0], &v[1], &v[2]);

                normalBuffer[normal][0] = v[0];
                normalBuffer[normal][1] = v[1];
                normalBuffer[normal][2] = v[2];

                 #if OBJ_DEBUG == 1
                    printf("normal buffer: %f %f %f\n", normalBuffer[normal][0],normalBuffer[normal][1],normalBuffer[normal][2]);
                #endif

                normal++;
            }

	   // texture coords

	    if(line[0] == 'v' && line[1] == 't'){

                //knock the first char out so we can use sscanf
                line[0] = ' ';
                line[1] = ' ';

                float t[2];
                sscanf(line, "%f %f", &t[0], &t[1]);

                textureBuffer[texture][0] = t[0];
                textureBuffer[texture][1] = t[1];

                texture++;
            }

            /* faces  eg. f 3/3/13 7/7/25 5/5/19 1/1/7

                1st index - vertex
                2nd normal
                3rd texture coord

                Blender: 3 nums instead??
                - no texture or normals by default
            */

            if(line[0] == 'f' && line[1] == ' '){

                line[0] = ' ';

                /* only vertices and indices so each line is going to 3 indices only */

                if(textureSize == 0 && normalSize == 0){

                    int f[3];
                    sscanf(line, "%d %d %d",&f[0], &f[1], &f[2]);
                    //printf("%d %d %d\n", f[0], f[1], f[2]);
                    indexBuffer[index + 0] = --f[0];
                    indexBuffer[index + 1] = --f[1];
                    indexBuffer[index + 2] = --f[2];

                    index += 3;
                }

                /* normals but NO texture */

                if(textureSize == 0 && normalSize > 0){

                    int f[7];
                    sscanf(line, "%d//%d %d//%d %d//%d",&f[0], &f[1], &f[2], &f[3], &f[4], &f[5]);

                    indexBuffer[index + 0] = --f[0];
                    indexBuffer[index + 1] = --f[2];
                    indexBuffer[index + 2] = --f[4];

                    normalIndexBuffer[index + 0] = --f[1];
                    normalIndexBuffer[index + 1] = --f[3];
                    normalIndexBuffer[index + 2] = --f[5];

                 #if OBJ_DEBUG == 1
                    printf("index: %d %d %d\n", indexBuffer[index + 0],indexBuffer[index + 1],indexBuffer[index + 2]);
                 #endif

                 #if OBJ_DEBUG == 1
                    printf("index: %d %d %d\n", normalIndexBuffer[index + 0], normalIndexBuffer[index + 1], normalIndexBuffer[index + 2]);
                 #endif

                    index += 3;
                }

                /* find evidence for this one - format from logic alone */
/*
                if(textureSize > 0 && normalSize == 0){

                    int f[7];
                    sscanf(line, "%d/%d %d/%d %d/%d",&f[0], &f[1], &f[2], &f[3], &f[4], &f[5]);
                    indexBuffer[index + 0] = --f[0];
                    indexBuffer[index + 1] = --f[1];
                    indexBuffer[index + 2] = --f[2];

                    index += 3;

                }

                if(textureSize > 0 && normalSize > 0){

                    int f[9];
                    printf("here");
                    sscanf(line, "%d/%d/%d %d/%d/%d %d/%d/%d",&f[0], &f[1], &f[2], &f[3], &f[4], &f[5], &f[6], &f[7], &f[8]);

                    indexBuffer[index + 0] = --f[0];
                    indexBuffer[index + 1] = --f[3];
                    indexBuffer[index + 2] = --f[6];

                    textureIndexBuffer[index + 0] = --f[1];
					textureIndexBuffer[index + 1] = --f[4];
					textureIndexBuffer[index + 2] = --f[7];

                    normalIndexBuffer[index + 0] = --f[2];
					normalIndexBuffer[index + 1] = --f[5];
					normalIndexBuffer[index + 2] = --f[8];

                    //printf("%d %d %d\n", textureIndexBuffer[index + 0],textureIndexBuffer[index + 1],textureIndexBuffer[index + 2]);
                    index += 3;
                }
*/
            }

    }


    /* set index and vertex to struct */

    setIndexArray(indexSize, indexBuffer, obj);
    setVertexArray(indexSize, vertexBuffer, obj);

    /* free index buffer as this is now in obj struct */
/*
    if(indexBuffer){
        while(i < indexSize * 3){
            free(indexBuffer[i]);
            i++;
        }
       // free(indexBuffer);
        indexBuffer = NULL;
    }
*/


    /* free vertex buffer as this is now in obj struct */
/*
    if(vertexBuffer){
        while(i < vertexSize){
            free(vertexBuffer[i]);
            i++;
        }
     //   free(vertexBuffer);
        vertexBuffer = NULL;
    }
*/
/*
    if(normalSize > 0){

        setNormalIndexArray(indexSize, normalIndexBuffer, obj);

        if(normalIndexBuffer){
            free(normalIndexBuffer);
            normalIndexBuffer = NULL;
        }

        setNormalArray(indexSize, normalBuffer, obj);

        if(vertexBuffer){
            free(normalBuffer);
            normalBuffer = NULL;
        }
*/


    /* only set if we have values to set */
/*
    if(textureSize > 0){
        setTextureArray((textureSize * 2), textureIndexBuffer, &textureBuffer, obj);

        free(textureIndexBuffer);

        int t = 0;
        while(t < textureSize){
            free(textureBuffer[t]);
            t++;
        }
        free(textureBuffer);

    }
*/
    fclose(file);
    return 0;
}
예제 #16
0
//------------------------------------------------------------------------------
void HudBar::updateVb()
{
    // Recreate buffers to reflect new size
    osg::Vec3Array * vertex = new osg::Vec3Array(4); // vec3 or computeBounds will complain
    setVertexArray(vertex);

    osg::Vec2Array* texcoord = new osg::Vec2Array(4);
    setTexCoordArray(0,texcoord);

    Vector2d pos;
    float size;
    getPositionAndSize(pos, size);

    switch (fill_direction_)
    {
    case HBFD_LEFT_RIGHT:
        (*vertex)[0].set(pos.x_,                              pos.y_,      0.0f);
        (*vertex)[1].set(pos.x_+size*aspect_ratio_*value_,    pos.y_,      0.0f);
        (*vertex)[2].set(pos.x_+size*aspect_ratio_*value_,    pos.y_+size, 0.0f);
        (*vertex)[3].set(pos.x_,                              pos.y_+size, 0.0f);

        (*texcoord)[0].set(0,0);
        (*texcoord)[1].set(value_,0);
        (*texcoord)[2].set(value_,1);
        (*texcoord)[3].set(0,1);
        break;
    case HBFD_RIGHT_LEFT:
        (*vertex)[0].set(pos.x_+size*aspect_ratio_*(1.0f-value_),    pos.y_,      0.0f);
        (*vertex)[1].set(pos.x_+size*aspect_ratio_,           pos.y_,      0.0f);
        (*vertex)[2].set(pos.x_+size*aspect_ratio_,           pos.y_+size, 0.0f);
        (*vertex)[3].set(pos.x_+size*aspect_ratio_*(1.0f-value_),    pos.y_+size, 0.0f);

        (*texcoord)[0].set(1-value_,        0);
        (*texcoord)[1].set(1, 0);
        (*texcoord)[2].set(1, 1);
        (*texcoord)[3].set(1-value_,        1);
        break;
    case HBFD_TOP_DOWN:
        (*vertex)[0].set(pos.x_,                    pos.y_+size*(1.0f-value_), 0.0f);
        (*vertex)[1].set(pos.x_+size*aspect_ratio_, pos.y_+size*(1.0f-value_), 0.0f);
        (*vertex)[2].set(pos.x_+size*aspect_ratio_, pos.y_+size, 0.0f);
        (*vertex)[3].set(pos.x_,                    pos.y_+size, 0.0f);

        (*texcoord)[0].set(0,1-value_);
        (*texcoord)[1].set(1,1-value_);
        (*texcoord)[2].set(1,1);
        (*texcoord)[3].set(0,1);
        break;
    case HBFD_BOTTOM_UP:
        (*vertex)[0].set(pos.x_,                    pos.y_,             0.0f);
        (*vertex)[1].set(pos.x_+size*aspect_ratio_, pos.y_,             0.0f);
        (*vertex)[2].set(pos.x_+size*aspect_ratio_, pos.y_+size*value_, 0.0f);
        (*vertex)[3].set(pos.x_,                    pos.y_+size*value_, 0.0f);

        (*texcoord)[0].set(0,0);
        (*texcoord)[1].set(1,0);
        (*texcoord)[2].set(1,value_);
        (*texcoord)[3].set(0,value_);
        break;
    }
}
예제 #17
0
void LaserScanLine::updateVertices()
{
    UrgToOsg::getOsg2DPoints(&urg, vertices);
    setVertexArray(vertices);
}
예제 #18
0
파일: Polyhedra.cpp 프로젝트: mew-cx/osgtoy
osgToy::Polyhedron::Polyhedron()
{
    setVertexArray( new osg::Vec3Array );
    setNormalArray( new osg::Vec3Array );
    setColorArray(  new osg::Vec4Array );
}