Ejemplo n.º 1
0
//---------------------------------------------------------------------
float CBless::Render()
{
	int i = 0;

	float x = eSrc.x;
	float y = eSrc.y - 5;
	float z = eSrc.z;

	if (ulCurrentTime >= ulDuration)
	{
		return 0.f;
	}

	GRenderer->SetCulling(Renderer::CullNone);
	GRenderer->SetRenderState(Renderer::DepthWrite, false);
	GRenderer->SetRenderState(Renderer::AlphaBlending, true);

	TexturedVertex v[4];
	TexturedVertex v3[4];

	float ff = ((float)spells[spellinstance].caster_level + 10) * 6.f;
	float fBetaRadCos = (float) cos(radians(MAKEANGLE(player.angle.b))) * ff;
	float fBetaRadSin = (float) sin(radians(MAKEANGLE(player.angle.b))) * ff;

	ColorBGRA color = Color::white.toBGR();

	v[0].p.x = x - fBetaRadCos - fBetaRadSin;
	v[0].p.y = y;
	v[0].p.z = z - fBetaRadSin + fBetaRadCos;
	v[1].p.x = x + fBetaRadCos - fBetaRadSin;
	v[1].p.y = y;
	v[1].p.z = z + fBetaRadSin + fBetaRadCos;
	v[2].p.x = x - fBetaRadCos + fBetaRadSin;
	v[2].p.y = y;
	v[2].p.z = z - fBetaRadSin - fBetaRadCos;
	v[3].p.x = x + fBetaRadCos + fBetaRadSin;
	v[3].p.y = y;
	v[3].p.z = z + fBetaRadSin - fBetaRadCos;
	
	v3[0].color = color;
	v3[1].color = color;
	v3[2].color = color;
	v3[3].color = color;
	
	GRenderer->SetTexture(0, tex_sol);
	
	v3[0].uv = Vec2f::ZERO;
	v3[1].uv = Vec2f::X_AXIS;
	v3[2].uv = Vec2f::Y_AXIS;
	v3[3].uv = Vec2f::ONE;
	
	EE_RT2(&v[0], &v3[0]);
	EE_RT2(&v[1], &v3[1]);
	EE_RT2(&v[2], &v3[2]);
	EE_RT2(&v[3], &v3[3]);
	ARX_DrawPrimitive(&v3[0], &v3[1], &v3[2]);
	ARX_DrawPrimitive(&v3[1], &v3[2], &v3[3]);
	
	GRenderer->SetRenderState(Renderer::AlphaBlending, false);
	
	for(i = 0; i < 12; i++) {
		
		PARTICLE_DEF * pd = createParticle();
		if(!pd) {
			break;
		}
		
		pd->ov = eSrc - Vec3f(0.f, 20.f, 0.f);
		pd->move = Vec3f(3.f * frand2(), rnd() * 0.5f, 3.f * frand2());
		pd->siz = 0.005f;
		pd->tolive = Random::get(1000, 2000);
		pd->tc = tex_p1;
		pd->special = FADE_IN_AND_OUT | ROTATING | MODULATE_ROTATION | DISSIPATING;
		pd->fparam = 0.0000001f;
		pd->rgb = Color3f(0.7f, 0.6f, 0.2f);
	}
	
	GRenderer->SetCulling(Renderer::CullNone);
	GRenderer->SetRenderState(Renderer::DepthWrite, false);
	GRenderer->SetRenderState(Renderer::AlphaBlending, true);
	
	return 1;
}
Ejemplo n.º 2
0
float GetColorz(const Vec3f &pos) {

	ShaderLight lights[llightsSize];
	int lightsCount;
	UpdateLlights(lights, lightsCount, pos, true);
	
	Color3f ff = Color3f(0.f, 0.f, 0.f);
	
	for(long k = 0; k < lightsCount; k++) {
		const ShaderLight & light = lights[k];
		
		float dd = fdist(light.pos, pos);
		
		if(dd < light.fallend) {
			float dc;
			
			if(dd <= light.fallstart) {
				dc = light.intensity * GLOBAL_LIGHT_FACTOR;
			} else {
				float p = ((light.fallend - dd) * light.falldiffmul);
				
				if(p <= 0.f)
					dc = 0.f;
				else
					dc = p * light.intensity * GLOBAL_LIGHT_FACTOR;
			}
			
			dc *= 0.4f * 255.f;
			ff.r = std::max(ff.r, light.rgb.r * dc);
			ff.g = std::max(ff.g, light.rgb.g * dc);
			ff.b = std::max(ff.b, light.rgb.b * dc);
		}
	}


	EERIEPOLY * ep;
	float needy;
	ep = CheckInPoly(pos, &needy);

	if(ep != NULL) {
		Color3f _ff = Color3f(0.f, 0.f, 0.f);
		
		long to = (ep->type & POLY_QUAD) ? 4 : 3;
		float div = (1.0f / to);

		EP_DATA & epdata = portals->rooms[ep->room].epdata[0];
		ApplyTileLights(ep, epdata.p);

		for(long i = 0; i < to; i++) {
			Color col = Color::fromRGBA(ep->tv[i].color);
			_ff.r += float(col.r);
			_ff.g += float(col.g);
			_ff.b += float(col.b);
		}

		_ff.r *= div;
		_ff.g *= div;
		_ff.b *= div;
		float ratio, ratio2;
		ratio = glm::abs(needy - pos.y) * ( 1.0f / 300 );
		ratio = (1.f - ratio);
		ratio2 = 1.f - ratio;
		ff.r = ff.r * ratio2 + _ff.r * ratio;
		ff.g = ff.g * ratio2 + _ff.g * ratio;
		ff.b = ff.b * ratio2 + _ff.b * ratio;
	}

	return (std::min(ff.r, 255.f) + std::min(ff.g, 255.f) + std::min(ff.b, 255.f)) * (1.f/3);
}
Ejemplo n.º 3
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

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

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

    // Make Torus Node (creates Torus in background of scene)
    NodeRefPtr TorusGeometryNode = makeTorus(.5, 2, 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();

    GradientBackgroundRefPtr TheBackground = GradientBackground::create();
    TheBackground->addLine(Color3f(1.0,0.0,0.0), 0.0);
    TheBackground->addLine(Color3f(0.0,1.0,0.0), 0.2);
    TheBackground->addLine(Color3f(0.0,0.0,1.0), 0.4);
    TheBackground->addLine(Color3f(0.0,1.0,1.0), 0.6);
    TheBackground->addLine(Color3f(1.0,1.0,0.0), 0.8);
    TheBackground->addLine(Color3f(1.0,1.0,1.0), 1.0);

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

            Create a List.  A List has several 
			parts to it:
			-ListModel: Contains the data which is to be
			    displayed in the List.  Data is added
				as shown below
			-ListCellRenderer: Creates the Components to
				be used within the List (the default
				setting is to create Labels using 
				the desired text).
			-ListSelectionModel: Determines how
				the List may be selected.

			To add values to the list:
            
            First, create SFStrings and use the 
            .setValue("Value") function to set their
            values.  Then, use the .pushBack(&SFStringName)
            to add them to the List.

            Next, create the CellRenderer and ListSelectionModel
            defaults.

            Finally, actually create the List.  Set
            its Model, CellRenderer, and SelectionModel
            as shown below.  Finally, choose the
            type of display for the List (choices outlined
            below).

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

    // Add data to it
	ExampleListModel = MFieldListModel::create();
    ExampleListModel->setContainer(TheBackground);
    ExampleListModel->setFieldId(GradientBackground::ColorFieldId);

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

            Create ListCellRenderer and 
			ListSelectionModel.  Most 
			often the defauls will be used.
			
			Note: the ListSelectionModel was
			created above and is referenced
			by the ActionListeners.

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


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

            Create List itself and assign its 
			Model, CellRenderer, and SelectionModel
			to it.
			-setOrientation(ENUM): Determine the
				Layout of the cells (Horizontal
				or Vertical).  Takes List::VERTICAL_ORIENTATION
				and List::HORIZONTAL_ORIENTATION arguments.

    ******************************************************/    
    ExampleList = List::create();
        ExampleList->setPreferredSize(Vec2f(200, 300));
        ExampleList->setOrientation(List::VERTICAL_ORIENTATION);
        //ExampleList->setOrientation(List::HORIZONTAL_ORIENTATION);
		ExampleList->setModel(ExampleListModel);

    ExampleList->setSelectionModel(ExampleListSelectionModel);


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

            Determine the SelectionModel
            -SINGLE_SELECTION lets you select ONE item
                via a single mouse click
            -SINGLE_INTERVAL_SELECTION lets you select
                one interval via mouse and SHIFT key
            -MULTIPLE_INTERVAL_SELECTION lets you select
                via mouse, and SHIFT and CONTRL keys

            Note: this tutorial is currently set up
            to allow for this to be changed via 
			TogggleButtons with ActionListeners attached 
            to them so this code is commented out.

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

    //SelectionModel.setMode(DefaultListSelectionModel::SINGLE_SELECTION);
    //SelectionModel.setMode(DefaultListSelectionModel::SINGLE_INTERVAL_SELECTION);
    //SelectionModel.setMode(DefaultListSelectionModel::MULTIPLE_INTERVAL_SELECTION);

    // Create a ScrollPanel for easier viewing of the List (see 27ScrollPanel)
    ScrollPanelRefPtr ExampleScrollPanel = ScrollPanel::create();
        ExampleScrollPanel->setPreferredSize(Vec2f(200,300));
        ExampleScrollPanel->setHorizontalResizePolicy(ScrollPanel::RESIZE_TO_VIEW);
        //ExampleScrollPanel->setVerticalResizePolicy(ScrollPanel::RESIZE_TO_VIEW);
    ExampleScrollPanel->setViewComponent(ExampleList);

    // Create MainFramelayout
    FlowLayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();
    MainInternalWindowLayout->setOrientation(FlowLayout::VERTICAL_ORIENTATION);
    MainInternalWindowLayout->setMajorAxisAlignment(0.5f);
    MainInternalWindowLayout->setMinorAxisAlignment(0.5f);

    LabelRefPtr ListLabel = Label::create();
    ListLabel->setText("Background Colors List");
    ListLabel->setPreferredSize(Vec2f(200.0f, ListLabel->getPreferredSize().y()));

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

    InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
    MainInternalWindow->pushToChildren(ListLabel);
    MainInternalWindow->pushToChildren(ExampleScrollPanel);
    MainInternalWindow->setLayout(MainInternalWindowLayout);
    MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
    MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
    MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.7f,0.5f));
    MainInternalWindow->setDrawTitlebar(false);
    MainInternalWindow->setResizable(false);

    // Create the Drawing Surface
    UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindow);
    
	TutorialDrawingSurface->openWindow(MainInternalWindow);

    // Create the UI Foreground Object
    UIForegroundRefPtr TutorialUIForeground = OSG::UIForeground::create();

        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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

    // Add the UI Foreground Object to the Scene
    ViewportRefPtr TutorialViewport = mgr->getWindow()->getPort(0);
    TutorialViewport->addForeground(TutorialUIForeground);
    TutorialViewport->setBackground(TheBackground);

    // 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,
            "44MFieldList");

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

    osgExit();

    return 0;
}
Ejemplo n.º 4
0
void IceFieldSpell::Update(float timeDelta) {
	
	ARX_UNUSED(timeDelta);
	
	if(!lightHandleIsValid(m_light))
		m_light = GetFreeDynLight();

	if(lightHandleIsValid(m_light)) {
		EERIE_LIGHT * el = lightHandleGet(m_light);
		
		el->pos = m_pos + Vec3f(0.f, -120.f, 0.f);
		el->intensity = 4.6f;
		el->fallstart = 150.f+rnd()*30.f;
		el->fallend   = 290.f+rnd()*30.f;
		el->rgb = Color3f(0.76f, 0.76f, 1.0f) + Color3f(0.f, 0.f, -rnd()*(1.0f/10));
		el->duration = 600;
		el->extras=0;
	}

	if(!VisibleSphere(Sphere(m_pos - Vec3f(0.f, 120.f, 0.f), 350.f)))
		return;
	
	RenderMaterial mat;
	mat.setDepthTest(true);
	mat.setBlendType(RenderMaterial::Additive);
	
	for(int i = 0; i < iMax; i++) {
		
		tSize[i] += Vec3f(0.1f);
		tSize[i] = glm::min(tSize[i], tSizeMax[i]);
		
		Anglef stiteangle = Anglef::ZERO;
		Vec3f stitepos;
		Vec3f stitescale;
		Color3f stitecolor;

		stiteangle.setPitch(glm::cos(glm::radians(tPos[i].x)) * 360);
		stitepos.x = tPos[i].x;
		stitepos.y = m_pos.y;
		stitepos.z = tPos[i].z;
		
		stitecolor.r = tSizeMax[i].y * 0.7f;
		stitecolor.g = tSizeMax[i].y * 0.7f;
		stitecolor.b = tSizeMax[i].y * 0.9f;

		if(stitecolor.r > 1)
			stitecolor.r = 1;

		if(stitecolor.g > 1)
			stitecolor.g = 1;

		if(stitecolor.b > 1)
			stitecolor.b = 1;

		stitescale.z = tSize[i].x;
		stitescale.y = tSize[i].y;
		stitescale.x = tSize[i].z;

		EERIE_3DOBJ * obj = (tType[i] == 0) ? smotte : stite;
		
		Draw3DObject(obj, stiteangle, stitepos, stitescale, stitecolor, mat);
	}
	
	for(int i = 0; i < iMax * 0.5f; i++) {
		
		float t = rnd();
		if(t < 0.01f) {
			
			PARTICLE_DEF * pd = createParticle();
			if(pd) {
				pd->ov = tPos[i] + randomVec(-5.f, 5.f);
				pd->move = randomVec(-2.f, 2.f);
				pd->siz = 20.f;
				pd->tolive = Random::get(2000, 6000);
				pd->tc = tex_p2;
				pd->special = FADE_IN_AND_OUT | ROTATING | MODULATE_ROTATION | DISSIPATING;
				pd->fparam = 0.0000001f;
				pd->rgb = Color3f(0.7f, 0.7f, 1.f);
			}
			
		} else if (t > 0.095f) {
			
			PARTICLE_DEF * pd = createParticle();
			if(pd) {
				pd->ov = tPos[i] + randomVec(-5.f, 5.f) + Vec3f(0.f, 50.f, 0.f);
				pd->move = Vec3f(0.f, 2.f - 4.f * rnd(), 0.f);
				pd->siz = 0.5f;
				pd->tolive = Random::get(2000, 6000);
				pd->tc = tex_p1;
				pd->special = FADE_IN_AND_OUT | ROTATING | MODULATE_ROTATION | DISSIPATING;
				pd->fparam = 0.0000001f;
				pd->rgb = Color3f(0.7f, 0.7f, 1.f);
			}
			
		}
	}
}
Ejemplo n.º 5
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        TheLuaManager->init();

        // 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);

        //Setup the Lua Manager

        BoostPath ModulePath("./Data/");
        std::string PackagePath = std::string("?;")
            + (ModulePath / "?.lua" ).file_string() + ";"
            + (ModulePath / "?" /  "init.lua").file_string();
        TheLuaManager->setPackagePath(PackagePath);

        // Make Torus Node (creates Torus in background of scene)
        GeometryRefPtr TorusGeometry = makeTorusGeo(.5, 2, 16, 16);
        setName(TorusGeometry,"Torus Geometry");
        //calcVertexTangents(TorusGeometry,0,Geometry::TexCoords7FieldId, Geometry::TexCoords6FieldId);


        NodeRefPtr TorusGeometryNode = Node::create();
        setName(TorusGeometryNode,"Torus Geometry Node");
        TorusGeometryNode->setCore(TorusGeometry);

        //Torus Transformation Node
        TransformRefPtr TheTorusNodeTransform = Transform::create();

        NodeRefPtr TheTorusTransfromNode = Node::create();
        TheTorusTransfromNode->setCore(TheTorusNodeTransform);
        TheTorusTransfromNode->addChild(TorusGeometryNode);
        setName(TheTorusTransfromNode,"Torus Transform Node");

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

        //Light Beacon Node
        TransformRefPtr TheLightBeaconNodeTransform = Transform::create();

        NodeRefPtr TheLightBeaconNode = Node::create();
        TheLightBeaconNode->setCore(TheLightBeaconNodeTransform);
        setName(TheLightBeaconNode,"Light Beacon Node");


        //Light Node
        DirectionalLightRefPtr TheLightCore = DirectionalLight::create();
        TheLightCore->setDirection(Vec3f(1.0,0.0,0.0));
        TheLightCore->setAmbient(Color4f(1.0,1.0,1.0,1.0));
        TheLightCore->setDiffuse(Color4f(1.0,1.0,1.0,1.0));
        TheLightCore->setSpecular(Color4f(1.0,1.0,1.0,1.0));
        TheLightCore->setBeacon(TheLightBeaconNode);

        NodeRefPtr TheLightNode = Node::create();
        TheLightNode->setCore(TheLightCore);
        TheLightNode->addChild(scene);
        setName(TheLightNode,"Light Node");

        NodeRefPtr RootNode = Node::create();
        RootNode->setCore(Group::create());
        RootNode->addChild(TheLightNode);
        RootNode->addChild(TheLightBeaconNode);
        setName(RootNode,"Root Node");

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

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

        //Create the Main interface
        LuaDebuggerInterface TheLuaDebuggerInterface;

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

        BorderLayoutRefPtr MainInternalWindowLayout = BorderLayout::create();

        //Split Panel
        BorderLayoutConstraintsRefPtr SplitPanelConstraints = BorderLayoutConstraints::create();
        SplitPanelConstraints->setRegion(BorderLayoutConstraints::BORDER_CENTER);
        TheLuaDebuggerInterface.getMainSplitPanel()->setConstraints(SplitPanelConstraints);

        BorderLayoutConstraintsRefPtr ButtonPanelConstraints = BorderLayoutConstraints::create();
        ButtonPanelConstraints->setRegion(BorderLayoutConstraints::BORDER_NORTH);
        TheLuaDebuggerInterface.getButtonPanel()->setConstraints(ButtonPanelConstraints);

        BorderLayoutConstraintsRefPtr CodeAreaInfoPanelConstraints = BorderLayoutConstraints::create();
        CodeAreaInfoPanelConstraints->setRegion(BorderLayoutConstraints::BORDER_SOUTH);
        TheLuaDebuggerInterface.getCodeAreaInfoPanel()->setConstraints(CodeAreaInfoPanelConstraints);

        InternalWindowRefPtr MainInternalWindow = InternalWindow::create();
        MainInternalWindow->pushToChildren(TheLuaDebuggerInterface.getButtonPanel());
        MainInternalWindow->pushToChildren(TheLuaDebuggerInterface.getMainSplitPanel());
        MainInternalWindow->pushToChildren(TheLuaDebuggerInterface.getCodeAreaInfoPanel());
        MainInternalWindow->setLayout(MainInternalWindowLayout);
        MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
        MainInternalWindow->setTitle("Lua Debugger");
        setName(MainInternalWindow,"Internal Window");

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

        TutorialDrawingSurface->openWindow(MainInternalWindow);

        // Create the UI Foreground Object
        UIForegroundRefPtr TutorialUIForeground = UIForeground::create();

        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);

        //Scene Background
        GradientBackgroundRefPtr SceneBackground = GradientBackground::create();
        SceneBackground->addLine(Color3f(0.0,0.0,0.0),0.0);
        setName(SceneBackground,"Scene Background");

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);
        sceneManager.setRoot(RootNode);
        //sceneManager.setHeadlight(false);

        // Add the UI Foreground Object to the Scene
        ViewportRefPtr TutorialViewport = sceneManager.getWindow()->getPort(0);
        TutorialViewport->addForeground(TutorialUIForeground);
        TutorialViewport->setBackground(SceneBackground);

        TutorialWindow->connectKeyTyped(boost::bind(keyTyped,
                                                    _1,
                                                    &TheLuaDebuggerInterface));

        // 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,
                                   "03LuaDebugger");

        MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
        MainInternalWindow->setPreferredSize(WinSize * 0.85);

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

        TheLuaManager->uninit();
    }

    osgExit();

    return 0;
}
Ejemplo n.º 6
0
Color3f Color3f::operator+(const Color3f& right) const{
	return(Color3f(red+right.red, green+right.green, blue+right.blue));
}
Ejemplo n.º 7
0
Color3f operator/(Color3f const& lhs, float rhs) {
  return Color3f(lhs.r() / rhs, lhs.g() / rhs, lhs.b() / rhs);
}
Ejemplo n.º 8
0
void NPC::setTShirtColor(float red, float green, float blue) {
	_tShirtColor = Color3f(red, green, blue);
}
Ejemplo n.º 9
0
// Initialize GLUT & OpenSG and set up the rootNode
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));
        TutorialWindow->connectKeyReleased(boost::bind(keyReleased, _1));

        //Make Main Scene Node
        NodeRefPtr scene = makeCoredNode<Group>();
        setName(scene, "scene");
        NodeRecPtr rootNode = Node::create();
        setName(rootNode, "rootNode");
        ComponentTransformRefPtr Trans = ComponentTransform::create();
        rootNode->setCore(Trans);
        rootNode->addChild(scene);

        //Light Beacon
        Matrix LightTransformMat;
        LightTransformMat.setTranslate(Vec3f(50.0,0.0,100.0));

        TransformRefPtr LightTransform = Transform::create();
        LightTransform->setMatrix(LightTransformMat);

        NodeRefPtr TutorialLightBeacon = Node::create();
        TutorialLightBeacon->setCore(LightTransform);

        //Light Node
        PointLightRefPtr TutorialLight = PointLight::create();
        TutorialLight->setBeacon(TutorialLightBeacon);

        NodeRefPtr TutorialLightNode = Node::create();
        TutorialLightNode->setCore(TutorialLight);

        scene->addChild(TutorialLightNode);
        scene->addChild(TutorialLightBeacon);


        //Setup Physics Scene
        PhysicsWorldRecPtr physicsWorld = PhysicsWorld::create();
        physicsWorld->setWorldContactSurfaceLayer(0.005);
        physicsWorld->setAutoDisableFlag(1);
        physicsWorld->setAutoDisableTime(0.75);
        physicsWorld->setWorldContactMaxCorrectingVel(100.0);
        physicsWorld->setGravity(Vec3f(0.0, 0.0, -9.81));

        PhysicsHashSpaceRecPtr physicsSpace = PhysicsHashSpace::create();

        //Setup the default collision parameters
        CollisionContactParametersRefPtr DefaultCollisionParams = CollisionContactParameters::createEmpty();
        DefaultCollisionParams->setMode(dContactApprox1);
        DefaultCollisionParams->setMu(1.0);
        DefaultCollisionParams->setMu2(0.0);
        DefaultCollisionParams->setBounce(0.0);
        DefaultCollisionParams->setBounceSpeedThreshold(0.0);
        DefaultCollisionParams->setSoftCFM(0.1);
        DefaultCollisionParams->setSoftERP(0.2);
        DefaultCollisionParams->setMotion1(0.0);
        DefaultCollisionParams->setMotion2(0.0);
        DefaultCollisionParams->setMotionN(0.0);
        DefaultCollisionParams->setSlip1(0.0);
        DefaultCollisionParams->setSlip2(0.0);

        physicsSpace->setDefaultCollisionParameters(DefaultCollisionParams);

        PhysicsHandlerRecPtr physHandler = PhysicsHandler::create();
        physHandler->setWorld(physicsWorld);
        physHandler->pushToSpaces(physicsSpace);
        physHandler->setUpdateNode(rootNode);
        physHandler->attachUpdateProducer(TutorialWindow);

        rootNode->addAttachment(physHandler);    
        rootNode->addAttachment(physicsWorld);
        rootNode->addAttachment(physicsSpace);


        /************************************************************************/
        /* create spaces, geoms and bodys                                                                     */
        /************************************************************************/
        //create a group for our space
        GroupRefPtr spaceGroup;
        NodeRecPtr spaceGroupNode = makeCoredNode<Group>(&spaceGroup);

        //create the ground terrain
        GeometryRefPtr TerrainGeo = buildTerrain(Vec2f(400.0,400.0),25,25);

        //and its Material
        SimpleMaterialRefPtr TerrainMat = SimpleMaterial::create();
        TerrainMat->setAmbient(Color3f(0.3,0.5,0.3));
        TerrainMat->setDiffuse(Color3f(0.5,0.9,0.5));
        TerrainGeo->setMaterial(TerrainMat);

        NodeRefPtr TerrainNode = Node::create();
        TerrainNode->setCore(TerrainGeo);


        //create ODE data
        PhysicsGeomRefPtr TerrainODEGeom = PhysicsTriMeshGeom::create();

        //add geom to space for collision
        TerrainODEGeom->setSpace(physicsSpace);
        //set the geometryNode to fill the ode-triMesh
        dynamic_pointer_cast<PhysicsTriMeshGeom>(TerrainODEGeom)->setGeometryNode(TerrainNode);

        //add attachments
        //add Attachments to nodes...
        spaceGroupNode->addAttachment(physicsSpace);
        spaceGroupNode->addChild(TerrainNode);

        TerrainNode->addAttachment(TerrainODEGeom);

        TutorialLightNode->addChild(spaceGroupNode);

        //Create Character
        PhysicsBodyRefPtr CharacterPhysicsBody = buildCharacter(Vec3f(5.0,5.0,10.0),
                                                                Pnt3f((Real32)(rand()%100)-50.0,(Real32)(rand()%100)-50.0,25.0),
                                                                spaceGroupNode,
                                                                physicsWorld,
                                                                physicsSpace);

        PhysicsLMotorJointRefPtr CharacterMover = buildMover(CharacterPhysicsBody);

        TutorialWindow->connectKeyPressed(boost::bind(keyPressed, _1,
                                                      spaceGroupNode.get(),
                                                      physicsWorld.get(),
                                                      physicsSpace.get()));

        TutorialWindow->connectUpdate(boost::bind(handleUpdate, _1,
                                                  CharacterPhysicsBody.get(),
                                                  CharacterMover.get()));

        // tell the manager what to manage
        sceneManager.setRoot  (rootNode);

        // show the whole rootNode
        sceneManager.showAll();

        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "03CharacterTerrain");

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

    osgExit();

    return 0;
}
Ejemplo n.º 10
0
void AddFlare(const Vec2s & pos, float sm, short typ, Entity * io, bool bookDraw) {
	
	int oldest = 0;
	size_t i;
	for(i = 0; i < MAX_FLARES; i++) {
		if(!magicFlares[i].exist) {
			break;
		}
		if(magicFlares[i].tolive < magicFlares[oldest].tolive) {
			oldest = i;
		}
	}
	if(i >= MAX_FLARES) {
		removeFlare(magicFlares[oldest]);
		i = oldest;
	}

	FLARES * fl = &magicFlares[i];
	fl->exist = 1;
	flarenum++;

	if(!bookDraw)
		fl->bDrawBitmap = 0;
	else
		fl->bDrawBitmap = 1;

	fl->io = io;
	if(io) {
		fl->flags = 1;
		io->flarecount++;
	} else {
		fl->flags = 0;
	}

	fl->pos.x = float(pos.x) - rnd() * 4.f;
	fl->pos.y = float(pos.y) - rnd() * 4.f - 50.f;
	fl->tv.rhw = fl->v.rhw = 1.f;

	if(!bookDraw) {
		EERIE_CAMERA ka = *Kam;
		ka.angle = Anglef(360.f, 360.f, 360.f) - ka.angle;
		EERIE_CAMERA * oldcam = ACTIVECAM;
		SetActiveCamera(&ka);
		PrepareCamera(&ka, g_size);
		fl->v.p += ka.orgTrans.pos;
		EE_RTP(fl->tv.p, &fl->v);
		fl->v.p += ka.orgTrans.pos;

		float vx = -(fl->pos.x - subj.center.x) * 0.2173913f;
		float vy = (fl->pos.y - subj.center.y) * 0.1515151515151515f;
		if(io) {
			fl->v.p = io->pos;
			fl->v.p += angleToVectorXZ(io->angle.getPitch() + vx) * 100.f;
			fl->v.p.y += std::sin(glm::radians(MAKEANGLE(io->angle.getYaw() + vy))) * 100.f - 150.f;
		} else {
			fl->v.p.x = 1.0f  * float(pos.x - (g_size.width()  / 2)) * 156.f / (640.f * g_sizeRatio.y);
			fl->v.p.y = 0.75f * float(pos.y - (g_size.height() / 2)) * 156.f / (480.f * g_sizeRatio.y);
			fl->v.p.z = 75.f;
			ka = *oldcam;
			SetActiveCamera(&ka);
			PrepareCamera(&ka, g_size);
			float temp = (fl->v.p.y * -ka.orgTrans.xsin) + (fl->v.p.z * ka.orgTrans.xcos);
			fl->v.p.y = (fl->v.p.y * ka.orgTrans.xcos) - (-fl->v.p.z * ka.orgTrans.xsin);
			fl->v.p.z = (temp * ka.orgTrans.ycos) - (-fl->v.p.x * ka.orgTrans.ysin);
			fl->v.p.x = (temp * -ka.orgTrans.ysin) + (fl->v.p.x * ka.orgTrans.ycos);
			fl->v.p += oldcam->orgTrans.pos;
		}
		fl->tv.p = fl->v.p;
		SetActiveCamera(oldcam);
		PrepareCamera(oldcam, g_size);
	} else {
		fl->tv.p = Vec3f(fl->pos.x, fl->pos.y, 0.001f);
	}

	switch(PIPOrgb) {
		case 0: {
			fl->rgb = Color3f(.4f, 0.f, .4f) + Color3f(2.f/3, 2.f/3, 2.f/3) * randomColor3f();
			break;
		}
		case 1: {
			fl->rgb = Color3f(.5f, .5f, 0.f) + Color3f(.625f, .625f, .55f) * randomColor3f();
			break;
		}
		case 2: {
			fl->rgb = Color3f(.4f, 0.f, 0.f) + Color3f(2.f/3, .55f, .55f) * randomColor3f();
			break;
		}
	}

	if(typ == -1) {
		float zz = eeMousePressed1() ? 0.29f : ((sm > 0.5f) ? rnd() : 1.f);
		if(zz < 0.2f) {
			fl->type = 2;
			fl->size = rnd() * 42.f + 42.f;
			fl->tolive = (800.f + rnd() * 800.f) * FLARE_MUL;
		} else if(zz < 0.5f) {
			fl->type = 3;
			fl->size = rnd() * 52.f + 16.f;
			fl->tolive = (800.f + rnd() * 800.f) * FLARE_MUL;
		} else {
			fl->type = 1;
			fl->size = (rnd() * 24.f + 32.f) * sm;
			fl->tolive = (1700.f + rnd() * 500.f) * FLARE_MUL;
		}
	} else {
		fl->type = (rnd() > 0.8f) ? 1 : 4;
		fl->size = (rnd() * 38.f + 64.f) * sm;
		fl->tolive = (1700.f + rnd() * 500.f) * FLARE_MUL;
	}

	fl->dynlight = LightHandle::Invalid;

	for(long kk = 0; kk < 3; kk++) {

		if(rnd() < 0.5f) {
			continue;
		}

		PARTICLE_DEF * pd = createParticle();
		if(!pd) {
			break;
		}

		if(!bookDraw) {
			pd->special = FADE_IN_AND_OUT | ROTATING | MODULATE_ROTATION | DISSIPATING;
			if(!io) {
				pd->special |= PARTICLE_NOZBUFFER;
			}
		} else {
			pd->special = FADE_IN_AND_OUT;
		}

		pd->ov = fl->v.p + randomVec(-5.f, 5.f);
		pd->move = Vec3f(0.f, 5.f, 0.f);
		pd->scale = Vec3f(-2.f);
		pd->tolive = 1300 + kk * 100 + Random::get(0, 800);
		pd->tc = fire2;
		if(kk == 1) {
			pd->move.y = 4.f;
			pd->siz = 1.5f;
		} else {
			pd->siz = 1.f + rnd();
		}
		pd->rgb = Color3f(fl->rgb.r * (2.f/3), fl->rgb.g * (2.f/3), fl->rgb.b * (2.f/3));
		pd->fparam = 1.2f;

		if(bookDraw)
			pd->is2D = true;
	}
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init
    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    glutCreateWindow("OpenSG");

    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    PassiveWindowPtr pwin=PassiveWindow::create();
    pwin->init();

    // create the scene
    NodePtr scene;

    scene = Node::create();

    // create the material

    // Pass 1: Simple red, shiny, depth-tested

    DepthChunkPtr cl1 = DepthChunk::create();
    beginEditCP(cl1);
    cl1->setEnable(true);
    cl1->setFunc(GL_LEQUAL);
    endEditCP(cl1);

    SimpleMaterialPtr mat = SimpleMaterial::create();
    beginEditCP(mat);
    mat->setDiffuse(Color3f(1,0,0));
    mat->setSpecular(Color3f(.9,.9,.9));
    mat->setShininess(30);
    mat->setLit(true);
    mat->addChunk(cl1);
    endEditCP(mat);

    // Pass 2: Green unlit, without depth testing

    DepthChunkPtr cl2 = DepthChunk::create();
    beginEditCP(cl2);
    cl2->setEnable(false);
    endEditCP(cl2);

    SimpleMaterialPtr mat2 = SimpleMaterial::create();
    beginEditCP(mat2);
    mat2->setDiffuse(Color3f(0,1,0));
    mat2->setLit(false);
    mat2->setTransparency(.8);
    mat2->addChunk(cl2);
    endEditCP(mat2);

    // Bring them together

    MultiPassMaterialPtr mpm = MultiPassMaterial::create();

    beginEditCP(mpm);
    mpm->editMFMaterials()->push_back(mat);
    mpm->editMFMaterials()->push_back(mat2);
    endEditCP(mpm);

    GeometryPtr g1 = makeTorusGeo(0.2, 2, 8, 16);

    beginEditCP(scene);
    scene->setCore(g1);
    endEditCP(scene);

    beginEditCP(g1);

    g1->setMaterial(mpm);

    endEditCP(g1);

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // create the window and initial camera/viewport
    mgr->setWindow(pwin );
    // tell the manager what to manage
    mgr->setRoot  (scene);

    // show the whole scene
    mgr->showAll();
    mgr->redraw();

    // GLUT main loop
    glutMainLoop();

    return 0;
}
Ejemplo n.º 12
0
bool vtkOsgConverter::WriteAnActor()
{
	vtkMapper* actorMapper = _actor->GetMapper();
	// see if the actor has a mapper. it could be an assembly
	if (actorMapper == NULL)
		return false;
	// dont export when not visible
	if (_actor->GetVisibility() == 0)
		return false;

	vtkDataObject* inputDO = actorMapper->GetInputDataObject(0, 0);
	if (inputDO == NULL)
		return false;

	// Get PolyData. Convert if necessary becasue we only want polydata
	vtkSmartPointer<vtkPolyData> pd;
	if(inputDO->IsA("vtkCompositeDataSet"))
	{
		vtkCompositeDataGeometryFilter* gf = vtkCompositeDataGeometryFilter::New();
		gf->SetInput(inputDO);
		gf->Update();
		pd = gf->GetOutput();
		gf->Delete();
	}
	else if(inputDO->GetDataObjectType() != VTK_POLY_DATA)
	{
		vtkGeometryFilter* gf = vtkGeometryFilter::New();
		gf->SetInput(inputDO);
		gf->Update();
		pd = gf->GetOutput();
		gf->Delete();
	}
	else
		pd = static_cast<vtkPolyData*>(inputDO);

	// Get the color range from actors lookup table
	double range[2];
	vtkLookupTable* actorLut = static_cast<vtkLookupTable*>(actorMapper->GetLookupTable());
	actorLut->GetTableRange(range);

	// Copy mapper to a new one
	vtkPolyDataMapper* pm = vtkPolyDataMapper::New();
	// Convert cell data to point data
	// NOTE: Comment this out to export a mesh
	if (actorMapper->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_DATA ||
		actorMapper->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)
	{
		vtkCellDataToPointData* cellDataToPointData = vtkCellDataToPointData::New();
		cellDataToPointData->PassCellDataOff();
		cellDataToPointData->SetInput(pd);
		cellDataToPointData->Update();
		pd = cellDataToPointData->GetPolyDataOutput();
		cellDataToPointData->Delete();

		pm->SetScalarMode(VTK_SCALAR_MODE_USE_POINT_DATA);
	}
	else
		pm->SetScalarMode(actorMapper->GetScalarMode());

	pm->SetInput(pd);
	pm->SetScalarVisibility(actorMapper->GetScalarVisibility());

	vtkLookupTable* lut = NULL;
	// ParaView OpenSG Exporter
	if (dynamic_cast<vtkDiscretizableColorTransferFunction*>(actorMapper->GetLookupTable()))
		lut = actorLut;
	// Clone the lut in OGS because otherwise the original lut gets destroyed
	else
	{
		lut = vtkLookupTable::New();
		lut->DeepCopy(actorLut);
		lut->Build();
	}
	pm->SetLookupTable(lut);
	pm->SetScalarRange(range);
	pm->Update();

	if(pm->GetScalarMode() == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA ||
	   pm->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
	{
		if(actorMapper->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID )
			pm->ColorByArrayComponent(actorMapper->GetArrayId(),
			                          actorMapper->GetArrayComponent());
		else
			pm->ColorByArrayComponent(actorMapper->GetArrayName(),
			                          actorMapper->GetArrayComponent());
	}


	vtkPointData* pntData = pd->GetPointData();
	bool hasTexCoords = false;
	vtkUnsignedCharArray* vtkColors = pm->MapScalars(1.0);

	// ARRAY SIZES
	vtkIdType m_iNumPoints = pd->GetNumberOfPoints();
	if (m_iNumPoints == 0)
		return false;
	vtkIdType m_iNumGLPoints = pd->GetVerts()->GetNumberOfCells();
	vtkIdType m_iNumGLLineStrips = pd->GetLines()->GetNumberOfCells();
	vtkIdType m_iNumGLPolygons = pd->GetPolys()->GetNumberOfCells();
	vtkIdType m_iNumGLTriStrips = pd->GetStrips()->GetNumberOfCells();
	vtkIdType m_iNumGLPrimitives = m_iNumGLPoints + m_iNumGLLineStrips + m_iNumGLPolygons +
	                               m_iNumGLTriStrips;
	bool lit = !(m_iNumGLPolygons == 0 && m_iNumGLTriStrips == 0);

	if (_verbose)
	{
		std::cout << "Array sizes:" << std::endl;
		std::cout << "  number of vertices: " << m_iNumPoints << std::endl;
		std::cout << "  number of GL_POINTS: " << m_iNumGLPoints << std::endl;
		std::cout << "  number of GL_LINE_STRIPS: " << m_iNumGLLineStrips << std::endl;
		std::cout << "  number of GL_POLYGON's: " << m_iNumGLPolygons << std::endl;
		std::cout << "  number of GL_TRIANGLE_STRIPS: " << m_iNumGLTriStrips << std::endl;
		std::cout << "  number of primitives: " << m_iNumGLPrimitives << std::endl;
	}

	// NORMALS
	vtkDataArray* vtkNormals = NULL;
	int m_iNormalType = NOT_GIVEN;
	if (_actor->GetProperty()->GetInterpolation() == VTK_FLAT)
	{
		vtkNormals = pd->GetCellData()->GetNormals();
		if (vtkNormals != NULL)
			m_iNormalType = PER_CELL;
	}
	else
	{
		vtkNormals = pntData->GetNormals();
		if (vtkNormals != NULL)
			m_iNormalType = PER_VERTEX;
	}
	if (_verbose)
	{
		std::cout << "Normals:" << std::endl;
		if (m_iNormalType != NOT_GIVEN)
		{
			std::cout << "  number of normals: " << vtkNormals->GetNumberOfTuples() <<
			std::endl;
			std::cout << "  normals are given: ";
			std::cout <<
			((m_iNormalType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl;
		}
		else
			std::cout << "  no normals are given" << std::endl;
	}

	// COLORS
	int m_iColorType = NOT_GIVEN;
	if(pm->GetScalarVisibility())
	{
		int iScalarMode = pm->GetScalarMode();
		if(vtkColors == NULL)
		{
			m_iColorType = NOT_GIVEN;
			std::cout << "WARNING: MapScalars(1.0) did not return array!" << std::endl;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA)
			m_iColorType = PER_CELL;
		else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA)
			m_iColorType = PER_VERTEX;
		else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)
		{
			std::cout <<
			"WARNING TO BE REMOVED: Can not process colours with scalar mode using cell field data!"
			          << std::endl;
			m_iColorType = PER_CELL;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA)
		{
			std::cout <<
			"WARNING TO BE REMOVED: Can not process colours with scalar mode using point field data!"
			          << std::endl;
			m_iColorType = PER_VERTEX;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_DEFAULT)
		{
			//Bummer, we do not know what it is. may be we can make a guess
			int numColors = vtkColors->GetNumberOfTuples();
			if (numColors == 0)
			{
				m_iColorType = NOT_GIVEN;
				std::cout << "WARNING: No colors found!" << std::endl;
			}
			else if (numColors == m_iNumPoints)
				m_iColorType = PER_VERTEX;
			else if (numColors == m_iNumGLPrimitives)
				m_iColorType = PER_CELL;
			else
			{
				m_iColorType = NOT_GIVEN;
				std::cout <<
				"WARNING: Number of colors do not match number of points / cells!"
				          << std::endl;
			}
		}
	}
	if (_verbose)
	{
		std::cout << "Colors:" << std::endl;
		if (m_iColorType != NOT_GIVEN)
		{
			std::cout << "  number of colors: " << vtkColors->GetNumberOfTuples() <<
			std::endl;
			std::cout << "  colors are given: " <<
			((m_iColorType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl;
		}
		else
			std::cout << "  no colors are given" << std::endl;
	}

	// TEXCOORDS
	vtkDataArray* vtkTexCoords = pntData->GetTCoords();
	if (_verbose)
	{
		std::cout << "Tex-coords:" << std::endl;
		if (vtkTexCoords)
		{
			std::cout << "  Number of tex-coords: " <<
			vtkTexCoords->GetNumberOfTuples() << std::endl;
			hasTexCoords = true;
		}
		else
			std::cout << "  No tex-coords where given" << std::endl;
	}

	// TRANSFORMATION
	double scaling[3];
	double translation[3];
	// double rotation[3];

	_actor->GetPosition(translation);
	_actor->GetScale(scaling);
	//_actor->GetRotation(rotation[0], rotation[1], rotation[2]);

	if (_verbose)
		std::cout << "set scaling: " << scaling[0] << " " << scaling[1] << " " <<
		scaling[2] << std::endl;

	osg::Matrix m;
	m.setIdentity();
	m.setTranslate(translation[0], translation[1], translation[2]);
	m.setScale(scaling[0], scaling[1], scaling[2]);
	// TODO QUATERNION m.setRotate(rotation[0], rotation[1], rotation[2])
	beginEditCP(_osgTransform);
	_osgTransform->setMatrix(m);
	endEditCP(_osgTransform);

	//pm->Update();

	// Get the converted OpenSG node
	NodePtr osgGeomNode = Node::create();
	GeometryPtr osgGeometry = Geometry::create();
	beginEditCP(osgGeomNode);
	osgGeomNode->setCore(osgGeometry);
	endEditCP(osgGeomNode);

	bool osgConversionSuccess = false;

	GeoPTypesPtr osgTypes = GeoPTypesUI8::create();
	GeoPLengthsPtr osgLengths = GeoPLengthsUI32::create();
	GeoIndicesUI32Ptr osgIndices = GeoIndicesUI32::create();
	GeoPositions3fPtr osgPoints = GeoPositions3f::create();
	GeoNormals3fPtr osgNormals = GeoNormals3f::create();
	GeoColors3fPtr osgColors = GeoColors3f::create();
	GeoTexCoords2dPtr osgTexCoords = GeoTexCoords2d::create();

	//Rendering with OpenSG simple indexed geometry
	if (((m_iNormalType == PER_VERTEX) || (m_iNormalType == NOT_GIVEN)) &&
		((m_iColorType == PER_VERTEX) || (m_iColorType == NOT_GIVEN)))
	{
		if (_verbose)
			std::cout << "Start ProcessGeometryNormalsAndColorsPerVertex()" << std::endl;

		//getting the vertices:
		beginEditCP(osgPoints);
		{
			for (int i = 0; i < m_iNumPoints; i++)
			{
				double* aVertex = pd->GetPoint(i);
				osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2]));
			}
		} endEditCP(osgPoints);

		//possibly getting the normals
		if (m_iNormalType == PER_VERTEX)
		{
			vtkIdType iNumNormals = vtkNormals->GetNumberOfTuples();
			beginEditCP(osgNormals);
			{
				double* aNormal;
				for (int i = 0; i < iNumNormals; i++)
				{
					aNormal = vtkNormals->GetTuple(i);
					osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
				}
			} endEditCP(osgNormals);
			if (iNumNormals != m_iNumPoints)
			{
				std::cout <<
				"WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of normals"
				          << std::endl;
				std::cout << "should equal the number of vertices (points)!" <<	std::endl << std::endl;
			}
		}

		//possibly getting the colors
		if (m_iColorType == PER_VERTEX)
		{
			vtkIdType iNumColors = vtkColors->GetNumberOfTuples();
			beginEditCP(osgColors);
			{
				unsigned char aColor[4];
				for (int i = 0; i < iNumColors; i++)
				{
					vtkColors->GetTupleValue(i, aColor);
					float r = ((float) aColor[0]) / 255.0f;
					float g = ((float) aColor[1]) / 255.0f;
					float b = ((float) aColor[2]) / 255.0f;
					osgColors->addValue(Color3f(r, g, b));
				}
			} endEditCP(osgColors);
			if (iNumColors != m_iNumPoints)
			{
				std::cout <<
				"WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of colors"
				          << std::endl;
				std::cout << "should equal the number of vertices (points)!" << std::endl << std::endl;
			}
		}

		//possibly getting the texture coordinates. These are alwary per vertex
		if (vtkTexCoords != NULL)
		{
			int numTuples = vtkTexCoords->GetNumberOfTuples();
			for (int i = 0; i < numTuples; i++)
			{
				double texCoords[3];
				vtkTexCoords->GetTuple(i, texCoords);
				osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1]));
			}
		}

		//getting the cells
		beginEditCP(osgTypes);
		beginEditCP(osgLengths);
		beginEditCP(osgIndices);
		{
			vtkCellArray* pCells;
			vtkIdType npts, * pts;
			int prim;

			prim = 0;
			pCells = pd->GetVerts();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_POINTS);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetLines();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_LINE_STRIP);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetPolys();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_POLYGON);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetStrips();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_TRIANGLE_STRIP);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}
		} endEditCP(osgIndices);
		endEditCP(osgLengths);
		endEditCP(osgTypes);

		ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords);
		beginEditCP(osgGeometry);
		{
			osgGeometry->setPositions(osgPoints);
			osgGeometry->setTypes(osgTypes);
			osgGeometry->setLengths(osgLengths);
			osgGeometry->setIndices(osgIndices);
			osgGeometry->setMaterial(material);

			if (m_iNormalType == PER_VERTEX)
				osgGeometry->setNormals(osgNormals);
			if (m_iColorType == PER_VERTEX)
				osgGeometry->setColors(osgColors);
			if (osgTexCoords->getSize() > 0)
				osgGeometry->setTexCoords(osgTexCoords);
		} endEditCP(osgGeometry);

		osgConversionSuccess = true;

		if (_verbose)
			std::cout << "    End ProcessGeometryNormalsAndColorsPerVertex()" <<
			std::endl;
	}
	else
	{
		//Rendering with OpenSG non indexed geometry by copying a lot of attribute data
		if (_verbose)
			std::cout <<
			"Start ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" <<
			std::endl;
		int gl_primitive_type = -1;
		if(m_iNumGLPolygons > 0)
		{
			if(m_iNumGLPolygons != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_POLYGON;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POLYGON, pd, osgGeometry);
		}
		else if(m_iNumGLLineStrips > 0)
		{
			if (m_iNumGLLineStrips != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_LINE_STRIP;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_LINE_STRIP, pd osgGeometry);
		}
		else if(m_iNumGLTriStrips > 0)
		{
			if (m_iNumGLTriStrips != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_TRIANGLE_STRIP;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_TRIANGLE_STRIP, pd osgGeometry);
		}
		else if (m_iNumGLPoints > 0)
		{
			if (m_iNumGLPoints != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_POINTS;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POINTS, pd osgGeometry);
		}
		if(gl_primitive_type != -1)
		{
			vtkCellArray* pCells;
			if (gl_primitive_type == GL_POINTS)
				pCells = pd->GetVerts();
			else if (gl_primitive_type == GL_LINE_STRIP)
				pCells = pd->GetLines();
			else if (gl_primitive_type == GL_POLYGON)
				pCells = pd->GetPolys();
			else if (gl_primitive_type == GL_TRIANGLE_STRIP)
				pCells = pd->GetStrips();
			else
			{
				std::cout <<
				"CVtkActorToOpenSG::ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)"
				<< std::endl << " was called with non implemented gl_primitive_type!" << std::endl;
			}

			beginEditCP(osgTypes);
			beginEditCP(osgLengths);
			beginEditCP(osgPoints);
			beginEditCP(osgColors);
			beginEditCP(osgNormals);
			{
				int prim = 0;
				if (pCells->GetNumberOfCells() > 0)
				{
					vtkIdType npts, * pts;
					for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
					     prim++)
					{
						osgLengths->addValue(npts);
						osgTypes->addValue(GL_POLYGON);
						for (int i = 0; i < npts; i++)
						{
							double* aVertex;
							double* aNormal;
							unsigned char aColor[4];

							aVertex = pd->GetPoint(pts[i]);
							osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2]));

							if (m_iNormalType == PER_VERTEX)
							{
								aNormal =
								        vtkNormals->GetTuple(pts[i]);
								osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
							}
							else if (m_iNormalType == PER_CELL)
							{
								aNormal = vtkNormals->GetTuple(prim);
								osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
							}

							if (m_iColorType == PER_VERTEX)
							{
								vtkColors->GetTupleValue(pts[i], aColor);
								float r = ((float) aColor[0]) /	 255.0f;
								float g = ((float) aColor[1]) / 255.0f;
								float b = ((float) aColor[2]) / 255.0f;
								osgColors->addValue(Color3f(r, g, b));
							}
							else if (m_iColorType == PER_CELL)
							{
								vtkColors->GetTupleValue(prim,
								                         aColor);
								float r = ((float) aColor[0]) /	255.0f;
								float g = ((float) aColor[1]) / 255.0f;
								float b = ((float) aColor[2]) / 255.0f;
								osgColors->addValue(Color3f(r, g, b));
							}
						}
					}
				}
			} endEditCP(osgTypes);
			endEditCP(osgLengths);
			endEditCP(osgPoints);
			endEditCP(osgColors);
			endEditCP(osgNormals);

			//possibly getting the texture coordinates. These are always per vertex
			vtkPoints* points = pd->GetPoints();
			if ((vtkTexCoords != NULL) && (points != NULL))
			{
				int numPoints = points->GetNumberOfPoints();
				int numTexCoords = vtkTexCoords->GetNumberOfTuples();
				if (numPoints == numTexCoords)
				{
					beginEditCP(osgTexCoords);
					{
						int numTuples = vtkTexCoords->GetNumberOfTuples();
						for (int i = 0; i < numTuples; i++)
						{
							double texCoords[3];
							vtkTexCoords->GetTuple(i, texCoords);
							osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1]));
						}
					} endEditCP(osgTexCoords);
				}
			}

			ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords);
			//GeometryPtr geo = Geometry::create();
			beginEditCP(osgGeometry);
			{
				osgGeometry->setPositions(osgPoints);
				osgGeometry->setTypes(osgTypes);
				osgGeometry->setLengths(osgLengths);
				osgGeometry->setMaterial(material);

				if (m_iNormalType != NOT_GIVEN)
					osgGeometry->setNormals(osgNormals);
				if (m_iColorType != NOT_GIVEN)
					osgGeometry->setColors(osgColors);
				if (osgTexCoords->getSize() > 0)
					osgGeometry->setTexCoords(osgTexCoords);
				//geo->setMaterial(getDefaultMaterial());
			} endEditCP(osgGeometry);

			osgConversionSuccess = true;
		}
		if (_verbose)
			std::cout <<
			"    End ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" <<
			std::endl;
	}

	if(!osgConversionSuccess)
	{
		std::cout << "OpenSG converter was not able to convert this actor." << std::endl;
		return false;
	}

	if(m_iNormalType == NOT_GIVEN)
	{
		//GeometryPtr newGeometryPtr = GeometryPtr::dcast(newNodePtr->getCore());
		if((osgGeometry != NullFC) && (m_iColorType == PER_VERTEX))
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per vertex!"
			          << std::endl;
			calcVertexNormals(osgGeometry);
		}
		else if ((osgGeometry != NullFC) && (m_iColorType == PER_CELL))
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per face!"
			          << std::endl;
			calcFaceNormals(osgGeometry);
		}
		else if (osgGeometry != NullFC)
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per vertex!"
			          << std::endl;
			calcVertexNormals(osgGeometry);
		}
	}

	std::cout << "Conversion finished." << std::endl;

	// Add node to root
	beginEditCP(_osgRoot);
	_osgRoot->addChild(osgGeomNode);
	endEditCP(_osgRoot);

	pm->Delete();

	return true;
}
Ejemplo n.º 13
0
void loadVtk(string path, VRTransformPtr res) {
    cout << "load VTK file " << path << endl;
    VRGeoData geo;

    vtkDataSetReader* reader = vtkDataSetReader::New();
    reader->SetFileName(path.c_str());
    reader->ReadAllScalarsOn();
    reader->ReadAllVectorsOn();
    reader->ReadAllNormalsOn();
    reader->ReadAllTensorsOn();
    reader->ReadAllTCoordsOn();
    reader->ReadAllFieldsOn();
    reader->ReadAllColorScalarsOn();
    reader->Update();

    vtkDataSet* dataset = reader->GetOutput();

    int npoints = dataset->GetNumberOfPoints();
    int ncells = dataset->GetNumberOfCells();
    int nscalars = reader->GetNumberOfScalarsInFile();
    int nvectors = reader->GetNumberOfVectorsInFile();
    int ntensors = reader->GetNumberOfTensorsInFile();
    cout << "dataset sizes: " << npoints << " " << ncells << " " << nscalars << " " << nvectors << " " << ntensors << endl;

    for (int i=0; i<npoints; i++) {
        auto p = dataset->GetPoint(i);
        Vec3d v(p[0], p[1], p[2]);
        geo.pushVert(v);
        cout << "point " << v << endl;
    }

    auto getCellPIDs = [](vtkCell* c) {
        vector<int> res;
        auto ids = c->GetPointIds();
        for (int k=0; k<ids->GetNumberOfIds(); k++) {
            res.push_back( ids->GetId(k) );
        }
        return res;
    };

    for (int i=0; i<ncells; i++) {
        vtkCell* c = dataset->GetCell(i);
        //int d = c->GetCellDimension();
        //int t = c->GetCellType();

        string type = c->GetClassName();
        cout << "cell type " << type << endl;
        if (type == "vtkQuad") {
            auto j = getCellPIDs(c);
            geo.pushQuad(j[0], j[1], j[2], j[3]);
        }
    }

    //vtkCellData* cells = dataset->GetCellData();
    vtkPointData* points = dataset->GetPointData();

    cout << "POINT_DATA:\n";
    if (points) {
        std::cout << " contains point data with " << points->GetNumberOfArrays() << " arrays." << std::endl;
        for (int i = 0; i < points->GetNumberOfArrays(); i++) {
            std::cout << "\tArray " << i << " is named " << (points->GetArrayName(i) ? points->GetArrayName(i) : "NULL") << std::endl;
        }

        for(int i=0; vtkDataArray* a = points->GetArray(i); i++ ) {
            int size = a->GetNumberOfTuples();
            int comp = a->GetNumberOfComponents();
            cout << " data array " << size << " " << comp << endl;

            for (int j=0; j<size; j++) {
                cout << "pnt:";
                for (int k=0; k<comp; k++) cout << " " << a->GetComponent(j, k);
                cout << endl;
            }
        }
    }


    cout << "FIELD_DATA:\n";
     if (dataset->GetFieldData()) {
       std::cout << " contains field data with "
            << dataset->GetFieldData()->GetNumberOfArrays()
             << " arrays." << std::endl;
        for (int i = 0; i < dataset->GetFieldData()->GetNumberOfArrays(); i++)
          {
          std::cout << "\tArray " << i
               << " is named " << dataset->GetFieldData()->GetArray(i)->GetName()
               << std::endl;
          }
        }


    cout << "CELL_DATA:\n";

     vtkCellData *cd = dataset->GetCellData();
      if (cd)
        {
        std::cout << " contains cell data with "
             << cd->GetNumberOfArrays()
             << " arrays." << std::endl;
        for (int i = 0; i < cd->GetNumberOfArrays(); i++)
          {
          std::cout << "\tArray " << i
               << " is named "
               << (cd->GetArrayName(i) ? cd->GetArrayName(i) : "NULL")
               << std::endl;
          }
        }

    /*if (cells) {
        for(int i=0; vtkDataArray* a = points->GetArray(i); i++ ) {
            int size = a->GetNumberOfTuples();
            int comp = a->GetNumberOfComponents();
            for (int j=0; j<size; j++) {
                cout << "cell:";
                for (int k=0; k<comp; k++) cout << " " << a->GetComponent(j, k);
                cout << endl;
            }
        }
    }*/

    string name = "vtk";

    auto m = VRMaterial::create(name + "_mat");
    m->setLit(0);
    m->setDiffuse(Color3f(0.3,0.7,1.0));

    VRGeometryPtr g = geo.asGeometry(name);
    g->setMaterial(m);
    //g->updateNormals();
    res->addChild( g );
}
Ejemplo n.º 14
0
void loadVtk_old(string path, VRTransformPtr res) {
    cout << "load VTK file " << path << endl;
    ifstream file(path.c_str());
    string line;

    auto next = [&]() -> string& {
        getline(file, line);
        return line;
    };

    VTKProject project;
    project.version = splitString( next() )[4];
    project.title = next();
    project.format = next();
    project.dataset = splitString( next() )[1];

    VRGeoData geo; // build geometry

    if (project.dataset == "STRUCTURED_POINTS") {
        auto r = splitString( next() ); Vec3i dims = toValue<Vec3i>( r[1] + " " + r[2] + " " + r[3] );
             r = splitString( next() ); Vec3d p0 = toValue<Vec3d>( r[1] + " " + r[2] + " " + r[3] );
             r = splitString( next() ); Vec3d d = toValue<Vec3d>( r[1] + " " + r[2] + " " + r[3] );

        for (int k=0; k<dims[2]; k++) {
            for (int j=0; j<dims[1]; j++) {
                for (int i=0; i<dims[0]; i++) {
                    geo.pushVert(p0 + Vec3d(d[0]*i, d[1]*j, d[2]*k) );
                    geo.pushPoint();
                }
            }
        }
    }

    if (project.dataset == "STRUCTURED_GRID") {
        auto r = splitString( next() ); Vec3i dims = toValue<Vec3i>( r[1] + " " + r[2] + " " + r[3] );
             r = splitString( next() ); int N = toInt(r[1]); string type = r[2]; // points

        vector<Vec3d> points;
        for (int i=0; i<N; i++) {
            Vec3d p = toValue<Vec3d>( next() );
            points.push_back(p);
            geo.pushVert(p);
            geo.pushPoint();
        }
    }

    if (project.dataset == "RECTILINEAR_GRID") {
        ;
    }

    if (project.dataset == "UNSTRUCTURED_GRID") {
        ;
    }

    if (project.dataset == "POLYDATA") {
        auto r = splitString( next() ); int N = toInt(r[1]); string type = r[2]; // points
        for (int i=0; i<N; i++) geo.pushVert( toValue<Vec3d>( next() ) );

        while (next() != "") {
            r = splitString( line );
            string type = r[0];
            N = toInt(r[1]);
            //int size = toInt(r[2]);
            for (int i=0; i<N; i++) { // for each primitive
                r = splitString( next() );
                int Ni = toInt(r[0]); // length of primitive
                cout << line << "  " << Ni << endl;
                //if (Ni == 2) geo.pushLine(toInt(r[1]), toInt(r[2]));
                if (Ni == 3) geo.pushTri(toInt(r[1]), toInt(r[2]), toInt(r[3]));
                if (Ni == 4) geo.pushQuad(toInt(r[1]), toInt(r[2]), toInt(r[3]), toInt(r[4]));
            }
        }
    }

    if (project.dataset == "FIELD") {
        ;
    }

    // parsing finished
    cout << project.toString() << endl;
    file.close();

    auto m = VRMaterial::create(project.title + "_mat");
    m->setLit(0);
    m->setDiffuse(Color3f(0.3,0.7,1.0));

    VRGeometryPtr g = geo.asGeometry(project.title);
    g->setMaterial(m);
    //g->updateNormals();
    res->addChild( g );
}
Ejemplo n.º 15
0
Color3f Color3f::operator*(const Color3f& right) const{
	return(Color3f(red*right.red, green*right.green, blue*right.blue));
}
Ejemplo n.º 16
0
    Color3f Li(const Scene *scene, Sampler *sampler, const Ray3f &ray) const {
        /* Find the surface that is visible in the requested direction */
        Intersection its;

        //check if the ray intersects the scene
        if (!scene->rayIntersect(ray, its)) {
            //check if a distant disk light is set
            const Emitter* distantsDisk = scene->getDistantEmitter();
            if(distantsDisk == nullptr ) return Color3f(0.0f);

            //sample the distant disk light
            Vector3f d = ray.d;
            return distantsDisk->sampleL(d);
        }

        //get the Number of lights from the scene
        const  std::vector<Emitter *> lights = scene->getEmitters();
        uint32_t nLights = lights.size();

        Color3f tp(1.0f, 1.0f, 1.0f);
        Color3f L(0.0f, 0.0f, 0.0f);
        Ray3f pathRay(ray.o, ray.d);

        bool deltaFlag = true;

        while(true) {

            if (its.mesh->isEmitter() && deltaFlag) {
                const Emitter* areaLightEM = its.mesh->getEmitter();
                const areaLight* aEM = static_cast<const areaLight *> (areaLightEM);
                L += tp * aEM->sampleL(-pathRay.d, its.shFrame.n, its);
            }

            //Light sampling
            //randomly select a lightsource
            uint32_t var = uint32_t(std::min(sampler->next1D()*nLights, float(nLights) - 1.0f));

            //init the light color
            Color3f Li(0.0f, 0.0f, 0.0f);
            Color3f Ld(1.0f, 1.0f, 1.0f);

            //create a sample for the light
            const BSDF* curBSDF = its.mesh->getBSDF();
            const Point2f lightSample = sampler->next2D();
            VisibilityTester vis;
            Vector3f wo;
            float lightpdf;
            float bsdfpdf;
            Normal3f n = its.shFrame.n;

            deltaFlag = curBSDF->isDeltaBSDF();

            //sample the light

            {
                Li = lights[var]->sampleL(its.p, Epsilon, lightSample , &wo, &lightpdf, &vis);
                lightpdf /= float(nLights);
                //check if the pdf of the sample is greater than 0 and if the color is not black
                if(lightpdf > 0 && Li.maxCoeff() != 0.0f) {
                    //calculate the cosine term wi in my case the vector to the light
                    float cosTerm = std::abs(n.dot(wo));
                    const BSDFQueryRecord queryEM = BSDFQueryRecord(its.toLocal(- pathRay.d), its.toLocal(wo), EMeasure::ESolidAngle, sampler);
                    Color3f f = curBSDF->eval(queryEM);

                    if(f.maxCoeff() > 0.0f && f.minCoeff() >= 0.0f && vis.Unoccluded(scene)) {
                        bsdfpdf = curBSDF->pdf(queryEM);
                        float weight = BalanceHeuristic(float(1), lightpdf, float(1), bsdfpdf);
                        if(curBSDF->isDeltaBSDF())  weight = 1.0f;
                        if(bsdfpdf > 0.0f) {
                            Ld = (weight * f * Li * cosTerm) / lightpdf;
                            L += tp * Ld;
                        } else {
                            //cout << "bsdfpdf = " << bsdfpdf  << endl;
                            //cout << "f = " << f  << endl;
                        }
                    }
                }
            }

            //Material part
            BSDFQueryRecord queryMats = BSDFQueryRecord(its.toLocal(-pathRay.d), Vector3f(0.0f), EMeasure::ESolidAngle, sampler);

            Color3f fi =  curBSDF->sample(queryMats, sampler->next2D());
            bsdfpdf = curBSDF->pdf(queryMats);
            lightpdf = 0.0f;
            if(fi.maxCoeff() > 0.0f && fi.minCoeff() >= 0.0f) {
                if(bsdfpdf > 0.0f) {
                    Ray3f shadowRay(its.p, its.toWorld(queryMats.wo));
                    Intersection lightIsect;

                     if (scene->rayIntersect(shadowRay, lightIsect)) {
                         if(lightIsect.mesh->isEmitter()){
                            const Emitter* areaLightEMcur = lightIsect.mesh->getEmitter();
                            const areaLight* aEMcur = static_cast<const areaLight *> (areaLightEMcur);

                            Li = aEMcur->sampleL(-shadowRay.d, lightIsect.shFrame.n, lightIsect);
                            lightpdf = aEMcur->pdf(its.p, (lightIsect.p - its.p).normalized(), lightIsect.p, Normal3f(lightIsect.shFrame.n));
                         }
                     } else {
                         const Emitter* distantsDisk = scene->getDistantEmitter();
                         if(distantsDisk != nullptr ) {
                             //check if THIS is right!
                             Li = distantsDisk->sampleL(lightIsect.toWorld(queryMats.wo));
                             lightpdf = distantsDisk->pdf(Point3f(0.0f), wo, Point3f(0.0f), Normal3f(0.0f));
                         }
                     }
                     lightpdf /= float(nLights);
                     //calculate the weights
                     float weight = BalanceHeuristic(float(1), bsdfpdf, float(1), lightpdf);


                     //check if the lightcolor is not black
                     if(Li.maxCoeff() > 0.0f  && lightpdf > 0.0f ) {
                         //wo in my case the vector to the light
                         Ld = weight * Li * fi;
                         L += tp * Ld;
                     }
                }



                 tp *= fi;
            } else {
                break;
            }

            wo = its.toWorld(queryMats.wo);
            pathRay = Ray3f(its.p, wo);

            if (!scene->rayIntersect(pathRay, its)) {
                const Emitter* distantsDisk = scene->getDistantEmitter();
                if(distantsDisk != nullptr ) {
                    //sample the distant disk light
                    Vector3f d = pathRay.d;
                    L += tp * distantsDisk->sampleL(d);
                }


                break;
            }

            float maxCoeff = tp.maxCoeff();
            float q = std::min(0.99f, maxCoeff);
            if(q < sampler->next1D()){
                break;
            }
            tp /= q;
        }

        return L;

    }
Ejemplo n.º 17
0
Color3f Color3f::operator*(float right) const{
	return(Color3f(red*right, green*right, blue*right));
}
int main (int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    int id=glutCreateWindow("OpenSG");

    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    GLUTWindowPtr gwin=GLUTWindow::create();
    gwin->setId(id);
    gwin->init();

    // create the scene
    NodePtr scene = Node::create();
    beginEditCP(scene);
        scene->setCore(Group::create());
    endEditCP(scene);

    // create the SimpleSceneManager helper
    _mgr = new SimpleSceneManager;

    // tell the manager what to manage
    _mgr->setWindow(gwin );
    _mgr->setRoot  (scene);

    // create the geometry.
    NodePtr plane = makePlane( 1, 1, 2, 2 );
    NodePtr torus = makeTorus( .2, 1, 16, 8 );

    GeometryPtr plane_geo, torus_geo;
    plane_geo = GeometryPtr::dcast(plane->getCore());
    torus_geo = GeometryPtr::dcast(torus->getCore());

    PolygonChunkPtr pchunk = PolygonChunk::create();
    beginEditCP(pchunk);
        pchunk->setFrontMode(GL_LINE);
        pchunk->setBackMode(GL_LINE);
        pchunk->setOffsetFactor(-1.0);
        pchunk->setOffsetLine(true);
    endEditCP(pchunk);

    // create materials for the plane.
    SimpleMaterialPtr pm1 = SimpleMaterial::create();
    beginEditCP(pm1);
        pm1->setDiffuse( Color3f( 0,1,0 ) );
        pm1->setAmbient( Color3f( 0,1,0 ) );
        pm1->setSpecular( Color3f( 0,0,0 ) );
    endEditCP(pm1);

    SimpleMaterialPtr pm2 = SimpleMaterial::create();
    beginEditCP(pm2);
        pm2->setDiffuse( Color3f( 1,0,0 ) );
        pm2->setAmbient( Color3f( 1,0,0 ) );
        pm2->setSpecular( Color3f( 0,0,0 ) );
        pm2->addChunk(pchunk);
    endEditCP(pm2);

    MultiPassMaterialPtr mppm = MultiPassMaterial::create();
    beginEditCP(mppm);
        mppm->addMaterial(pm1);
        mppm->addMaterial(pm2);
    endEditCP(mppm);

    plane_geo->setMaterial(mppm);

    // create materials for the torus.
    SimpleMaterialPtr tm1 = SimpleMaterial::create();
    beginEditCP(tm1);
        tm1->setDiffuse( Color3f( 0,0,1 ) );
        tm1->setAmbient( Color3f( 0,0,1 ) );
        tm1->setTransparency(0.6);
    endEditCP(tm1);

    SimpleMaterialPtr tm2 = SimpleMaterial::create();
    beginEditCP(tm2);
        tm2->setDiffuse( Color3f( 1,0,0 ) );
        tm2->setAmbient( Color3f( 1,0,0 ) );
        tm2->setSpecular( Color3f( 0,0,0 ) );
        tm2->addChunk(pchunk);
    endEditCP(tm2);

    MultiPassMaterialPtr mptm = MultiPassMaterial::create();
    beginEditCP(mptm);
        mptm->addMaterial(tm1);
        mptm->addMaterial(tm2);
    endEditCP(mptm);

    torus_geo->setMaterial( mptm );

    beginEditCP(scene);
        scene->addChild(plane);
        scene->addChild(torus);
    endEditCP(scene);

    // show the whole scene
    _mgr->showAll();
    
    // GLUT main loop
    glutMainLoop();

    return 0;
}
Ejemplo n.º 19
0
Color3f operator*(float const& lhs, Color3f rhs) {
  return Color3f(rhs.r() * lhs, rhs.g() * lhs, rhs.b() * lhs);
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

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

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

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

    // Make Torus Node (creates Torus in background of scene)
    NodeRefPtr TorusGeometryNode = makeTorus(.5, 2, 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();

    //Background
    TutorialBackground = GradientBackground::create();
    TutorialBackground->addLine(Color3f(1.0,0.0,0.0), 0.0);
    TutorialBackground->addLine(Color3f(0.0,1.0,0.0), 0.2);
    TutorialBackground->addLine(Color3f(0.0,0.0,1.0), 0.4);
    TutorialBackground->addLine(Color3f(0.0,1.0,1.0), 0.6);
    TutorialBackground->addLine(Color3f(1.0,1.0,0.0), 0.8);
    TutorialBackground->addLine(Color3f(1.0,1.0,1.0), 1.0);

	TheUndoManager = UndoManager::create();
	UndoManagerChangeListener TheUndoManagerChangeListener;
	TheUndoManager->addChangeListener(&TheUndoManagerChangeListener);
    
    LabelRefPtr SingleFieldLabel = OSG::Label::create();
    SingleFieldLabel->setText("Single Field");
    SingleFieldLabel->setBorders(NULL);
    SingleFieldLabel->setBackgrounds(NULL);

    LabelRefPtr MultiFieldLabel = OSG::Label::create();
    MultiFieldLabel->setText("Multi Field");
    MultiFieldLabel->setBorders(NULL);
    MultiFieldLabel->setBackgrounds(NULL);

    LabelRefPtr SinglePtrFieldLabel = OSG::Label::create();
    SinglePtrFieldLabel->setText("Single Ptr Field");
    SinglePtrFieldLabel->setBorders(NULL);
    SinglePtrFieldLabel->setBackgrounds(NULL);

    LabelRefPtr MultiPtrFieldLabel = OSG::Label::create();
    MultiPtrFieldLabel->setText("Multi Ptr Field");
    MultiPtrFieldLabel->setBorders(NULL);
    MultiPtrFieldLabel->setBackgrounds(NULL);

    TabPanelRefPtr ExampleTabPanel = OSG::TabPanel::create();
    ExampleTabPanel->setPreferredSize(Vec2f(600,600));
    ExampleTabPanel->addTab(SingleFieldLabel, createSingleFieldPanel());
    ExampleTabPanel->addTab(MultiFieldLabel, createMultiFieldPanel());
    ExampleTabPanel->addTab(SinglePtrFieldLabel, createSinglePtrFieldPanel());
    ExampleTabPanel->addTab(MultiPtrFieldLabel, createMultiPtrFieldPanel());
    ExampleTabPanel->setTabAlignment(0.5f);
    ExampleTabPanel->setTabPlacement(TabPanel::PLACEMENT_NORTH);
    ExampleTabPanel->setSelectedIndex(0);

	//UndoList
	UndoRedoListModel = DefaultListModel::create();
    UndoRedoListModel->pushBack(boost::any(std::string("Top")));
	ListSelectionModelPtr UndoRedoListSelectionModel(new DefaultListSelectionModel());

	UndoRedoList = List::create();
        UndoRedoList->setPreferredSize(Vec2f(200, 300));
        UndoRedoList->setOrientation(List::VERTICAL_ORIENTATION);
		UndoRedoList->setModel(UndoRedoListModel);

    UndoRedoList->setSelectionModel(UndoRedoListSelectionModel);

    UndoRedoListListener TheUndoRedoListListener;
    UndoRedoList->getSelectionModel()->addListSelectionListener(&TheUndoRedoListListener);

    UndoButton = OSG::Button::create();
            UndoButton->setText("Undo");
			UndoButton->setEnabled(TheUndoManager->numberOfUndos() != 0);
    UndoButtonActionListener TheUndoButtonActionListener;
    UndoButton->addActionListener(&TheUndoButtonActionListener);
	

    RedoButton = OSG::Button::create();
            RedoButton->setText("Redo");
			RedoButton->setEnabled(TheUndoManager->numberOfRedos() != 0);
    RedoButtonActionListener TheRedoButtonActionListener;
    RedoButton->addActionListener(&TheRedoButtonActionListener);

    // Create a ScrollPanel for easier viewing of the List (see 27ScrollPanel)
    ScrollPanelRefPtr UndoRedoScrollPanel = ScrollPanel::create();
        UndoRedoScrollPanel->setPreferredSize(Vec2f(200,200));
        UndoRedoScrollPanel->setHorizontalResizePolicy(ScrollPanel::RESIZE_TO_VIEW);
    UndoRedoScrollPanel->setViewComponent(UndoRedoList);

    // Create The Main InternalWindow
    // Create Background to be used with the Main InternalWindow
    ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create();
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
    InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
    LayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();
       MainInternalWindow->pushToChildren(ExampleTabPanel);
       MainInternalWindow->pushToChildren(UndoRedoScrollPanel);
       MainInternalWindow->pushToChildren(UndoButton);
       MainInternalWindow->pushToChildren(RedoButton);
       MainInternalWindow->setLayout(MainInternalWindowLayout);
       MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
	   MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.95f,0.95f));
	   MainInternalWindow->setDrawTitlebar(false);
	   MainInternalWindow->setResizable(false);

    // Create the Drawing Surface
    UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindow);
    
	TutorialDrawingSurface->openWindow(MainInternalWindow);
	
	// Create the UI Foreground Object
    UIForegroundRefPtr TutorialUIForeground = OSG::UIForeground::create();

        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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

    // Add the UI Foreground Object to the Scene
    ViewportRefPtr TutorialViewport = mgr->getWindow()->getPort(0);
    TutorialViewport->addForeground(TutorialUIForeground);
    TutorialViewport->setBackground(TutorialBackground);

    // 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,
            "01ChangeFieldCommands");

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

    osgExit();

    return 0;
}
Ejemplo n.º 21
0
void FlyingEyeSpell::Update(float timeDelta)
{
	ARX_UNUSED(timeDelta);
	
	const unsigned long tim = (unsigned long)(arxtime);
	
	const long framediff3 = tim - m_lastupdate;
	
	eyeball.floating = std::sin(m_lastupdate-m_timcreation * 0.001f);
	eyeball.floating *= 10.f;
	
	if(m_lastupdate-m_timcreation <= 3000) {
		eyeball.exist = m_lastupdate - m_timcreation * (1.0f / 30);
		eyeball.size = Vec3f(1.f - float(eyeball.exist) * 0.01f);
		eyeball.angle.setPitch(eyeball.angle.getPitch() + framediff3 * 0.6f);
	} else {
		eyeball.exist = 2;
	}
	
	m_lastupdate=tim;
	
	Entity * io = entities.player();
	EERIE_3DOBJ * eobj = io->obj;
	long pouet = 2;

	while(pouet) {
		long id;

		if(pouet == 2)
			id = io->obj->fastaccess.primary_attach;
		else
			id = GetActionPointIdx(io->obj, "left_attach");

		pouet--;

		if(id != -1) {
			if(!lightHandleIsValid(special[pouet])) {
				special[pouet] = GetFreeDynLight();
			}
			if(lightHandleIsValid(special[pouet])) {
				EERIE_LIGHT * el = lightHandleGet(special[pouet]);
				el->intensity = 1.3f;
				el->fallend = 180.f;
				el->fallstart = 50.f;
				el->rgb = Color3f(0.7f, 0.3f, 1.f);
				el->pos = eobj->vertexlist3[id].v;
			}
			
			for(long kk = 0; kk < 2; kk++) {
				
				PARTICLE_DEF * pd = createParticle();
				if(!pd) {
					break;
				}
				
				pd->ov = eobj->vertexlist3[id].v + randomVec(-1.f, 1.f);
				pd->move = Vec3f(0.1f, 0.f, 0.1f) + Vec3f(-0.2f, -2.2f, -0.2f) * Vec3f(rnd(), rnd(), rnd());
				pd->siz = 5.f;
				pd->tolive = Random::get(1500, 3500);
				pd->scale = Vec3f(0.2f);
				pd->tc = TC_smoke;
				pd->special = FADE_IN_AND_OUT | ROTATING | MODULATE_ROTATION | DISSIPATING;
				pd->sourceionum = PlayerEntityHandle;
				pd->source = &eobj->vertexlist3[id].v;
				pd->fparam = 0.0000001f;
				pd->rgb = Color3f(.7f, .3f, 1.f) + Color3f(-.1f, -.1f, -.1f) * Color3f(rnd(), rnd(), rnd());
			}
		}
	}
}
Ejemplo n.º 22
0
Color3f
Light::getAmbient ( void ) const
{
        return Color3f ( 0.1, 0.1, 0.1 );
}
Ejemplo n.º 23
0
void ConfuseSpell::Update(float timeDelta) {
	
	ARX_UNUSED(timeDelta);
	
	Vec3f pos = entities[m_target]->pos;
	if(m_target != PlayerEntityHandle) {
		pos.y += entities[m_target]->physics.cyl.height - 30.f;
	}
	
	long idx = entities[m_target]->obj->fastaccess.head_group_origin;
	if(idx >= 0) {
		pos = entities[m_target]->obj->vertexlist3[idx].v;
		pos.y -= 50.f;
	}
	
	eCurPos = pos;
	
	RenderMaterial mat;
	mat.setDepthTest(false);
	mat.setBlendType(RenderMaterial::Additive);
	mat.setTexture(tex_trail);
	
	Anglef stiteangle = Anglef(0.f, -glm::degrees(arxtime.get_updated() * ( 1.0f / 500 )), 0.f);
	Draw3DObject(spapi, stiteangle, eCurPos, Vec3f_ONE, Color3f::white, mat);
	
	for(int i = 0; i < 6; i++) {
		
		PARTICLE_DEF * pd = createParticle();
		if(!pd) {
			break;
		}
		
		float ang = rnd() * 360.f;
		float rad = rnd() * 15.f;
		pd->ov = eCurPos;
		pd->ov += angleToVectorXZ(ang) * rad;
		
		pd->move = Vec3f(0.f, rnd() * 3.f + 1.f, 0.f);
		pd->siz = 0.25f;
		pd->tolive = Random::get(2300, 3300);
		pd->tc = tex_p1;
		pd->special = PARTICLE_GOLDRAIN | FADE_IN_AND_OUT | ROTATING | MODULATE_ROTATION
					  | DISSIPATING;
		pd->fparam = 0.0000001f;
		
		Color3f baseColor = Color3f(0.4f, 0.2f, 0.4f);
		Color3f randomFactor = Color3f(0.4f, 0.6f, 0.4f);
		Color3f c = baseColor + Color3f(rnd(), rnd(), rnd()) * randomFactor;
		while(glm::abs(c.r - c.g) > 0.3f && glm::abs(c.g - c.b) > 0.3f) {
			c = baseColor + Color3f(rnd(), rnd(), rnd()) * randomFactor;
		}
		pd->rgb = c * Color3f(0.8f, 0.8f, 0.8f);
	}
	
	if(!lightHandleIsValid(m_light))
		m_light = GetFreeDynLight();

	if(lightHandleIsValid(m_light)) {
		EERIE_LIGHT * light = lightHandleGet(m_light);
		
		light->intensity = 1.3f;
		light->fallstart = 180.f;
		light->fallend   = 420.f;
		light->rgb = Color3f(0.3f, 0.3f, 0.5f) + Color3f(0.2f, 0.f, 0.2f) * Color3f(rnd(), rnd(), rnd());
		light->pos = eCurPos;
		light->duration = 200;
		light->extras = 0;
	}
}
Ejemplo n.º 24
0
Color3f
Light::getDiffuse ( void ) const
{
        return Color3f ( 0.8, 0.8, 0.8 );
}
Ejemplo n.º 25
0
#include "game/Inventory.h"
#include "game/Player.h"

#include "graphics/Math.h"
#include "graphics/Draw.h"
#include "graphics/DrawLine.h"

#include "platform/profiler/Profiler.h"

#include "scene/Object.h"
#include "scene/GameSound.h"
#include "scene/Interactive.h"

static const float GLOBAL_LIGHT_FACTOR=0.85f;

static const Color3f defaultAmbient = Color3f(0.09f, 0.09f, 0.09f);
static const int NPC_ITEMS_AMBIENT_VALUE_255 = 35;

EERIE_LIGHT * GLight[MAX_LIGHTS];
EERIE_LIGHT DynLight[MAX_DYNLIGHTS];

EERIE_LIGHT * PDL[MAX_DYNLIGHTS];
size_t TOTPDL = 0;

static EERIE_LIGHT * IO_PDL[MAX_DYNLIGHTS];
size_t TOTIOPDL = 0;

void ColorMod::updateFromEntity(Entity *io, bool inBook) {
	factor = Color3f::white;
	term = Color3f::black;
	if(io) {
Ejemplo n.º 26
0
Color3f
Light::getSpecular ( void ) const
{
        return Color3f ( 0.1, 0.1, 0.1 );
}
Ejemplo n.º 27
0
Color3f Ground::colorAt(Coord3f point, Coord2i indexPoint) {
	// NOTE: In this function, the vertical component is i, which comes in as indexPoint.x,
	// 		 and vice versa for the horizonal, j, which is indexPoint.y

	bool ignore[6] = { false, false, false, false, false, false };

	if (indexPoint.x == 0) {
		ignore[2] = true;
		ignore[3] = true;
	}
	if (indexPoint.x == (this->nRows - 1)) {
		ignore[0] = true;
		ignore[5] = true;
	}
	if (indexPoint.y == 0) {
		ignore[1] = true;
		ignore[2] = true;
	}
	if (indexPoint.y == (this->nCols - 1)) {
		ignore[2] = true;
		ignore[5] = true;
	}

	int dI, dJ;
	float dX;
	float maxSlope = 0; // The most slope
	float slope;
	bool isLake = true;

	for (int i = 0; i < 6; i++) {
		if (ignore[i]) continue;

		switch (i) {
			case 0: dI = 1;
					dJ = 0;
					dX = this->cellSize;
					break;
			case 1: dI = 0;
					dJ = -1;
					dX = this->cellSize;
					break;
			case 2: dI = -1;
					dJ = -1;
					dX = 1.414 * this->cellSize; // sqrt(2)
					break;
			case 3: dI = -1;
					dJ = 0;
					dX = this->cellSize;
					break;
			case 4: dI = 0;
					dJ = 1;
					dX = this->cellSize;
					break;
			case 5: dI = 1;
					dJ = 1;
					dX = 1.414 * this->cellSize; // sqrt(2)
					break;
		}

		slope = abs(this->pointGrid[indexPoint.x][indexPoint.y] - this->pointGrid[indexPoint.x + dI][indexPoint.y + dJ]) / dX;
		if (slope > 0.1f) isLake = false;
		if (slope > maxSlope) maxSlope = slope;
	}

	float degrees = atan(slope) * (180 / M_PI);

	if (degrees > 45) { // Angle > 60 means a grey cliff
		return Color3f(0.3, 0.3, 0.3);
	}
	else if (point.y > this->secondDelimiter) { // If above snowline, then white
		return Color3f(1.0, 1.0, 1.0);
	}
	else if (isLake) {
		return Color3f(0.3, 0.3, 1.0);
	}
	else {
		return Color3f(0.1, 0.3, 0.1);
	}
}
Ejemplo n.º 28
0
void ARX_INTERFACE_ManageOpenedBook_Finish()
{

	Vec3f pos = Vec3f(0.f, 0.f, 2100.f);
	Anglef angle = Anglef::ZERO;
	
	EERIE_LIGHT * light = lightHandleGet(torchLightHandle);
	
	EERIE_LIGHT tl = *light;
	
	light->pos = Vec3f(500.f, -1960.f, 1590.f);
	light->exist = 1;
	light->rgb = Color3f(0.6f, 0.7f, 0.9f);
	light->intensity  = 1.8f;
	light->fallstart=4520.f;
	light->fallend = light->fallstart + 600.f;
	RecalcLight(light);
	
	EERIE_CAMERA * oldcam = ACTIVECAM;
	
	PDL[0] = light;
	TOTPDL=1;
	
	Vec2i tmpPos = Vec2i_ZERO;
	
	for(size_t i = 0; i < RUNE_COUNT; i++) {
		if(!gui::necklace.runes[i])
			continue;
		
		EERIE_3DOBJ * rune = gui::necklace.runes[i];
		
		bookcam.center.x = (382 + tmpPos.x * 45 + BOOKDEC.x) * g_sizeRatio.x;
		bookcam.center.y = (100 + tmpPos.y * 64 + BOOKDEC.y) * g_sizeRatio.y;
		
		SetActiveCamera(&bookcam);
		PrepareCamera(&bookcam, g_size);
		
		// First draw the lace
		angle.setPitch(0.f);
		
		if(player.hasRune((Rune)i)) {
			
			TransformInfo t1(pos, glm::toQuat(toRotationMatrix(angle)));
			DrawEERIEInter(gui::necklace.lacet, t1, NULL);
			
			if(rune->angle.getPitch() != 0.f) {
				if(rune->angle.getPitch() > 300.f)
					rune->angle.setPitch(300.f);
				
				angle.setPitch(std::sin(arxtime.get_updated() * (1.0f / 200)) * rune->angle.getPitch() * (1.0f / 40));
			}
			
			rune->angle.setPitch(rune->angle.getPitch() - framedelay * 0.2f);
			
			if(rune->angle.getPitch() < 0.f)
				rune->angle.setPitch(0.f);
			
			GRenderer->SetRenderState(Renderer::DepthWrite, true);
			GRenderer->SetRenderState(Renderer::AlphaBlending, false);
			
			// Now draw the rune
			TransformInfo t2(pos, glm::toQuat(toRotationMatrix(angle)));
			DrawEERIEInter(rune, t2, NULL);
			
			EERIE_2D_BBOX runeBox;
			UpdateBbox2d(*rune, runeBox);
			
			PopAllTriangleList();
			
			tmpPos.x++;
			
			if(tmpPos.x > 4) {
				tmpPos.x = 0;
				tmpPos.y++;
			}
			
			const Rect runeMouseTestRect(
			runeBox.min.x,
			runeBox.min.y,
			runeBox.max.x,
			runeBox.max.y
			);
			
			// Checks for Mouse floating over a rune...
			if(runeMouseTestRect.contains(Vec2i(DANAEMouse))) {
				long r=0;
				
				for(size_t j = 0; j < rune->facelist.size(); j++) {
					float n = PtIn2DPolyProj(rune, &rune->facelist[j], (float)DANAEMouse.x, (float)DANAEMouse.y);
					
					if(n!=0.f) {
						r=1;
						break;
					}
				}
				
				if(r) {
					GRenderer->SetRenderState(Renderer::AlphaBlending, true);
					GRenderer->SetBlendFunc(Renderer::BlendOne, Renderer::BlendOne);
					
					TransformInfo t(pos, glm::toQuat(toRotationMatrix(angle)));
					DrawEERIEInter(rune, t, NULL);
					
					rune->angle.setPitch(rune->angle.getPitch() + framedelay*2.f);
					
					PopAllTriangleList();
					
					GRenderer->SetRenderState(Renderer::AlphaBlending, false);
					
					SpecialCursor=CURSOR_INTERACTION_ON;
					
					if(eeMouseDown1())
						if((size_t)LastRune != i) {
							PlayerBookDrawRune((Rune)i);
						}
						
						LastRune=i;
				}
			}
		}
	}
	
	GRenderer->SetCulling(Renderer::CullCCW);
	
	LastRune=-1;
	
	*light = tl;
	
	SetActiveCamera(oldcam);
	PrepareCamera(oldcam, g_size);
}
Ejemplo n.º 29
0
void Fist::fire() const {
    float time = timer::totalTime();
    if (time - timer_ > 0.5f) {
        timer_ = time;
        float angleRad = parent_->rotation()*M_PI / 180.f;
        Vector2f faceDirection(std::cos(angleRad), std::sin(angleRad));

        particles::spawn(particles::pAmmoFist, parent_->location() + faceDirection*parent_->radius(), faceDirection, parent_->velocity(), Color3f(), parent_->getOwner());

        parent_->velocity() -= faceDirection*200.f;
        sound::playSound(sound::Pump, parent_->location());
    }
}
Ejemplo n.º 30
0
Entity::Entity(const res::path & classPath, EntityInstance instance)
	: mainevent(SM_MAIN)
	, m_index(size_t(-1))
	, m_id(classPath, instance)
	, m_classPath(classPath)
{
	
	m_index = entities.add(this);
	
	ioflags = 0;
	lastpos = Vec3f_ZERO;
	pos = Vec3f_ZERO;
	move = Vec3f_ZERO;
	lastmove = Vec3f_ZERO;
	forcedmove = Vec3f_ZERO;
	
	angle = Anglef::ZERO;
	physics = IO_PHYSICS();
	room = -1;
	requestRoomUpdate = true;
	original_height = 0.f;
	original_radius = 0.f;
	m_icon = NULL;
	obj = NULL;
	std::fill_n(anims, MAX_ANIMS, (ANIM_HANDLE *)NULL);
	
	for(size_t l = 0; l < MAX_ANIM_LAYERS; l++) {
		animlayer[l] = AnimLayer();
	}
	
	animBlend.m_active = false;
	animBlend.lastanimtime = 0;
	
	std::memset(&bbox3D, 0, sizeof(EERIE_3D_BBOX)); // TODO use constructor
	
	bbox2D.min = Vec2f(-1.f, -1.f);
	bbox2D.max = Vec2f(-1.f, -1.f);

	tweaky = NULL;
	sound = audio::INVALID_ID;
	type_flags = 0;
	scriptload = 0;
	target = Vec3f_ZERO;
	targetinfo = EntityHandle(TARGET_NONE);
	
	_itemdata = NULL;
	_fixdata = NULL;
	_npcdata = NULL;
	_camdata = NULL;
	
	inventory = NULL;
	show = SHOW_FLAG_IN_SCENE;
	collision = 0;
	infracolor = Color3f::blue;
	changeanim = -1;
	
	weight = 1.f;
	gameFlags = GFLAG_NEEDINIT | GFLAG_INTERACTIVITY;
	fall = 0.f;
	
	initpos = Vec3f_ZERO;
	initangle = Anglef::ZERO;
	scale = 1.f;
	
	usepath = NULL;
	symboldraw = NULL;
	dynlight = LightHandle();
	lastspeechflag = 2;
	inzone = NULL;
	halo = IO_HALO();
	halo_native = IO_HALO();
	halo_native.color = Color3f(0.2f, 0.5f, 1.f);
	halo_native.radius = 45.f;
	halo_native.flags = 0;
	ARX_HALO_SetToNative(this);
	
	for(size_t j = 0; j < MAX_SCRIPTTIMERS; j++) {
		m_scriptTimers[j] = 0;
	}
	m_disabledEvents = 0;
	
	stat_count = 0;
	stat_sent = 0;
	tweakerinfo = NULL;
	material = MATERIAL_NONE;
	
	m_inventorySize = Vec2s(1, 1);
	
	soundtime = 0;
	soundcount = 0;
	
	sfx_time = 0;
	collide_door_time = 0;
	ouch_time = 0;
	dmg_sum = 0.f;
	
	spellcast_data = IO_SPELLCAST_DATA();
	flarecount = 0;
	no_collide = EntityHandle();
	invisibility = 0.f;
	basespeed = 1.f;
	
	speed_modif = 0.f;
	
	rubber = BASE_RUBBER;
	max_durability = durability = 100.f;
	poisonous = 0;
	poisonous_count = 0;
	
	ignition = 0.f;
	ignit_light = LightHandle();
	ignit_sound = audio::INVALID_ID;
	head_rot = 0.f;
	
	damager_damages = 0;
	damager_type = 0;
	
	sfx_flag = 0;
	secretvalue = -1;
	
	shop_multiply = 1.f;
	isHit = false;
	inzone_show = 0;
	summoner = EntityHandle();
	spark_n_blood = 0;

	special_color = Color3f::white;
	highlightColor = Color3f::black;
	
}