void myApp02::init() {

	globalAmbient = Col3f(1, .1, .1);
	shadowsOn();
	// wall
	plane = GroundPlane(Vec3(), Vec3(), Dim2f(8, 7), Col4f(1, 1, 0, 1), 1, 1, "orange.jpg");
	//Plane.textureOn();
	plane.setBumpMap("white_tile.jpg");
	plane.setTextureScale(Vec2f(.5));
	//Plane.setAmbientMaterial(Col4f(.02, .02, .02, 1.0));
	plane.setSpecularMaterial(Col4f(.1, .1, .1, 1.0));
	plane.setShininess(100);


	//tube = ProtoTube();

	float radius = .107;
	Vec3f v(0, 0, 0);

	int segments = 5; // 60;
	v = Vec3f(0, 0, 0);
	Vec3f spd(0, 0, 0);

	//cps.push_back(v);
	float turbulence = .1f;
	Dim3f size(4.25, 4.25, 4.25);


	float startY = -.5;

	int ribCount = 13;// 17;
	float ribSpan = 4.5;
	float ribRadius = 0;
	float ribRadiusMax = 2.0;
	float ribTheta = 0;

	float ribGap = ribSpan / ribCount;

	for (int i = 0; i < ribCount; ++i){

		float theta = 0, weaveTheta = 0;
		std::vector <Vec3> cps;
		Spline3 spline;
		ribRadius = fabs(sin(ribTheta) * ribRadiusMax);
		for (int j = 0; j < segments; ++j){
			//spd = Vec3(random(-turbulence*.1, turbulence*.1), 0, random(-turbulence*.1, turbulence*.1));
			//v = spd + Vec3f(sin(theta)*2+random(-turbulence, turbulence), startY+=.1, cos(theta)*2+random(-turbulence, turbulence));
			//cps.push_back(Vec3(v.x, v.y, v.z));
			cps.push_back(Vec3(sin(theta) * ribRadius, -ribSpan / 2 + ribGap*i + sin(weaveTheta) * .15, cos(theta) * ribRadius));
			theta += TWO_PI / segments;
			//weaveTheta += j*j*j*.125 * PI / 180;
			weaveTheta += TWO_PI / segments * (ribRadius * 4);
		}
		//trace("ribradius = ", ribRadius*4);
		ribTheta += PI / ribCount;

		//spline = Spline3(cps, 4, false, .5);
		spline = Spline3(cps, 5, false, .5);

		TransformFunction t1 = TransformFunction(TransformFunction::SINUSOIDAL, Tup2f(.02, .95 + (ribRadius*random(.07, .31))), 1/*int(random(1, 3))*/);

		ribs.push_back(ProtoTube(Vec3f(), Vec3f(), Dim3f(1), Col4f(1), spline, .09, 12, t1, true, "pitted.jpg", Vec2f(1, random(.0825, .2))));
		ribs.at(i).setIsClosed(0);
		ribs.at(i).setSpecularMaterial(Col4f(.4, .275, .1, 1));
		ribs.at(i).setShininess(6);
		ribs.at(i).setBumpMap("pitted.jpg");

		// rib tendrils
		std::vector <Vec3> ribCps;
		for (int j = 0; j < ribs.at(i).getFrenetFrameLength(); j += int(random(1, 3))){
			for (int k = 0; k < ribs.at(i).getCrossSectionDetail(); k += int(random(1, 3))){
				ribCps.push_back(ribs.at(i).getVertices().at(j*ribs.at(i).getCrossSectionDetail() + k).pos);
			}
		}

		Spline3 ribSpline = Spline3(ribCps, 3, false, .5);
		TransformFunction ribT = TransformFunction(TransformFunction::SINUSOIDAL, Tup2f(random(.05, .1), random(.1, .2)), int(random(1, 12)));
		ribBands.push_back(ProtoTube(Vec3f(), Vec3f(), Dim3f(1), Col4f(1), ribSpline, .09, 12, ribT, true, "vascular.jpg", Vec2f(1, random(.0825, .2))));
		ribBands.at(i).setIsClosed(0);
		ribBands.at(i).setSpecularMaterial(Col4f(.4, .275, .1, 1));
		ribBands.at(i).setShininess(6);
		ribBands.at(i).setBumpMap("vascular.jpg");
	}

	
	//yRot = xRot = 0;
	//xRotLast = yRotLast = 0;
	//mouseXIn = mouseYIn = 0;

}
Пример #2
0
void Oscillator::update()
{
    angle += velocity;
    display = Vec2f( sin( angle.x ) * amplitude.x, sin( angle.y ) * amplitude.y );
}
void StelQGLRenderer::drawText(const TextParams& params)
{
	statistics[TEXT_DRAWS] += 1.0;
	StelQGLTextureBackend* currentTexture = currentlyBoundTextures[0];

	if(params.string_.length() == 0)
	{
		return;
	}

	viewport.enablePainting();
	if(currentFontSet)
	{
		viewport.setFont(currentFont);
	}
	QPainter* painter = viewport.getPainter();
	Q_ASSERT_X(NULL != painter, Q_FUNC_INFO, 
	           "Trying to draw text but painting is disabled");

	QFontMetrics fontMetrics = painter->fontMetrics();

	StelProjectorP projector = NULL == params.projector_
	                         ? StelApp::getInstance().getCore()->getProjection2d() 
	                         : params.projector_;
	Vec3f win;
	if(params.doNotProject_) 
	{
		win = params.position_;
	}
	else if(!projector->project(params.position_, win))
	{
		viewport.disablePainting();
		return;
	}

	const int x = win[0];
	const int y = win[1];

	// Avoid drawing if outside viewport.
	// We do a worst-case approximation as getting exact text dimensions is expensive.
	// We also account for rotation by assuming the worst case in bot X and Y 
	// (culling with a rotating rectangle would be expensive)
	const int cullDistance = 
		std::max(fontMetrics.height(), params.string_.size() * fontMetrics.maxWidth());
	const Vec4i viewXywh = projector->getViewportXywh();
	const int viewMinX = viewXywh[0];
	const int viewMinY = viewXywh[1];
	const int viewMaxX = viewMinX + viewXywh[2];
	const int viewMaxY = viewMinY + viewXywh[3];

	if(y + cullDistance < viewMinY || y - cullDistance > viewMaxY ||
	   x + cullDistance < viewMinX || x - cullDistance > viewMaxX)
	{
		viewport.disablePainting();
		return;
	}

	if(projector->useGravityLabels() && !params.noGravity_)
	{
		drawTextGravityHelper(params, *painter, x, y, projector);
		return;
	}
	
	const int pixelSize   = painter->font().pixelSize();
	// Strings drawn by drawText() can differ by text, font size, or the font itself.
	const QByteArray hash = params.string_.toUtf8() + QByteArray::number(pixelSize) + 
	                        painter->font().family().toUtf8();
	StelQGLTextureBackend* textTexture = textTextureCache.object(hash);

	// No texture in cache for this string, need to draw it.
	if (NULL == textTexture) 
	{
		const QRect extents = fontMetrics.boundingRect(params.string_);

		// Width and height of the text. 
		// Texture width/height is required to be at least equal to this.
		//
		// Both X and Y need to be at least 1 so we don't create an empty image 
		// (doesn't work with textures)
		const int requiredWidth  = std::max(1, extents.width() + 1 + static_cast<int>(0.02f * extents.width()));
		const int requiredHeight = std::max(1, extents.height());
		// Create temporary image and render text into it

		// QImage is used solely to reuse existing QGLTextureBackend constructor 
		// function. QPixmap could be used as well (not sure which is faster, 
		// needs profiling)
		QImage image = areNonPowerOfTwoTexturesSupported() 
		             ? QImage(requiredWidth, requiredHeight, QImage::Format_ARGB32_Premultiplied) 
		             : QImage(StelUtils::smallestPowerOfTwoGreaterOrEqualTo(requiredWidth), 
		                      StelUtils::smallestPowerOfTwoGreaterOrEqualTo(requiredHeight),
		                      QImage::Format_ARGB32);
		image.fill(Qt::transparent);

		QPainter fontPainter(&image);
		fontPainter.setFont(painter->font());
		fontPainter.setRenderHints(QPainter::TextAntialiasing, true);
		fontPainter.setPen(Qt::white);

		// The second argument ensures the text is positioned correctly even if 
		// the image is enlarged to power-of-two.
		fontPainter.drawText(-extents.x(), 
		                     image.height() - requiredHeight - extents.y(), 
		                     params.string_);

		textTexture = StelQGLTextureBackend::constructFromImage
			(this, QString(), TextureParams().filtering(TextureFiltering_Linear), image);
		const QSize size = textTexture->getDimensions();
		if(!textTexture->getStatus() == TextureStatus_Loaded)
		{
			qWarning() << "Texture error: " << textTexture->getErrorMessage();
			Q_ASSERT_X(false, Q_FUNC_INFO, "Failed to construct a text texture");
		}
		textTextureCache.insert(hash, textTexture, 4 * size.width() * size.height());
	}

	// Even if NPOT textures are not supported, we always draw the full rectangle 
	// of the texture. The extra space is fully transparent, so it's not an issue.

	// Shortcut variables to calculate the rectangle.
	const QSize size   = textTexture->getDimensions();
	const float w      = size.width();
	const float h      = size.height();
	const float xShift = params.xShift_;
	const float yShift = params.yShift_;

	const float angleDegrees = 
		params.angleDegrees_ + 
		(params.noGravity_ ? 0.0f : projector->getDefaultAngleForGravityText());
	// Zero out very small angles.
	// 
	// (this could also be used to optimize the case with zero angled
	//  to avoid sin/cos if needed)
	const bool  angled = std::fabs(angleDegrees) >= 1.0f * M_PI / 180.f;
	const float cosr   = angled  ? std::cos(angleDegrees * M_PI / 180.0) : 1.0f;
	const float sinr   = angled  ? std::sin(angleDegrees * M_PI / 180.0) : 0.0f;

	// Corners of the (possibly rotated) texture rectangle.
	const Vec2f ne(round(x + cosr * xShift       - sinr * yShift),
	               round(y + sinr * xShift       + cosr * yShift));
	const Vec2f nw(round(x + cosr * (w + xShift) - sinr * yShift),
	               round(y + sinr * (w + xShift) + cosr * yShift));
	const Vec2f se(round(x + cosr * xShift       - sinr * (h + yShift)),
	               round(y + sinr * xShift       + cosr * (h + yShift)));
	const Vec2f sw(round(x + cosr * (w + xShift) - sinr * (h + yShift)),
	               round(y + sinr * (w + xShift) + cosr * (h + yShift)));

	// Construct the text vertex buffer if it doesn't exist yet, otherwise clear it.
	if(NULL == textBuffer)
	{
		textBuffer = createVertexBuffer<TexturedVertex>(PrimitiveType_TriangleStrip);
	}
	else
	{
		textBuffer->unlock();
		textBuffer->clear();
	}

	textBuffer->addVertex(TexturedVertex(ne, Vec2f(0.0f, 0.0f)));
	textBuffer->addVertex(TexturedVertex(nw, Vec2f(1.0f, 0.0f)));
	textBuffer->addVertex(TexturedVertex(se, Vec2f(0.0f, 1.0f)));
	textBuffer->addVertex(TexturedVertex(sw, Vec2f(1.0f, 1.0f)));
	textBuffer->lock();

	// Draw.
	const BlendMode oldBlendMode = blendMode;
	setBlendMode(BlendMode_Alpha);
	textTexture->bind(0);
	drawVertexBuffer(textBuffer);
	setBlendMode(oldBlendMode);

	// Reset user-bound texture.
	if(NULL != currentTexture)
	{
		currentTexture->bind(0);
	}
	viewport.disablePainting();
}
Пример #4
0
void LoadLevelScreen(long num) {
	
	// resets status
	if(num < -1) {
		delete tc, tc = NULL;
		lastloadednum = -1;
		lastnum = -1;
		PROGRESS_BAR_TOTAL = 0;
		return;
	}
	
	if(num == -1) {
		num = lastnum;
	}
	lastnum = num;
	
	if(num < 0) {
		return;
	}
	
	static u32 last_progress_bar_update = Time::getMs();
	
	// only update if time since last update to progress bar > 16ms
	// and progress bar's value has actually changed
	if (Time::getElapsedMs(last_progress_bar_update) > 16 &&
		 OLD_PROGRESS_BAR_COUNT != PROGRESS_BAR_COUNT)
	{
		GRenderer->GetTextureStage(0)->setMinFilter(TextureStage::FilterLinear);
		GRenderer->GetTextureStage(0)->setMagFilter(TextureStage::FilterLinear);

		float ratio = (PROGRESS_BAR_TOTAL > 0.f ? PROGRESS_BAR_COUNT / PROGRESS_BAR_TOTAL : 0); 

		ratio = glm::clamp(ratio, 0.f, 1.f);

		GRenderer->Clear(Renderer::ColorBuffer | Renderer::DepthBuffer);
		
		GRenderer->SetRenderState(Renderer::DepthTest, true);
		GRenderer->SetCulling(Renderer::CullNone);
		GRenderer->SetRenderState(Renderer::DepthWrite, true);
		GRenderer->SetRenderState(Renderer::Fog, false);
		GRenderer->SetRenderState(Renderer::AlphaBlending, false);
		
		if (num == 10) {
			pbar = TextureContainer::LoadUI("graph/interface/menus/load_full");
		} else {
			pbar = TextureContainer::LoadUI("graph/interface/menus/load_full_level");
		}
		
		nopbar = 1;
		
		if(num != lastloadednum) {
			delete tc, tc = NULL;
			lastloadednum = num;
			char temp[256];
			char tx[256];
			GetLevelNameByNum(num, tx);
			sprintf(temp, "graph/levels/level%s/loading", tx);
			tc = TextureContainer::LoadUI(temp, TextureContainer::NoColorKey);
		}
		
		float scale = minSizeRatio();
		
		if(tc) {
			GRenderer->SetRenderState(Renderer::ColorKey, false);
			
			Vec2f size = (num == 10) ? Vec2f(640, 480) : Vec2f(320, 390);
			size *= scale;
			EERIEDrawBitmap2(g_size.center().x - size.x * 0.5f, g_size.center().y - size.y * 0.5f,
												size.x, size.y, 0.001f, tc, Color::white);
			
			GRenderer->SetRenderState(Renderer::ColorKey, true);
		}
		
		if(pbar) {
			float px = g_size.center().x - 100 * scale;
			float py = g_size.center().y + ((num == 10) ? 221 : 35) * scale;
			float px2 = ratio * 200 * scale;
			float py2 = 8 * scale;
			EERIEDrawBitmap_uv(px, py, px2, py2, 0.f, pbar, Color::white, 0.f, 0.f, ratio, 1.f);
		}
		
		mainApp->getWindow()->showFrame();
		
		OLD_PROGRESS_BAR_COUNT = PROGRESS_BAR_COUNT;
		last_progress_bar_update = Time::getMs();
	}
}
Пример #5
0
Vec2f JitteredSampler::getSamplePosition(int n) {
	// YOUR CODE HERE (R9)
	// Return a randomly generated sample through Nth subpixel.
	return Vec2f(0,0);
}
Пример #6
0
Vec2f GravityCalculation(Vec2f move)
{
  return Vec2f(move.x(), move.y() - GR);
}
Пример #7
0
Vec2f Component::getContentRequestedSize(void) const
{
    return Vec2f(0.0,0.0);
}
Пример #8
0
void Entity::setPos(float x, float y) {
    pos = Vec2f(x, y);
    body->SetTransform(b2Vec2(x, y), body->GetAngle());
}
Пример #9
0
void StateMap::setupLvDisplay() {
    // Create display element
    m_lvInfo = UIElement::create( "MapLevelInfo" );
    // Register the display in UI manager
    UI_MANAGER.addElement( m_lvInfo );

    const Vec2f displaySize  = Vec2f( 600, 380 );
    const Vec2i windowCenter = Game::getWindowCenter();

    // Set size and position
    m_lvInfo->setSize( displaySize );
    m_lvInfo->setCenter( windowCenter );

    // Hide the display by default
    m_lvInfo->setActive( false );
    m_lvInfo->setVisible( false );

    /** Sprites */
    {
        // Create sprite for display background
        Sprite* bgSprite = new Sprite();
        bgSprite->setName( "MapLevelInfoSprite" );
        bgSprite->setSprite( "window_map_levelinfo" );

        // Create sprite for level display
        Sprite* levelSprite = new Sprite();
        levelSprite->setName( "MapLevelInfoLevelSprite" );
        levelSprite->setScale( 0.25, 0.25 );
        levelSprite->setPos( 45, 92 );

        // Add sprites to the display
        m_lvInfo->addChild( bgSprite );
        m_lvInfo->addChild( levelSprite, 1 );
    }

    /** Level name */
    {
        Text* name = new Text();
        name->setName( "MapLevelName" );
        name->setFont( "" );
        name->setCharSize( 18 );
        name->setColor( sf::Color::Yellow );
        name->setAlign( Text::Align_Center );
        name->setPos( displaySize.x / 2, 20 );

        m_lvInfo->addChild( name, 1 );
    }

    /** Buttons */
    {
        const Vec2f buttonSize  = Vec2f( 130, 25 );
        const int   offset      = 20;

        UIButton* play = UIButton::create( "MapButtonPlay", "button_dev" );
        play->setSize( buttonSize );
        play->setPos( offset, displaySize.y - buttonSize.y - offset );
        play->setButtonCallback( UIButton::Clicked, DOS_FUNC_BIND_1( &StateMap::cbLevelPlay, this ) );

        UIButton* cancel = UIButton::create( "MapButtonCancel", "button_dev" );
        cancel->setSize( buttonSize );
        cancel->setPos(
                      displaySize.x - buttonSize.x - offset,
                      displaySize.y - buttonSize.y - offset
                    );
        cancel->setButtonCallback( UIButton::Clicked, DOS_FUNC_BIND_1( &StateMap::cbLevelCancel, this ) );

        m_lvInfo->addChild( play, 1 );
        m_lvInfo->addChild( cancel, 1 );
    }
}
Пример #10
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    /******************************************************

             Add MouseListeners and WindowListeners
             to the WindowEvent.

    ******************************************************/

    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseListener1 BasicListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindow->addMouseListener(&TheTutorialMouseListener);
    TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);
    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);

    // Make Torus Node (creates Torus in background of scene)
    NodeRefPtr TorusGeometryNode = makeTorus(90, 270, 16, 16);

    // Make Main Scene Node and add the Torus
    NodeRefPtr scene = OSG::Node::create();
    scene->setCore(OSG::Group::create());
    scene->addChild(TorusGeometryNode);

    // Create the Graphics
    GraphicsRefPtr TutorialGraphics = OSG::Graphics2D::create();

    // Initialize the LookAndFeelManager to enable default settings
    LookAndFeelManager::the()->getLookAndFeel()->init();


    LoadButton = Button::create();

    LoadButton->setMinSize(Vec2f(50, 25));
    LoadButton->setMaxSize(Vec2f(200, 100));
    LoadButton->setPreferredSize(Vec2f(100, 50));
    LoadButton->setToolTipText("Click to open a file browser window");
    LoadButton->setText("Load File");

    LoadButton->addActionListener(&BasicListener);

    SaveButton = Button::create();

    SaveButton->setMinSize(Vec2f(50, 25));
    SaveButton->setMaxSize(Vec2f(200, 100));
    SaveButton->setPreferredSize(Vec2f(100, 50));
    SaveButton->setToolTipText("Click to save the currently opened file");
    SaveButton->setText("Save File");

    SaveButton->addActionListener(&BasicListener);

    theTextEditor = TextEditor::create();
    theTextEditor->setPreferredSize(Vec2f(600,400));

    /*

    UIFontRefPtr _Font = UIFont::create();
    _Font->setFamily("SANS");
    _Font->setGap(3);
    _Font->setGlyphPixelSize(46);
    _Font->setSize(15);
    _Font->setTextureWidth(0);
    _Font->setStyle(TextFace::STYLE_PLAIN);

    ExampleTextDomArea->setPreferredSize(Vec2f(600, 400));
    ExampleTextDomArea->setWrapStyleWord(false);
    ExampleTextDomArea->setMinSize(Vec2f(600,400));
    ExampleTextDomArea->setFont(_Font);

    ExampleAdvancedTextDomArea = OSG::AdvancedTextDomArea::create();
    ExampleAdvancedTextDomArea->setPreferredSize(Vec2f(600,400));
    ExampleAdvancedTextDomArea->setMinSize(Vec2f(600,400));
    ExampleAdvancedTextDomArea->setGutterVisible(true);
    ExampleAdvancedTextDomArea->pushToChildren(ExampleTextDomArea);
    ExampleAdvancedTextDomArea->setLayout(LayoutRefPtr(OSG::FlowLayout::create()));
    ExampleAdvancedTextDomArea->setPreferredSize(Vec2f(600,400));
    ExampleAdvancedTextDomArea->setMinSize(Vec2f(600,400));

    ScrollPanelRefPtr TextAreaScrollPanel = ScrollPanel::create();
    TextAreaScrollPanel->setPreferredSize(Vec2f(600,400));
    TextAreaScrollPanel->setMinSize(Vec2f(600,400));
    TextAreaScrollPanel->setViewComponent(ExampleAdvancedTextDomArea);

    */

    ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create();
    MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));

    LayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();

    InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
    MainInternalWindow->pushToChildren(theTextEditor);
    MainInternalWindow->pushToChildren(LoadButton);
    MainInternalWindow->pushToChildren(SaveButton);
    MainInternalWindow->setLayout(MainInternalWindowLayout);
    MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
    MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
    MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.85f,0.85f));
    MainInternalWindow->setDrawTitlebar(true);
    MainInternalWindow->setResizable(false);


    /******************************************************

             The Drawing Surface is created the
             same as with previous Tutorials
             (however the MainInternalWindow is created
             in a function below).

    ******************************************************/

    UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
    TutorialDrawingSurface->setGraphics(TutorialGraphics);
    TutorialDrawingSurface->setEventProducer(TutorialWindow);

    TutorialDrawingSurface->openWindow(MainInternalWindow);

    /******************************************************

            Create the 3D UIRectangle.  This allows
            the DrawingSurface to be rotated relative
            to the screen, allowing a 3D aspect to
            the DrawingSurface.  The Surface
            can still be interacted with, so Buttons,
            Menus, etc. all will still function
            normally.

            -setPoint(Pnt3f): Determine the location
                of the UIRectangle in 3D space.  Keep
                in mind that (0,0,0) is located
                directly in the center of the sceen.
                (For our purposes it is the center
                of the tori.) The point is located
                on the lower left corner of the
                rectangle.
            -setWidth(float): Determine the Width
                of the UIRectangle.  This may
                physically appear different depending
                on where the UIRectangle is placed
                as above (due to it being located
                further away, etc).
            -setHeight(float): Determine the Height
                of the UIRectangle.  This may
                physically appear different depending
                on where the UIRectangle is placed
                as above (due to it being located
                further away, etc).
            -setDrawingSurface(DrawingSurface):
                Determine what DrawingSurface is
                drawn on the UIRectangle.  This
                will typically be the main
                DrawingSurface, however, multiple
                DrawingSurfaces can be used with
                multiple UIRectangles.


    ******************************************************/

    //Make A 3D Rectangle to draw the UI on
    UIRectangleRefPtr ExampleUIRectangle = UIRectangle::create();
    ExampleUIRectangle->setPoint(Pnt3f(-400,-400,200));
    ExampleUIRectangle->setWidth(800.0);
    ExampleUIRectangle->setHeight(800.0);
    ExampleUIRectangle->setDrawingSurface(TutorialDrawingSurface);

    /******************************************************

            Because the previous Tutorials used a
            Viewport to view the scene, which is
            no longer being used, the UIRectangle
            must be added to the scene for it to
            be displayed (identical to how the
            Torus is added).

            First, create a Node, and set its
            core to be the UIRectangle.  Then,
            add that to the scene Node which
            is created above.  This scene is
            then set as the Root for the view.
            It is possible to change this Root
            to be just the UIRectangle (as
            commented out below).

    ******************************************************/
    NodeRefPtr ExampleUIRectangleNode = OSG::Node::create();
    ExampleUIRectangleNode->setCore(ExampleUIRectangle);

    // Add the UIRectangle as a child to the scene
    scene->addChild(ExampleUIRectangleNode);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);
    mgr->setRoot(scene);
    //mgr->setRoot(ExampleUIRectangleNode);

    // Show the whole Scene
    mgr->showAll();


    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
                               WinSize,
                               "3DNotepad!!");

    //Enter main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

        // Create the SimpleSceneManager helper
        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        //Attach to events
        TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager));
        TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager));
        TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager));
        TutorialWindow->connectMouseWheelMoved(boost::bind(mouseWheelMoved, _1, &sceneManager));

        //Particle System Material
        PointChunkRefPtr PSPointChunk = PointChunk::create();
        PSPointChunk->setSize(5.0f);
        PSPointChunk->setSmooth(true);

        BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
        PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
        PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

        MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create();
        PSMaterialChunkChunk->setAmbient(Color4f(1.0f,1.0f,1.0f,1.0f));
        PSMaterialChunkChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
        PSMaterialChunkChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f));
        PSMaterialChunkChunk->setColorMaterial(GL_NONE);

        ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
        PSMaterial->addChunk(PSPointChunk);
        PSMaterial->addChunk(PSMaterialChunkChunk);
        PSMaterial->addChunk(PSBlendChunk);

        //Particle System
        ParticleSystemRefPtr ExampleParticleSystem = ParticleSystem::create();
        ExampleParticleSystem->addParticle(Pnt3f(0,25,0),
                                           Vec3f(0.0,0.0f,1.0f),
                                           Color4f(1.0,1.0,1.0,1.0), 
                                           Vec3f(1.0,1.0,1.0), 
                                           0.1, 
                                           Vec3f(0.0f,0.0f,0.0f), //Velocity
                                           Vec3f(0.0f,0.0f,0.0f)
                                          );
        ExampleParticleSystem->addParticle(Pnt3f(0,-25,0),
                                           Vec3f(0.0,0.0f,1.0f),
                                           Color4f(1.0,1.0,1.0,1.0), 
                                           Vec3f(1.0,1.0,1.0), 
                                           0.1, 
                                           Vec3f(0.0f,0.0f,0.0f), //Velocity
                                           Vec3f(0.0f,0.0f,0.0f)
                                          );
        ExampleParticleSystem->attachUpdateProducer(TutorialWindow);

        //Particle System Drawer (Point)
        PointParticleSystemDrawerRecPtr ExamplePointParticleSystemDrawer = PointParticleSystemDrawer::create();

        //Particle System Drawer (line)
        LineParticleSystemDrawerRecPtr ExampleLineParticleSystemDrawer = LineParticleSystemDrawer::create();
        ExampleLineParticleSystemDrawer->setLineDirectionSource(LineParticleSystemDrawer::DIRECTION_VELOCITY);
        ExampleLineParticleSystemDrawer->setLineLengthSource(LineParticleSystemDrawer::LENGTH_SIZE_X);
        ExampleLineParticleSystemDrawer->setLineLength(2.0f);
        ExampleLineParticleSystemDrawer->setEndPointFading(Vec2f(0.0f,1.0f));

        //Create a Rate Particle Generator
        RateParticleGeneratorRefPtr ExampleGenerator = RateParticleGenerator::create();

        //Attach the function objects to the Generator
        ExampleGenerator->setPositionDistribution(createPositionDistribution());
        ExampleGenerator->setLifespanDistribution(createLifespanDistribution());
        ExampleGenerator->setGenerationRate(200);

        UniformParticleAffectorRecPtr ExampleUniformAffector = UniformParticleAffector::create();
        ExampleUniformAffector->setMagnitude(20.0); // force which the field exerts on particles (negative = towards the air field's beacon location)
        NodeRefPtr UniformBeacon = Node::create();
        ExampleUniformAffector->setBeacon(UniformBeacon); // set to 'emulate' from (0,0,0)
        ExampleUniformAffector->setDirection(Vec3f(1.0,0.0,0.0)); // direction which field is exerted
        ExampleUniformAffector->setMaxDistance(-1.0); // particles affected regardless of distance from
        ExampleUniformAffector->setAttenuation(0.0); // strength of uniform field dimishes by dist^attenuation, in this case it is constant regardless of distance
        ExampleUniformAffector->setParticleMass(10.0);



        //Attach the Generator and Affector to the Particle System
        ExampleParticleSystem->pushToGenerators(ExampleGenerator);
        ExampleParticleSystem->pushToAffectors(ExampleUniformAffector);
        ExampleParticleSystem->setMaxParticles(500);


        //Particle System Node
        ParticleSystemCoreRecPtr ParticleNodeCore = ParticleSystemCore::create();
        ParticleNodeCore->setSystem(ExampleParticleSystem);
        ParticleNodeCore->setDrawer(ExamplePointParticleSystemDrawer);
        ParticleNodeCore->setMaterial(PSMaterial);

        NodeRefPtr ParticleNode = Node::create();
        ParticleNode->setCore(ParticleNodeCore);


        // Make Main Scene Node and add the Torus
        NodeRefPtr scene = Node::create();
        scene->setCore(Group::create());
        scene->addChild(ParticleNode);

        TutorialWindow->connectKeyTyped(boost::bind(keyTyped, _1,
                                                    &sceneManager,
                                                    ParticleNodeCore.get(),
                                                    ExamplePointParticleSystemDrawer.get(),
                                                    ExampleLineParticleSystemDrawer.get(),
                                                    ExampleUniformAffector.get()));

        sceneManager.setRoot(scene);

        //Create the Documentation
        SimpleScreenDoc TheSimpleScreenDoc(&sceneManager, TutorialWindow);

        // Show the whole Scene
        sceneManager.showAll();

        sceneManager.getCamera()->setFar(1000.0);

        //Open Window
        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "19UniformFieldParticleAffector");

        //Enter main Loop
        TutorialWindow->mainLoop();

    }
    osgExit();

    return 0;
}
SegmentDistribution1DBase::SegmentDistribution1DBase(void) :
    Inherited(),
    _sfSegment                (Vec2f(0.0,1.0))
{
}
Пример #13
0
/** Liang-Barsky polygon clip.  [see Foley & Van Damn 19.1.3] */
void SceneCuller::clipVisibleQuad(vector<Vec2f> &in) {
	const float min_x = 0.f, min_y = 0.f;
	const float max_x = World::getCurrWorld()->getMap()->getW() - 2.01f;
	const float max_y = World::getCurrWorld()->getMap()->getH() - 2.01f;

	vector<Vec2f> &out = visiblePoly;

	float	xIn, yIn, xOut, yOut;
	float	tOut1, tIn2, tOut2;
	float	tInX, tOutX, tInY, tOutY;
	float	deltaX, deltaY;
	
	out.clear();

	for (unsigned i=0; i < in.size() - 1; ++i) {
		deltaX = in[i+1].x - in[i].x;
		deltaY = in[i+1].y - in[i].y;
		
		// find paramater values for x,y 'entry' points
		if (deltaX > 0 || (deltaX == 0.f && in[i].x > max_x)) {
			xIn = min_x; xOut = max_x;
		} else {
			xIn = max_x; xOut = min_x;
		}
		if (deltaY > 0 || (deltaY == 0.f && in[i].y > max_y)) {
			yIn = min_y; yOut = max_y;
		} else {
			yIn = max_y; yOut = min_y;
		}

		// find parameter values for x,y 'exit' points
		if (deltaX) {
			tOutX = (xOut - in[i].x) / deltaX;
		} else if (in[i].x <= max_x && min_x <= in[i].x ) {
			tOutX = numeric_limits<float>::infinity();
		} else {
			tOutX = -numeric_limits<float>::infinity();
		}
		if (deltaY) {
			tOutY = (yOut - in[i].y) / deltaY;
		} else if (in[i].y <= max_y && min_y <= in[i].y) {
			tOutY = numeric_limits<float>::infinity();
		} else {
			tOutY = -numeric_limits<float>::infinity();
		}
		
		if (tOutX < tOutY) {
			tOut1 = tOutX;  tOut2 = tOutY;
		} else {
			tOut1 = tOutY;  tOut2 = tOutX;
		}

		if (tOut2 > 0.f) {
			if (deltaX) {
				tInX = (xIn - in[i].x) / deltaX;
			} else {
				tInX = -numeric_limits<float>::infinity();
			}
			if (deltaY) {
				tInY = (yIn - in[i].y) / deltaY;
			} else {
				tInY = -numeric_limits<float>::infinity();
			}

			if (tInX < tInY) {
				tIn2 = tInY;
			} else {
				tIn2 = tInX;
			}

			if (tOut1 < tIn2) { // edge does not cross map
				if (0.f < tOut1 && tOut1 <= 1.f) {
					// but it does go across a corner segment, add corner...
					if (tInX < tInY) {
						out.push_back(Vec2f(xOut, yIn));
					} else {
						out.push_back(Vec2f(xIn, yOut));
					}
				}
			} else {
				if (0.f < tOut1 && tIn2 <= 1.f) {
					if (0.f < tIn2) { // edge enters map
						if (tInX > tInY) {
							out.push_back(Vec2f(xIn, in[i].y + tInX * deltaY));
						} else {
							out.push_back(Vec2f(in[i].x + tInY * deltaX, yIn));
						}
					}
					if (1.f > tOut1) { // edge exits map
						if (tOutX < tOutY) {
							out.push_back(Vec2f(xOut, in[i].y + tOutX * deltaY));
						} else {
							out.push_back(Vec2f(in[i].x + tOutY * deltaX, yOut));
						}
					} else {
						out.push_back(Vec2f(in[i+1].x, in[i+1].y));
					}
				}
			}
			// edge end point on map
			if (0.f < tOut2 && tOut2 <= 1.f) {
				out.push_back(Vec2f(xOut, yOut));
			}
		} // if (tOut2 > 0.f)
	} // for each edge
}
void ProtoRootBall02::init() {

	//170, 150
	// set Materials for composite objects - or setup as multiple inheritance/interface
	rootBallCore = RootBall(Vec3f(), Vec3f(), Dim3f(2.55f), Col4f(.9f), 1, 30, .2, Tup2f(.5, 2.25), "shipPlate_yellow.jpg", 8);
	TransformFunction t1 = TransformFunction(TransformFunction::SINUSOIDAL, Tup2f(.2f, .75f), 3); // local, so can't be sent as reference
	rootBallCore.setTransformFunction(t1);


	//rootBall = RootBall(Vec3f(), Vec3f(), Dim3f(1.345f), Col4f(.9f), 1, 40, .2, Tup2f(.2, 3), "vascular3.jpg", 1);
	TransformFunction t2 = TransformFunction(TransformFunction::SINUSOIDAL, Tup2f(.14f, .22f), 80); // local, so can't be sent as reference
	//rootBall.setTransformFunction(t2);
	//std::vector<Tup4v> vs = rootBall.getGeomData();

	// export geometry data to 
	//std::vector<Tup4v> vs;
	//std::vector<Tup4v> temp = rootBallCore.getGeomData();
	//vs.insert(vs.end(), temp.begin(), temp.end());
	//std::vector<Tup4v> temp2 = rootBall.getGeomData();
	//vs.insert(vs.end(), temp2.begin(), temp2.end());
	//export(vs, STL);

	// wall
	plane = GroundPlane(Vec3(), Vec3(), Dim2f(8, 7), Col4f(1, 1, 1, 1), 1, 1, "leather2.jpg");
	//plane.textureOn();
	plane.setBumpMap("leather2.jpg");
	//plane.loadBumpMapTexture("shipPlate_normal.jpg");
	plane.setTextureScale(Vec2f(.5));
	//plane.setAmbientMaterial(Col4f(.02, .02, .02, 1.0));
	plane.setSpecularMaterial(Col4f(1, .9, 1, 1.0));
	plane.setShininess(4);
	//trace("GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS =", GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);

	// ground
	ground = GroundPlane(Vec3(), Vec3(), Dim2f(8, 7), Col4f(1, 1, 1, 1), 1, 1, "pink2.jpg");
	//plane.textureOn();
	ground.setBumpMap("pink2.jpg");
	//plane.loadBumpMapTexture("shipPlate_normal.jpg");
	ground.setTextureScale(Vec2f(.25));
	//plane.setAmbientMaterial(Col4f(.02, .02, .02, 1.0));
	ground.setSpecularMaterial(Col4f(1, 1, 1, 1.0));
	ground.setShininess(3);
	//trace("GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS =", GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);


	std::string texs[] = { "pebbles.jpg", "gold_foil2.jpg", "vascular.jpg", "greenCrocSkin.jpg", "pink2.jpg", "metal_screwHeads.jpg", "woodPlank.jpg", "metal_blue.jpg", "shipPlate_yellow.jpg", "reptile2_invert.jpg", "corroded_metal.jpg", "giraffe.jpg", "shipPlate.jpg", "metal_grate.jpg" };

	for (int i = 0; i < W*H*D; ++i){
		int sub = int(random(14));
		toroids[i] = Toroid(Vec3f(), Vec3f(random(45), random(45), random(45)), Dim3f(3, 3, 3), Col4f(.5, .5, .5, 1), 12, 12, 3, 1.2, texs[sub]);
		toroids[i].setBumpMap(texs[sub]);
		//toroids[i].setBumpMap("grime.jpg");
		toroids[i].setDiffuseMaterial(Col4f(.65, .75, 1, 1.0));
		toroids[i].setSpecularMaterial(Col4f(1, 1, 1, 1.0));
		toroids[i].setTextureScale(Vec2f(random(.25, 8.5)));
		toroids[i].setShininess(int(random(15, 40)));
	}



}
Пример #15
0
void MapScreen::scroll(Vec2f new_cam_pos, Camera& cam)
{
	new_cam_pos = new_cam_pos + Vec2f(-16 - 8, -16 - 8);
	cam.position(Vec2f(round(new_cam_pos.x()), round(new_cam_pos.y())));
}
Пример #16
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindowEventProducer = createDefaultWindowEventProducer();
    WindowPtr MainWindow = TutorialWindowEventProducer->initWindow();

    TutorialWindowEventProducer->setDisplayCallback(display);
    TutorialWindowEventProducer->setReshapeCallback(reshape);

    TutorialKeyListener TheKeyListener;
    TutorialWindowEventProducer->addKeyListener(&TheKeyListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(MainWindow);
	
										
    // Make Torus Node (creates Torus in background of scene)
    NodePtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);

    // Make Main Scene Node and add the Torus
    NodePtr scene = osg::Node::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
        scene->setCore(osg::Group::create());
        scene->addChild(TorusGeometryNode);
    endEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);

    // Create the Graphics
    GraphicsPtr TutorialGraphics = osg::Graphics2D::create();

    // Initialize the LookAndFeelManager to enable default settings
    LookAndFeelManager::the()->getLookAndFeel()->init();
    /******************************************************

                 Create an Button Component and
                 a simple Font.
                 See 17Label_Font for more
                 information about Fonts.

    ******************************************************/
    ButtonPtr ExampleButton = osg::Button::create();

    UIFontPtr ExampleFont = osg::UIFont::create();
    beginEditCP(ExampleFont, UIFont::SizeFieldMask);
        ExampleFont->setSize(16);
    endEditCP(ExampleFont, UIFont::SizeFieldMask);

    /******************************************************

            Edit the Button's characteristics.
            Note: the first 4 functions can
            be used with any Component and 
            are not specific to Button.

            -setMinSize(Vec2f): Determine the 
                Minimum Size of the Component.
                Some Layouts will automatically
                resize Components; this prevents
                the Size from going below a
                certain value.
            -setMaxSize(Vec2f): Determine the 
                Maximum Size of the Component.
            -setPreferredSize(Vec2f): Determine
                the Preferred Size of the Component.
                This is what the Component will
                be displayed at unless changed by
                another Component (such as a 
                Layout).
            -setToolTipText("Text"): Determine
                what text is displayed while
                Mouse is hovering above Component.
                The word Text will be displayed
                in this case.
            
            Functions specfic to Button:
            -setText("DesiredText"): Determine 
                the Button's text.  It will read
                DesiredText in this case.
            -setFont(FontName): Determine the 
                Font to be used on the Button.
            -setTextColor(Color4f): Determine the
                Color for the text.
            -setRolloverTextColor(Color4f): Determine
                what the text Color will be when
                the Mouse Cursor is above the 
                Button.
            -setActiveTextColor(Color4f): Determine
                what the text Color will be when
                the Button is pressed (denoted by
                Active).
            -setAlignment(Vec2f):
                Determine the Vertical Alignment
                of the text.  The value is 
                in [0.0, 1.0].

    ******************************************************/
    beginEditCP(ExampleButton, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask | Button::AlignmentFieldMask);
            ExampleButton->setMinSize(Vec2f(50, 25));
            ExampleButton->setMaxSize(Vec2f(200, 100));
            ExampleButton->setPreferredSize(Vec2f(100, 50));
            ExampleButton->setToolTipText("Button 1 ToolTip");

            ExampleButton->setText("Button 1");
            ExampleButton->setFont(ExampleFont);
            ExampleButton->setTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
            ExampleButton->setRolloverTextColor(Color4f(1.0, 0.0, 1.0, 1.0));
            ExampleButton->setActiveTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
            ExampleButton->setAlignment(Vec2f(1.0,0.0));
    endEditCP(ExampleButton, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask | Button::AlignmentFieldMask);
            
    // Create an ActionListener and assign it to ExampleButton
    // This Class is defined above, and will cause the output
    // window to display "Button 1 Action" when pressed
    ExampleButtonActionListener TheExampleButtonActionListener;
    ExampleButton->addActionListener(&TheExampleButtonActionListener);

    /******************************************************

        Create a ToggleButton and determine its 
        characteristics.  ToggleButton inherits
        off of Button, so all characteristsics
        used above can be used with ToggleButtons
        as well.

        The only difference is that when pressed,
        ToggleButton remains pressed until pressed 
        again.

        -setSelected(bool): Determine whether the 
            ToggleButton is Selected (true) or
            deselected (false).  

    ******************************************************/
    ToggleButtonPtr ExampleToggleButton = osg::ToggleButton::create();
    
    beginEditCP(ExampleToggleButton, ToggleButton::SelectedFieldMask | ToggleButton::TextFieldMask | ToggleButton::ToolTipTextFieldMask);
        ExampleToggleButton->setSelected(false);
        ExampleToggleButton->setText("ToggleMe");
        ExampleToggleButton->setToolTipText("Toggle Button ToolTip");
    endEditCP(ExampleToggleButton, ToggleButton::SelectedFieldMask | ToggleButton::TextFieldMask | ToggleButton::ToolTipTextFieldMask);

    //Button with Image
    ButtonPtr ExampleDrawObjectButton = osg::Button::create();
    beginEditCP(ExampleDrawObjectButton, Button::DrawObjectToTextAlignmentFieldMask | Button::TextFieldMask);
	    ExampleDrawObjectButton->setDrawObjectToTextAlignment(Button::ALIGN_DRAW_OBJECT_RIGHT_OF_TEXT);
        ExampleDrawObjectButton->setText("Icon");
    endEditCP(ExampleDrawObjectButton, Button::DrawObjectToTextAlignmentFieldMask | Button::TextFieldMask);

    ExampleDrawObjectButton->setImage(std::string("Data/Icon.png"));
    ExampleDrawObjectButton->setActiveImage(std::string("Data/Icon.png"));
    ExampleDrawObjectButton->setFocusedImage(std::string("Data/Icon.png"));
    ExampleDrawObjectButton->setRolloverImage(std::string("Data/Icon.png"));
    ExampleDrawObjectButton->setDisabledImage(std::string("Data/Icon.png"));

    // Create The Main InternalWindow
    // Create Background to be used with the Main InternalWindow
    ColorLayerPtr MainInternalWindowBackground = osg::ColorLayer::create();
    beginEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
    endEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);
    InternalWindowPtr MainInternalWindow = osg::InternalWindow::create();
    LayoutPtr MainInternalWindowLayout = osg::FlowLayout::create();
	beginEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);
       MainInternalWindow->getChildren().push_back(ExampleButton);
       MainInternalWindow->getChildren().push_back(ExampleToggleButton);
       MainInternalWindow->getChildren().push_back(ExampleDrawObjectButton);
       MainInternalWindow->setLayout(MainInternalWindowLayout);
       MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
	   MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setDrawTitlebar(false);
	   MainInternalWindow->setResizable(false);
    endEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);

    // Create the Drawing Surface
    UIDrawingSurfacePtr TutorialDrawingSurface = UIDrawingSurface::create();
    beginEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindowEventProducer);
    endEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
    
	TutorialDrawingSurface->openWindow(MainInternalWindow);
	
	// Create the UI Foreground Object
    UIForegroundPtr TutorialUIForeground = osg::UIForeground::create();

    beginEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);
        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);
    endEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);

    mgr->setRoot(scene);

    // Add the UI Foreground Object to the Scene
    ViewportPtr TutorialViewport = mgr->getWindow()->getPort(0);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);
        TutorialViewport->getForegrounds().push_back(TutorialUIForeground);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);

    // Show the whole Scene
    mgr->showAll();


    //Open Window
    Vec2f WinSize(TutorialWindowEventProducer->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindowEventProducer->getDesktopSize() - WinSize) *0.5);
    TutorialWindowEventProducer->openWindow(WinPos,
            WinSize,
            "01RubberBandCamera");

    //Enter main Loop
    TutorialWindowEventProducer->mainLoop();

    osgExit();

    return 0;
}
Пример #17
0
bool KeyManager::LoadFromFile(std::string filename){
    std::ifstream stream;
    stream.open(filename);
    if(!stream.is_open())
    {
        return false;
    }
    std::string row;
    std::getline(stream, row, '\n');
    if (*(row.end()-1) == '\r')
    {
        row.erase(row.end()-1);
    }
    if (*(row.begin()) == '\xef')
    {
        for(int i =0; i<3; i++)
        {
            row.erase(row.begin());
        }
    }
    while (!stream.eof())
    {
        
        while(row != "\xa7")
        {
            int x, y;
            std::stringstream ss(row);
            ss >> x >> y;
            
            sf::Color* color = new sf::Color;
            int c;
            ss >> c;
            color->r=c;
            ss >> c;
            color->g=c;
            ss >> c;
            color->b=c;
            
            Key* key = new Key(x, y, m_texture, color);
            m_keys.insert(std::make_pair(key->GetPickUpRadius(), key));
            
            ltbl::Light_Point* glow = new ltbl::Light_Point();
            glow->m_center = Vec2f(key->GetPickUpRadius()->getPosition().x, mp_lightSystem->m_viewAABB.GetDims().y - key->GetPickUpRadius()->getPosition().y);
            glow->m_radius = key->GetPickUpRadius()->getRadius();
            glow->m_size = 1.0f;
            glow->m_color.r = static_cast<float>(color->r) / 255.0f;
            glow->m_color.g = static_cast<float>(color->g) / 255.0f;
            glow->m_color.b = static_cast<float>(color->b) / 255.0f;
            glow->m_intensity = 2.0f;
            glow->m_spreadAngle = ltbl::pifTimes2;
            glow->m_softSpreadAngle = 0.0f;
            glow->CalculateAABB();
            
            mp_lightManager->AddLight(glow, key);
            
            //glow->SetAlwaysUpdate(false);
            
            std::getline(stream, row, '\n');
            if (*(row.end()-1) == '\r')
            {
                row.erase(row.end()-1);
            }
        }
        std::getline(stream, row, '\n');
        if (row == "")
        {
            break;
        }
    }
    return true;
}
Пример #18
0
void Road::ConvertAndPushRoadToVertices(Terrain& _terrain)
{
	for( size_t index=0; index < m_roads.size(); index++)
	{
		RoadTile tile = m_roads[index];
		//Vec2f min = tile.position - tile.size;
		//Vec2f max = tile.position + tile.size;
		Vec2f min = tile.position;
		Vec2f max = tile.position + tile.size;

		Vertex_PosColor vertices[6];
		vertices[0].position = Vec3f( (float)min.x , (float)min.y , 0.01f + _terrain.GetHeightAt( min ) );
		vertices[1].position = Vec3f( (float)max.x , (float)min.y , 0.01f + _terrain.GetHeightAt( Vec2f( (float)max.x , (float)min.y ) ) );
		vertices[2].position = Vec3f( (float)min.x , (float)max.y , 0.01f + _terrain.GetHeightAt( Vec2f( (float)min.x , (float)max.y ) ) );

		vertices[3].position = Vec3f( (float)min.x , (float)max.y , 0.01f + _terrain.GetHeightAt( Vec2f( (float)min.x , (float)max.y ) ) );
		vertices[4].position = Vec3f( (float)max.x , (float)min.y , 0.01f + _terrain.GetHeightAt( Vec2f( (float)max.x , (float)min.y ) ) );
		vertices[5].position = Vec3f( (float)max.x , (float)max.y , 0.01f + _terrain.GetHeightAt(max) );

		for( int index = 0; index < 6; ++index)
		{
			vertices[index].color = tile.color;
			m_vertices.push_back(vertices[index]);
		}
	}
}
Пример #19
0
void GLWidget::project_quad_texture() {
    const int sx = width(), sy = height();
    Point pt[4];
    static Vec3f corners[] = {
        Vec3f(0, 0, 0),
        Vec3f(sx-1, 0, 0),
        Vec3f(0, sy-1, 0),
        Vec3f(sx-1, sy-1, 0)
    };
    
    for (int i = 0; i < 4; i++) {
        pt[i] = project(Vec3f(corners[i].x - sx/2, corners[i].y - sy/2, 0));
        pt[i].x += sx/2;
        pt[i].y += sy/2;
    }
    
    Vec3f normal1(0, 0, 1);
    Vec3f normal2;
    {
        Vec3f foo[3];
        for (int i = 0; i < 3; i++)
            foo[i] = project2(corners[i]);
        normal2 = normal(foo[0], foo[1], foo[2]);
    }
    
    double dir = normal1.x * normal2.x + normal1.y * normal2.y + normal1.z * normal2.z;
    
    QImage& tex = dir < 0 ? back : front;
    
    int ow = tex.width(), oh = tex.height();
       
    Vec2f p2[4];

    for (int i = 0; i < 4; i++)
        p2[i] = Vec2f(pt[i].x, pt[i].y);
    
    QImage texture(QSize(sx, sy), QImage::Format_RGB888);
    texture.fill(Qt::black);
    
    const Vec2f projected[2][3] = { { p2[0], p2[1], p2[2] }, { p2[3], p2[1], p2[2] } };
    const Vec2f origs[2][3] = {
        { Vec2f(0, 0), Vec2f(ow-1, 0), Vec2f(0, oh-1) },
        { Vec2f(ow-1, oh-1), Vec2f(ow-1, 0), Vec2f(0, oh-1) }
    };
    const Triangle triangles[2] = {
        Triangle(projected[0][0], projected[0][1], projected[0][2]),
        Triangle(projected[1][0], projected[1][1], projected[1][2])
    };
  
    int orig_pitch = tex.bytesPerLine();
    int dest_pitch = texture.bytesPerLine();
    
    const unsigned char* orig = tex.bits();
    unsigned char* dest = texture.bits();
    
    int orig_depth = tex.depth() / 8;
    int dest_depth = texture.depth() / 8;
    
    /* image breakage? */
    if (orig_depth < 3)
        return;

    for (int y = 0; y < sy; y++)
        for (int x = 0; x < sx; x++) {
            Vec2f pos;
            pos.x = x;
            pos.y = y;
            for (int i = 0; i < 2; i++) {
                Vec2f coords;
                if (triangles[i].barycentric_coords(pos, coords))
                {
                    double qx = origs[i][0].x
                                + coords.x * (origs[i][2].x - origs[i][0].x)
                                + coords.y * (origs[i][1].x - origs[i][0].x);
                    double qy = origs[i][0].y
                                + coords.x * (origs[i][2].y - origs[i][0].y)
                                + coords.y * (origs[i][1].y - origs[i][0].y);
                    int qx1 = std::min<int>(ow - 1, std::max<int>(0, qx - 0.5));
                    int qy1 = std::min<int>(oh - 1, std::max<int>(0, qy - 0.5));
                    int qx2 = std::min<int>(ow - 1, std::max<int>(0, qx + 0.5));
                    int qy2 = std::min<int>(oh - 1, std::max<int>(0, qy + 0.5));

                    double dx1 = qx1 - qx;
                    double dy1 = qy1 - qy;
                    double dx2 = qx2 - qx;
                    double dy2 = qy2 - qy;

                    double d1 = 2 - (dx1 * dx1 + dy1 * dy1);
                    double d2 = 2 - (dx2 * dx2 + dy2 * dy2);
                    double d3 = 2 - (dx2 * dx2 + dy1 * dy1);
                    double d4 = 2 - (dx1 * dx1 + dy2 * dy2);

                    double inv_norm = 1. / (d1 + d2 + d3 + d4);

                    d1 *= inv_norm;
                    d2 *= inv_norm;
                    d3 *= inv_norm;
                    d4 *= inv_norm;
                    
                    double r = d1 * (double) orig[qy1 * orig_pitch + qx1 * orig_depth + 2]
                               + d2 * (double) orig[qy2 * orig_pitch + qx2 * orig_depth + 2]
                               + d3 * (double) orig[qy1 * orig_pitch + qx2 * orig_depth + 2]
                               + d4 * (double) orig[qy2 * orig_pitch + qx1 * orig_depth + 2];
                    
                    double g = d1 * (double) orig[qy1 * orig_pitch + qx1 * orig_depth + 1]
                               + d2 * (double) orig[qy2 * orig_pitch + qx2 * orig_depth + 1]
                               + d3 * (double) orig[qy1 * orig_pitch + qx2 * orig_depth + 1]
                               + d4 * (double) orig[qy2 * orig_pitch + qx1 * orig_depth + 1];
                    
                    double b = d1 * (double) orig[qy1 * orig_pitch + qx1 * orig_depth + 0]
                               + d2 * (double) orig[qy2 * orig_pitch + qx2 * orig_depth + 0]
                               + d3 * (double) orig[qy1 * orig_pitch + qx2 * orig_depth + 0]
                               + d4 * (double) orig[qy2 * orig_pitch + qx1 * orig_depth + 0];
                    
                    dest[y * dest_pitch + x * dest_depth + 0] = std::max<int>(0, std::min<int>(255, r));
                    dest[y * dest_pitch + x * dest_depth + 1] = std::max<int>(0, std::min<int>(255, g));
                    dest[y * dest_pitch + x * dest_depth + 2] = std::max<int>(0, std::min<int>(255, b));

                    break;
                }
            }
        }
    pixmap = QPixmap::fromImage(texture);
}
// Initialize WIN32 & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

        // Create the SimpleSceneManager helper
        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        TutorialWindow->connectKeyTyped(boost::bind(keyPressed, _1));

        // Make Torus Node (creates Torus in background of scene)
        NodeRecPtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);

        // Make Main Scene Node and add the Torus
        NodeRecPtr scene = Node::create();
        scene->setCore(Group::create());
        scene->addChild(TorusGeometryNode);

        // Create the Graphics
        GraphicsRecPtr graphics = Graphics2D::create();

        // Initialize the LookAndFeelManager to enable default settings
        LookAndFeelManager::the()->getLookAndFeel()->init();

        /******************************************************

          Create the DerivedFieldContainerComboBoxModel and
          add Elements to it (derived FieldContainerTypes
          ).  These will be the data
          values shown in the ComboBox.

         ******************************************************/   

        DerivedFieldContainerComboBoxModelRecPtr ExampleComboBoxModel = DerivedFieldContainerComboBoxModel::create();
        ExampleComboBoxModel->editMFDerivedFieldContainerTypes()->push_back(std::string(Component::getClassType().getCName()));

        /******************************************************

          Create an editable ComboBox.  A ComboBox 
          has a Model just like various other 
          Components.  

         ******************************************************/   

        //Create the ComboBox
        ComboBoxRecPtr ExampleUneditableComboBox = ComboBox::create();

        // Set it to be uneditable
        ExampleUneditableComboBox->setEditable(false);
        ExampleUneditableComboBox->setModel(ExampleComboBoxModel);
        ExampleUneditableComboBox->setSelectedIndex(0);
        ExampleUneditableComboBox->setPreferredSize(Vec2f(160.0f,ExampleUneditableComboBox->getPreferredSize().y()));

        // Create The Main InternalWindow
        // Create Background to be used with the Main InternalWindow
        ColorLayerRecPtr MainInternalWindowBackground = ColorLayer::create();
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));

        FlowLayoutRecPtr MainInternalWindowLayout = FlowLayout::create();
        MainInternalWindowLayout->setMinorAxisAlignment(0.2f);

        InternalWindowRecPtr MainInternalWindow = InternalWindow::create();
        MainInternalWindow->pushToChildren(ExampleUneditableComboBox);
        MainInternalWindow->setLayout(MainInternalWindowLayout);
        MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
        MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
        MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.8f,0.8f));
        MainInternalWindow->setDrawTitlebar(false);
        MainInternalWindow->setResizable(false);

        //Create the Drawing Surface
        UIDrawingSurfaceRecPtr TutorialDrawingSurface = UIDrawingSurface::create();
        TutorialDrawingSurface->setGraphics(graphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindow);

        TutorialDrawingSurface->openWindow(MainInternalWindow);

        // Create the UI Foreground Object
        UIForegroundRecPtr foreground = UIForeground::create();

        foreground->setDrawingSurface(TutorialDrawingSurface);



        // Tell the manager what to manage
        sceneManager.setRoot(scene);

        // Add the UI Foreground Object to the Scene
        ViewportRecPtr viewport = sceneManager.getWindow()->getPort(0);
        viewport->addForeground(foreground);

        // Show the whole scene
        sceneManager.showAll();

        //Open Window
        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "42FieldContainerComboBox");

        //Enter main Loop
        TutorialWindow->mainLoop();
    }

    osgExit();

    return 0;
}
Пример #21
0
//---------------------------------------------------------------------------
bool Player::Update()
{
	//g_xboxHandlerOne.UpdateControllerState();
	m_position = Vec2f( CosDegrees( m_degrees ), SinDegrees( m_degrees ) ) * m_currentRadius;
	return m_didUpdate;
}
Пример #22
0
void CpuClipmapRenderer::renderBlock( const GeometryClipmapLevel& level, const GeometryClipmapLevel* coarserLevel, const ClipmapRenderParameters& renderParameters, const Color3f& debugColor )
{
    TerrainLevelRenderData& renderData = levels_[ level.index ];

    if( renderData.indices.size() <= 0 )
    {
        return;
    }


    // enable the texture:
    // todo: enable the texture of the next coarser level too, so we can blend between both
    if( renderData.texture != NULL )
    {
        //renderData.texture->activate( renderParameters.renderAction );
    }
    Pnt2i transitionSize;

    //transitionSize[ 0 ] = std::min( ( levelSampleCount_ / 10 ) * level.sampleDistance[ 0 ], level.minTransitionSize[ 0 ] );
    //transitionSize[ 1 ] = std::min( ( levelSampleCount_ / 10 ) * level.sampleDistance[ 1 ], level.minTransitionSize[ 1 ] );

    const int levelSampleSpacing = level.sampleSpacing;

    transitionSize[ 0 ] = levelSampleSpacing * level.heightmap.size / 10;
    transitionSize[ 1 ] = levelSampleSpacing * level.heightmap.size / 10;

    // min and max are the first,last point inside the renderregion:
    Pnt2f activeRegionMin = Pnt2f( level.sampleOrigin );
    Pnt2f activeRegionMax = Pnt2f( componentAdd( level.sampleOrigin, Pnt2i( level.getSampleCoverage(), level.getSampleCoverage() ) ) );

    Pnt2f worldTransitionSize = Pnt2f( transitionSize );

    //Point2f activeRegionCenter = samplePosToWorldPos( level.outerRenderBounds.getTopLeft() + level.outerRenderBounds.getSize() / 2 );		
    //Point2f localViewerPos( worldViewerPosition_[ 0 ], worldViewerPosition_.z );
    //Pnt2i viewerSamplePos = worldPosToSamplePos( localViewerPos );
    //Point2f baseLocalViewerPos = samplePosToWorldPos( viewerSamplePos );

    //localViewerPos -= baseLocalViewerPos;

#ifdef OLD_GEOCLIP
    //beginEditCP( terrainShader_ );
    terrainShader_.setUniform( "transitionWidth", Vec2f( worldTransitionSize ) );
    terrainShader_.setUniform( "activeRegionMin", Vec2f( activeRegionMin ) );
    terrainShader_.setUniform( "activeRegionMax", Vec2f( activeRegionMax ) );
    //terrainShader_->setUniform( "activeRegionCenter", activeRegionCenter );		
    terrainShader_.setUniform( "localViewerPos", Vec3f( viewerPosition_ ) );
    terrainShader_.setUniform( "baseColor0", colorToVector( debugColor ) );
    //endEditCP( terrainShader_ );
#else
    _pTerrainShader->addUniformVariable( "transitionWidth", 
                                          Vec2f( worldTransitionSize ) );
    _pTerrainShader->addUniformVariable( "activeRegionMin", 
                                          Vec2f( activeRegionMin ) );
    _pTerrainShader->addUniformVariable( "activeRegionMax", 
                                          Vec2f( activeRegionMax ) );
    //terrainShader_->setUniform( "activeRegionCenter", activeRegionCenter );		
    _pTerrainShader->addUniformVariable( "localViewerPos", 
                                          Vec3f( viewerPosition_ ) );
#ifdef NOTUSED
    _pTerrainShader->setUniformParameter( "baseColor0", 
                                          colorToVector( debugColor ) );
#endif
#endif

    if( coarserLevel )
    {
#ifdef OLD_GEOCLIP
        terrainShader_.setUniform( 
            "baseColor1", 
            colorToVector( getDebugColor( coarserLevel->index ) ) );
#else
#ifdef NOTUSED
        _pTerrainShader->setUniformParameter( 
            "baseColor1", 
            colorToVector( getDebugColor( coarserLevel->index ) ) );
#endif
#endif
    }
    else
    {
#ifdef OLD_GEOCLIP
        terrainShader_.setUniform( 
            "baseColor1", 
            colorToVector( debugColor ) );
#else
#ifdef NOTUSED
        _pTerrainShader->setUniformParameter( 
            "baseColor1", 
            colorToVector( debugColor ) );
#endif
#endif
    }

    //terrainShader_->updateParameters( drawAction->getWindow(), terrainShader_->getParameters() );

    if( renderParameters.useVboExtension && useVertexBufferObjects_ )
    {
        renderData.vertexBuffer.activate();

        char* base = 0;

        glVertexPointer( 4, GL_FLOAT, sizeof( OpenGLTerrainVertex ), base );
        glEnableClientState( GL_VERTEX_ARRAY );

        glTexCoordPointer( 2, GL_FLOAT, sizeof( OpenGLTerrainVertex ), base + sizeof( Pnt4f ) );
        glEnableClientState( GL_TEXTURE_COORD_ARRAY );

        glDrawElements( GL_TRIANGLES, GLsizei(renderData.indices.size()),
                        GL_UNSIGNED_SHORT, &renderData.indices[ 0 ] );

        renderData.vertexBuffer.deactivate();
    }
    else
    {
        glVertexPointer( 4, GL_FLOAT, sizeof( OpenGLTerrainVertex ), &renderData.vertices[ 0 ].pos );
        glEnableClientState( GL_VERTEX_ARRAY );

        glTexCoordPointer( 2, GL_FLOAT, sizeof( OpenGLTerrainVertex ), &renderData.vertices[ 0 ].uv );
        glEnableClientState( GL_TEXTURE_COORD_ARRAY );

        glDrawElements( GL_TRIANGLES, GLsizei(renderData.indices.size()),
                        GL_UNSIGNED_SHORT, &renderData.indices[ 0 ] );
    }

    glDisableClientState( GL_TEXTURE_COORD_ARRAY );
    glDisableClientState( GL_NORMAL_ARRAY );
    glDisableClientState( GL_VERTEX_ARRAY );

    stats_.drawnBlockCount++;
    stats_.drawnTriangleCount		+= int(renderData.indices.size()) / 3;
    stats_.transformedVertexCount	+= int(renderData.vertices.size());

    if( renderData.texture != NULL )
    {
        //renderData.texture->deactivate( renderParameters.renderAction );
    }
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

        // Create the SimpleSceneManager helper
        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        //Attach to events
        TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager));
        TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager));
        TutorialWindow->connectMouseMoved(boost::bind(mouseMoved, _1, &sceneManager));
        TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager));
        TutorialWindow->connectMouseWheelMoved(boost::bind(mouseWheelMoved, _1, &sceneManager));

        //Particle System Material
        PointChunkRefPtr PSPointChunk = PointChunk::create();
        PSPointChunk->setSize(5.0f);
        PSPointChunk->setSmooth(true);

        BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
        PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
        PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

        MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create();
        PSMaterialChunkChunk->setAmbient(Color4f(1.0f,1.0f,1.0f,1.0f));
        PSMaterialChunkChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
        PSMaterialChunkChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f));
        PSMaterialChunkChunk->setColorMaterial(GL_NONE);

        ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
        PSMaterial->addChunk(PSPointChunk);
        PSMaterial->addChunk(PSMaterialChunkChunk);
        PSMaterial->addChunk(PSBlendChunk);

        //Particle System
        ParticleSystemRefPtr ExampleParticleSystem = ParticleSystem::create();
        ExampleParticleSystem->addParticle(Pnt3f(0,-50,0),
                                           Vec3f(0.0,0.0f,1.0f),
                                           Color4f(1.0,1.0,1.0,1.0), 
                                           Vec3f(1.0,1.0,1.0), 
                                           0.1, 
                                           Vec3f(0.0f,0.0f,0.0f), //Velocity
                                           Vec3f(0.0f,0.0f,0.0f)
                                          );
        ExampleParticleSystem->addParticle(Pnt3f(0,30,0),
                                           Vec3f(0.0,0.0f,1.0f),
                                           Color4f(1.0,1.0,1.0,1.0), 
                                           Vec3f(1.0,1.0,1.0), 
                                           0.1, 
                                           Vec3f(0.0f,0.0f,0.0f), //Velocity
                                           Vec3f(0.0f,0.0f,0.0f)
                                          );
        ExampleParticleSystem->attachUpdateProducer(TutorialWindow);

        //Particle System Drawer (Point)
        PointParticleSystemDrawerRecPtr ExamplePointParticleSystemDrawer = PointParticleSystemDrawer::create();

        //Particle System Drawer (line)
        LineParticleSystemDrawerRecPtr ExampleLineParticleSystemDrawer = LineParticleSystemDrawer::create();
        ExampleLineParticleSystemDrawer->setLineDirectionSource(LineParticleSystemDrawer::DIRECTION_VELOCITY);
        ExampleLineParticleSystemDrawer->setLineLengthSource(LineParticleSystemDrawer::LENGTH_SIZE_X);
        ExampleLineParticleSystemDrawer->setLineLength(2.0f);
        ExampleLineParticleSystemDrawer->setEndPointFading(Vec2f(0.0f,1.0f));

        //Create a Rate Particle Generator
        RateParticleGeneratorRefPtr ExampleGenerator = RateParticleGenerator::create();

        //Attach the function objects to the Generator
        ExampleGenerator->setPositionDistribution(createPositionDistribution());
        ExampleGenerator->setLifespanDistribution(createLifespanDistribution());
        ExampleGenerator->setGenerationRate(60.0);
        ExampleGenerator->setVelocityDistribution(createVelocityDistribution());


        DragParticleAffectorRecPtr ExampleDragAffector = DragParticleAffector::create();
        ExampleDragAffector->setMagnitude(5.0); 
        ExampleDragAffector->setDirection(Vec3f(0.0,5.0,5.0));
        NodeRefPtr DragBeacon = Node::create();
        ExampleDragAffector->setBeacon(DragBeacon); // set to 'emulate' from (0,0,0)
        ExampleDragAffector->setMaxDistance(-1.0); // particles affected regardless of distance
        ExampleDragAffector->setAttenuation(1.5); // strength of uniform field dimishes by a factor of dist^attenuation
        ExampleDragAffector->setSpeedAttenuation(2.0); // particle w/ velocity < speedAttenuation are not affected as much


        //Attach the Generator and Affector to the Particle System
        ExampleParticleSystem->pushToGenerators(ExampleGenerator);
        ExampleParticleSystem->pushToAffectors(ExampleDragAffector);
        ExampleParticleSystem->setMaxParticles(800);


        //Particle System Node
        ParticleSystemCoreRecPtr ParticleNodeCore = ParticleSystemCore::create();
        ParticleNodeCore->setSystem(ExampleParticleSystem);
        ParticleNodeCore->setDrawer(ExamplePointParticleSystemDrawer);
        ParticleNodeCore->setMaterial(PSMaterial);

        NodeRefPtr ParticleNode = Node::create();
        ParticleNode->setCore(ParticleNodeCore);


        // Make Main Scene Node and add the Torus
        NodeRefPtr scene = Node::create();
        scene->setCore(Group::create());
        scene->addChild(ParticleNode);

        TutorialWindow->connectKeyTyped(boost::bind(keyTyped, _1,
                                                    &sceneManager,
                                                    ParticleNodeCore.get(),
                                                    ExamplePointParticleSystemDrawer.get(),
                                                    ExampleLineParticleSystemDrawer.get(),
                                                    ExampleDragAffector.get()));

        sceneManager.setRoot(scene);

        // Show the whole Scene
        sceneManager.showAll();

        sceneManager.getCamera()->setFar(1000.0);

        std::cout << "Drag Particle Affector Tutorial Controls:\n"
            << "1: Use point drawer\n"
            << "2: Use line drawer\n"
            << "3: Decrease magnitude of drag.\n"
            << "4: Increase magnitude of drag.\n"
            << "Ctrl + Q: Exit Tutorial";

        //Open Window
        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "26DragParticleAffector");

        //Enter main Loop
        TutorialWindow->mainLoop();

    }
    osgExit();

    return 0;
}
Пример #24
0
 Vec2f perp(const Vec2f& v) {
     return Vec2f(v[1], -v[0]);
 }
Пример #25
0
	WritingExample(void)
	{
		VertexShader vs;
		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"in vec4 Position;"
			"void main(void)"
			"{"
			"	gl_Position = Position;"
			"}"
		);
		// compile it
		vs.Compile();

		GeometryShader gs;
		// Set the geometry shader source
		gs.Source(
			"#version 330\n"
			"layout(lines) in;"
			"layout(triangle_strip, max_vertices = 4) out;"
			"void main(void)"
			"{"
			"	vec4 offs = vec4(0.02, 0.01, 0.0, 0.0);"
			"	gl_Position = gl_in[0].gl_Position - offs;"
			"	EmitVertex();"
			"	gl_Position = gl_in[0].gl_Position + offs;"
			"	EmitVertex();"
			"	gl_Position = gl_in[1].gl_Position - offs;"
			"	EmitVertex();"
			"	gl_Position = gl_in[1].gl_Position + offs;"
			"	EmitVertex();"
			"	EndPrimitive();"
			"}"
		);
		// compile it
		gs.Compile();

		FragmentShader fs;
		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	fragColor = vec4(0.0, 0.0, 0.0, 1.0);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(gs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		const Vec2f points[] = {
			Vec2f(-0.33f, +0.50f),
			Vec2f(-0.45f, +0.70f),
			Vec2f(-0.66f, +0.70f),
			Vec2f(-0.66f, +0.30f),
			Vec2f(-0.66f, -0.20f),
			Vec2f(-0.35f, -0.15f),
			Vec2f(-0.30f, +0.05f),
			Vec2f(-0.20f, +0.50f),
			Vec2f(-0.30f, +0.50f),
			Vec2f(-0.33f, +0.50f),
			Vec2f(-0.50f, +0.45f),
			Vec2f(-0.10f, +0.40f),
			Vec2f(+0.10f, +0.55f),
			Vec2f(-0.20f, +0.40f),
			Vec2f(-0.30f, -0.10f),
			Vec2f( 0.00f, -0.10f),
			Vec2f(+0.10f, -0.10f),
			Vec2f(+0.20f, -0.10f),
			Vec2f(+0.10f, +0.55f),
			Vec2f(+0.20f, +0.00f),
			Vec2f(+0.30f, -0.70f),
			Vec2f( 0.00f, -0.75f),
			Vec2f(-0.40f, -0.75f),
			Vec2f( 0.00f,  0.00f),
			Vec2f(+0.40f, +0.10f),
			Vec2f(+0.60f, +0.10f),
			Vec2f(+0.70f, +0.90f),
			Vec2f(+0.55f, +0.90f),
			Vec2f(+0.35f, +0.90f),
			Vec2f(+0.10f, -0.10f),
			Vec2f(+0.55f,  0.00f),
			Vec2f(+0.90f,  0.10f),
			Vec2f(+0.70f,  0.10f),
			Vec2f(+0.90f,  0.20f)
		};
		BezierCurves<Vec2f, double, 3> bezier(
			std::vector<Vec2f>(
				points,
				points+sizeof(points)/sizeof(points[0])
			)
		);

		writing.Bind();
		{
			auto data = bezier.Approximate(25);
			curve_n = data.size();
			Bind(curve_verts, Buffer::Target::Array).Data(data);
			VertexAttribArray attr(prog, "Position");
			attr.Setup(2, DataType::Float);
			attr.Enable();
		}

		gl.ClearColor(0.9f, 0.9f, 0.9f, 0.0f);
	}
Пример #26
0
bool CubemapCamera::sampleDirection(PathSampleGenerator &sampler, const PositionSample &point,
        DirectionSample &sample) const
{
    Vec2u pixel(sampler.next2D(CameraSample)*Vec2f(_res));
    return sampleDirection(sampler, point, pixel, sample);
}
Пример #27
0
int main(int argc, char* argv[])
{

	// ========================================================
	// ========================================================
	// Some sample code you might like to use for parsing 
	// command line arguments 

	char *input_file = NULL;
	int width = 100;
	int height = 100;
	char *output_file = NULL;
	float depth_min = 0;
	float depth_max = 1;
	char *depth_file = NULL;

	// sample command line:
	// raytracer -input scene1_1.txt -size 200 200 -output output1_1.tga -depth 9 10 depth1_1.tga

	for (int i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "-input")) {
			i++; assert(i < argc);
			input_file = argv[i];
		}
		else if (!strcmp(argv[i], "-size")) {
			i++; assert(i < argc);
			width = atoi(argv[i]);
			i++; assert(i < argc);
			height = atoi(argv[i]);
		}
		else if (!strcmp(argv[i], "-output")) {
			i++; assert(i < argc);
			output_file = argv[i];
		}
		else if (!strcmp(argv[i], "-depth")) {
			i++; assert(i < argc);
			depth_min = atof(argv[i]);
			i++; assert(i < argc);
			depth_max = atof(argv[i]);
			i++; assert(i < argc);
			depth_file = argv[i];
		}
		else {
			printf("whoops error with command line argument %d: '%s'\n", i, argv[i]);
			assert(0);
		}
	}

	// ========================================================
	// ========================================================

	//Use the input file parsing code provided to load the camera, 
	//background color and objects of the scene.
	SceneParser* sceneParser = new SceneParser(input_file);

	Image *image = new Image(width, height);
	Image *image2 = new Image(width, height);
	image->SetAllPixels(sceneParser->getBackgroundColor());
	image2->SetAllPixels(sceneParser->getBackgroundColor());
	Camera *camera = sceneParser->getCamera();
	Group *group = sceneParser->getGroup();

	Vec3f black(0.0f, 0.0f, 0.0f);
	Material *init = new Material(black);

	/*
	Write a main function that reads the scene (using the parsing code provided),
	loops over the pixels in the image plane,
	generates a ray using your OrthographicCamera class,
	intersects it with the high-level Group that stores the objects of the scene,
	and writes the color of the closest intersected object.
	*/
	/*
	ray casting:
	for every pixel
	construct a ray from the eye
	for every object in the scene
	find intersection with the ray
	keep if closest
	*/

	for (int i = 0; i < width; i++)
	for (int j = 0; j < height; j++)
	{
		float x = i*1.0 / width;
		float y = j*1.0 / height;
		Ray ray = camera->generateRay(Vec2f(x, y));

		Hit hit(0.0f, init);
		//ray:带入参数  hit:带出信息
		if (group->intersect(ray, hit, camera->getTMin()))//撞到了
		{
			image->SetPixel(i,j,hit.getMaterial()->getDiffuseColor());

			//k值越大说明越远,颜色应该越深
			float k = (hit.getT() - depth_min)*1.0 / (depth_max - depth_min);
			if (k > 1.0f) k = 1.0f;
			if (k < 0.0f) k = 0.0f;
			Vec3f gray(1.0f - k, 1.0f - k, 1.0f - k);
			image2->SetPixel(i, j, gray);
		}
	}

	image->SaveTGA(output_file);
	image2->SaveTGA(depth_file);

	/*
	Implement a second rendering style to visualize the depth t of objects in the scene. 
	Two input depth values specify the range of depth values which should be mapped 
	to shades of gray in the visualization. Depth values outside this range are simply clamped.
	*/

	return 0;
}
Пример #28
0
// Initialize WIN32 & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

        // Create the SimpleSceneManager helper
        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        TutorialWindow->connectKeyTyped(boost::bind(keyPressed, _1));

        // Make Torus Node (creates Torus in background of scene)
        NodeRecPtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);

        // Make Main Scene Node and add the Torus
        NodeRecPtr scene = Node::create();
        scene->setCore(Group::create());
        scene->addChild(TorusGeometryNode);

        // Create the Graphics
        GraphicsRecPtr graphics = Graphics2D::create();

        // Initialize the LookAndFeelManager to enable default settings
        LookAndFeelManager::the()->getLookAndFeel()->init();

        /******************************************************

          Create the DefaultMutableComboBoxModel and
          add Elements to it (several Colors
          in this case).  These will be the data
          values shown in the ComboBox.

         ******************************************************/   

        DefaultMutableComboBoxModelRecPtr ExampleComboBoxModel = DefaultMutableComboBoxModel::create();
        ExampleComboBoxModel->addElement(boost::any(std::string("Red")));
        ExampleComboBoxModel->addElement(boost::any(std::string("Green")));
        ExampleComboBoxModel->addElement(boost::any(std::string("Blue")));
        ExampleComboBoxModel->addElement(boost::any(std::string("Brown")));
        ExampleComboBoxModel->addElement(boost::any(std::string("Yellow")));
        ExampleComboBoxModel->addElement(boost::any(std::string("Orange")));
        ExampleComboBoxModel->addElement(boost::any(std::string("Violet")));
        ExampleComboBoxModel->addElement(boost::any(std::string("Black")));

        /******************************************************

          Create an editable ComboBox.  A ComboBox 
          has a Model just like various other 
          Components.  

         ******************************************************/   

        //Create the ComboBox
        ComboBoxRecPtr ExampleComboBox = ComboBox::create();

        // Set the Model created above to the ComboBox
        ExampleComboBox->setModel(ExampleComboBoxModel);

        // Determine where the ComboBox starts
        ExampleComboBox->setSelectedIndex(0);

        /******************************************************

          Create a non-editable ComboBox.  

          -setEditable(bool): Determine whether
          the user can type in the ComboBox
          or if it is uneditable.  In this
          case, it is set to false.

          When creating a non-editable ComboBox,
          a Renderer must also be assigned.  For
          editable ComboBoxes, the ComboBox
          automatically shows its text due to the
          nature of the ComboBox.  However, when
          uneditable, this aspect of the ComboBox
          is disabled, and so to display the 
          selection, a renderer must be created and
          assigned to the ComboBox.

Note: as with Sliders and ScrollBars,
having the same Model assigned causes
the ComboBoxes to be tied together.

         ******************************************************/   
        // Create another ComboBox
        ComboBoxRecPtr ExampleUneditableComboBox = ComboBox::create();

        // Set it to be uneditable
        ExampleUneditableComboBox->setEditable(false);
        ExampleUneditableComboBox->setModel(ExampleComboBoxModel);

        // Create The Main InternalWindow
        // Create Background to be used with the Main InternalWindow
        ColorLayerRecPtr MainInternalWindowBackground = ColorLayer::create();
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));

        LayoutRecPtr MainInternalWindowLayout = FlowLayout::create();

        InternalWindowRecPtr MainInternalWindow = InternalWindow::create();
        MainInternalWindow->pushToChildren(ExampleComboBox);
        MainInternalWindow->pushToChildren(ExampleUneditableComboBox);
        MainInternalWindow->setLayout(MainInternalWindowLayout);
        MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
        MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
        MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.5f,0.5f));
        MainInternalWindow->setDrawTitlebar(false);
        MainInternalWindow->setResizable(false);

        //Create the Drawing Surface
        UIDrawingSurfaceRecPtr TutorialDrawingSurface = UIDrawingSurface::create();
        TutorialDrawingSurface->setGraphics(graphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindow);

        TutorialDrawingSurface->openWindow(MainInternalWindow);

        // Create the UI Foreground Object
        UIForegroundRecPtr foreground = UIForeground::create();

        foreground->setDrawingSurface(TutorialDrawingSurface);



        // Tell the manager what to manage
        sceneManager.setRoot(scene);

        // Add the UI Foreground Object to the Scene
        ViewportRecPtr viewport = sceneManager.getWindow()->getPort(0);
        viewport->addForeground(foreground);

        //Create the Documentation Foreground and add it to the viewport
        SimpleScreenDoc TheSimpleScreenDoc(&sceneManager, TutorialWindow);

        // Show the whole scene
        sceneManager.showAll();

        //Open Window
        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "33ComboBox");

        //Enter main Loop
        TutorialWindow->mainLoop();
    }

    osgExit();

    return 0;
}
void StelQGLRenderer::drawRectInternal
	(const bool textured, const float x, const float y, const float width, 
	 const float height, const float angle)
{
	statistics[RECT_DRAWS] += 1.0;
	// Could be improved by keeping the vertex buffer as a data member,
	// or even caching all rectangle draws to the same buffer and drawing them 
	// at once at the end of the frame.
	
	Vec2f ne, nw, se, sw;

	// Faster path for angles that are zero or extremely small.
	if(abs(angle) < 0.1)
	{
		ne = Vec2f(x, y);
		nw = Vec2f(x + width, y);
		se = Vec2f(x, y + height);
		sw = Vec2f(x + width, y + height);
	}
	// Need to rotate the rectangle (around its center).
	else
	{
		const float cosr       = std::cos(angle / 180 * M_PI);
		const float sinr       = std::sin(angle / 180 * M_PI);
		const float halfWidth  = width  * 0.5;
		const float halfHeight = height * 0.5;
		const Vec2f center(x + halfWidth, y + halfHeight);

		const float widthCos  = halfWidth  * cosr;
		const float heightCos = halfHeight * cosr;
		const float widthSin  = halfWidth  * sinr;
		const float heightSin = halfHeight * sinr;

		ne = center + Vec2f(-widthCos + heightSin, -widthSin - heightCos);
		nw = center + Vec2f(widthCos  + heightSin, widthSin  - heightCos);
		se = center + Vec2f(-widthCos - heightSin, -widthSin + heightCos);
		sw = center + Vec2f(widthCos  - heightSin, widthSin  + heightCos);
	}
	
	// Prepare a vertex buffer for the rectangle and draw it.
	if(textured)
	{
		if(NULL == texturedRectBuffer)
		{
			texturedRectBuffer = 
				createVertexBuffer<TexturedVertex>(PrimitiveType_TriangleStrip);
		}
		else
		{
			texturedRectBuffer->unlock();
			texturedRectBuffer->clear();
		}

		texturedRectBuffer->addVertex(TexturedVertex(ne, Vec2f(0.0f , 0.0f)));
		texturedRectBuffer->addVertex(TexturedVertex(nw, Vec2f(1.0f , 0.0f)));
		texturedRectBuffer->addVertex(TexturedVertex(se, Vec2f(0.0f , 1.0f)));
		texturedRectBuffer->addVertex(TexturedVertex(sw, Vec2f(1.0f , 1.0f)));

		texturedRectBuffer->lock();
		drawVertexBuffer(texturedRectBuffer);
	}
	else
	{
		if(NULL == plainRectBuffer)
		{
			plainRectBuffer = 
				createVertexBuffer<VertexP2>(PrimitiveType_TriangleStrip);
		}
		else
		{
			plainRectBuffer->unlock();
			plainRectBuffer->clear();
		}

		plainRectBuffer->addVertex(VertexP2(ne));
		plainRectBuffer->addVertex(VertexP2(nw));
		plainRectBuffer->addVertex(VertexP2(se));
		plainRectBuffer->addVertex(VertexP2(sw));

		plainRectBuffer->lock();
		drawVertexBuffer(plainRectBuffer);
	}
}
Пример #30
0
void Player::draw()
{
    if (displist == -1)
    {
        displist = glGenLists(1);
        glNewList(displist, GL_COMPILE);

        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_COLOR, GL_ONE);
        if (side == FRONT)
        {
            GLfloat mat_ambient[] = {0.0, 0.5, 0.0};
            GLfloat mat_diffuse[] = {0.0, 0.5, 0.0};
            GLfloat mat_specular[] = {0.0, 0.0, 0.0};
            GLfloat mat_emission[] = {0.0, 0.0, 0.0};
            GLfloat mat_shininess = 0.07812619;
            glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
            glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
            glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
            glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_emission);
            glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
        } else {
            GLfloat mat_ambient[] = {0.8, 0.0, 0.0};
            GLfloat mat_diffuse[] = {0.8, 0.0, 0.0};
            GLfloat mat_specular[] = {0.0, 0.0, 0.0};
            GLfloat mat_emission[] = {0.0, 0.0, 0.0};
            GLfloat mat_shininess = 0.07812619;
            glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
            glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
            glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
            glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_emission);
            glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
        }

        Vec2f diff = Vec2f(width / 2.0f / 5.0f,	height / 2.0f / 5.0f);

        // this descibes the Z axis bending
        double zmod[5][5][2][2] =
        {
            4, 5, 2, 3,	2, 3, 1, 2,	1, 2, 1, 2,	1, 2, 2, 3,	2, 3, 4, 5,
            3, 4, 1, 2,	1, 2, 0, 1,	0, 1, 0, 1,	0, 1, 1, 2,	1, 2, 3, 4,
            3, 3, 1, 1,	1, 1, 0, 0,	0, 0, 0, 0,	0, 0, 1, 1,	1, 1, 3, 3,
            4, 3, 2, 1,	2, 1, 1, 0,	1, 0, 1, 0,	1, 0, 2, 1,	2, 1, 4, 3,
            5, 4, 3, 2,	3, 2, 2, 1,	2, 1, 2, 1,	2, 1, 3, 2,	3, 2, 5, 4,
        };
        double z = thickness * (side == FRONT ? 1.0 : -1.0);
        glTranslatef(0.0, 0.0, - 5.0 * z);
        glBegin(GL_QUADS);
        for (int x = -2; x < 3; x++)
        {
            for (int y = -2; y < 3; y++)
            {
                glVertex3f(x * diff.x*2.0 + diff.x, y * diff.y*2.0 - diff.y, zmod[x+2][y+2][0][0] * z);
                glVertex3f(x * diff.x*2.0 - diff.x, y * diff.y*2.0 - diff.y, zmod[x+2][y+2][0][1] * z);
                glVertex3f(x * diff.x*2.0 - diff.x, y * diff.y*2.0 + diff.y, zmod[x+2][y+2][1][1] * z);
                glVertex3f(x * diff.x*2.0 + diff.x, y * diff.y*2.0 + diff.y, zmod[x+2][y+2][1][0] * z);
            }
        }
        glEnd();
        glDisable(GL_BLEND);

        glEndList();
    }
    glPushMatrix();
    glTranslatef(position.x, position.y, position.z);
    glCallList(displist);
    glPopMatrix();
}