• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ Clamp函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中Clamp函数的典型用法代码示例。如果您正苦于以下问题:C++ Clamp函数的具体用法?C++ Clamp怎么用?C++ Clamp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Clamp函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: Clamp

void COverheadController::MouseWheelMove(float move)
{
	if (move == 0.0f)
		return;

	camHandler->CameraTransition(0.05f);

	const float shiftSpeed = (KeyInput::GetKeyModState(KMOD_SHIFT) ? 3.0f : 1.0f);
	const float altZoomDist = height * move * 0.007f * shiftSpeed;
	
	// tilt the camera if LCTRL is pressed
	//
	// otherwise holding down LALT uses 'instant-zoom'
	// from here to the end of the function (smoothed)
	if (KeyInput::GetKeyModState(KMOD_CTRL)) {
		angle += (move * tiltSpeed * shiftSpeed * 0.025f) * angleStep;
		angle = Clamp(angle, 0.01f, fastmath::HALFPI);
	} else {
		if (move < 0.0f) {
			// ZOOM IN to mouse cursor instead of mid screen
			float3 cpos = pos - dir * height;
			float dif = -altZoomDist;

			if ((height - dif) < 60.0f) {
				dif = height - 60.0f;
			}
			if (KeyInput::GetKeyModState(KMOD_ALT)) {
				// instazoom in to standard view
				dif = (height - oldAltHeight) / mouse->dir.y * dir.y;
			}

			float3 wantedPos = cpos + mouse->dir * dif;
			float newHeight = CGround::LineGroundCol(wantedPos, wantedPos + dir * 15000, false);

			if (newHeight < 0.0f) {
				newHeight = height * (1.0f + move * 0.007f * shiftSpeed);
			}
			if ((wantedPos.y + (dir.y * newHeight)) < 0.0f) {
				newHeight = -wantedPos.y / dir.y;
			}
			if (newHeight < maxHeight) {
				height = newHeight;
				pos = wantedPos + dir * height;
			}
		} else {
			// ZOOM OUT from mid screen
			if (KeyInput::GetKeyModState(KMOD_ALT)) {
				// instazoom out to maximum height
				if (height < maxHeight*0.5f && changeAltHeight) {
					oldAltHeight = height;
					changeAltHeight = false;
				}
				height = maxHeight;
				pos.x  = mapDims.mapx * SQUARE_SIZE * 0.5f;
				pos.z  = mapDims.mapy * SQUARE_SIZE * 0.55f; // somewhat longer toward bottom
			} else {
				height *= (1.0f + (altZoomDist / height));
			}
		}

		// instant-zoom: turn on the smooth transition and reset the camera tilt
		if (KeyInput::GetKeyModState(KMOD_ALT)) {
			angle = DEFAULT_ANGLE;
			camHandler->CameraTransition(1.0f);
		} else {
			changeAltHeight = true;
		}
	}

	Update();
}
开发者ID:DoctorEmmettBrown,项目名称:spring,代码行数:71,代码来源:OverheadController.cpp


示例2: Clamp

 float MathHelper::SmoothStep(float val1, float val2, float t)
 {
     t = Clamp(t, 0, 1);
     return Lerp(val1, val2, t*t*(3 - 2 * t));
 }
开发者ID:Swillis57,项目名称:YAX,代码行数:5,代码来源:MathHelper.cpp


示例3: UpdateOptions

void UpdateOptions()
{
    if(optionsInit)
    {
        mouse.x = mouse_x;mouse.y = mouse_y;
        mouseBPrev = mouseB;
        mouseB = mouse_b;

        if(ABB(mouse,backButt) && mouseB == 1)
        {
            hFile = HeroF->str;
            zFile = ZombieF->str;
            SaveConfig("config.cfg");

            GameState = MAINMENU;
        }
        if(ABB(mouse,fxPlus) && mouseB == 1)
        {
            fxVol = Clamp(0,fxVol+1,255);
            fxAm.w = fxVol;
        }
        if(ABB(mouse,fxMinus) && mouseB == 1)
        {
            fxVol = Clamp(0,fxVol-1,255);
            fxAm.w = fxVol;
        }
        if(ABB(mouse,musPlus) && mouseB == 1)
        {
            musicVol = Clamp(0,musicVol+1,255);
            adjust_sample(bgMusic,musicVol,127,1000,1);
            musAm.w = musicVol;
        }
        if(ABB(mouse,musMinus) && mouseB == 1)
        {
            musicVol = Clamp(0,musicVol-1,255);
            adjust_sample(bgMusic,musicVol,127,1000,1);
            musAm.w = musicVol;
        }

        if(ABB(mouse,zombieNext) && mouseB == 0 && mouseBPrev == 1)
        {
            if(ZombieF->next) ZombieF = ZombieF->next;
        }
        if(ABB(mouse,zombiePrev) && mouseB == 0 && mouseBPrev == 1)
        {
            if(ZombieF->prev) ZombieF = ZombieF->prev;
        }
        if(ABB(mouse,heroNext) && mouseB == 0 && mouseBPrev == 1)
        {
            if(HeroF->next) HeroF = HeroF->next;
        }
        if(ABB(mouse,heroPrev) && mouseB == 0 && mouseBPrev == 1)
        {
            if(HeroF->prev) HeroF = HeroF->prev;
        }
    }
    else
    {
        InitOptions();
    }
}
开发者ID:BartoszF,项目名称:ZombieSlasher,代码行数:61,代码来源:options.c


示例4: Clamp

void SoundSource3D::SetOuterAngle(float angle)
{
    outerAngle_ = Clamp(angle, 0.0f, DEFAULT_ANGLE);
    MarkNetworkUpdate();
}
开发者ID:rokups,项目名称:Urho3D,代码行数:5,代码来源:SoundSource3D.cpp


示例5: if


//.........这里部分代码省略.........
                // If using 4 shadow samples, offset the position diagonally by half pixel
                if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
                {
                    addX -= 0.5f / width;
                    addY -= 0.5f / height;
                }
                graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
            }
            
            {
                // Calculate shadow camera depth parameters for point light shadows and shadow fade parameters for
                //  directional light shadows, stored in the same uniform
                Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
                float nearClip = shadowCamera->GetNearClip();
                float farClip = shadowCamera->GetFarClip();
                float q = farClip / (farClip - nearClip);
                float r = -q * nearClip;
                
                const CascadeParameters& parameters = light->GetShadowCascade();
                float viewFarClip = camera_->GetFarClip();
                float shadowRange = parameters.GetShadowRange();
                float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
                float fadeEnd = shadowRange / viewFarClip;
                float fadeRange = fadeEnd - fadeStart;
                
                graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
            }
            
            {
                float intensity = light->GetShadowIntensity();
                float fadeStart = light->GetShadowFadeDistance();
                float fadeEnd = light->GetShadowDistance();
                if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
                    intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
                float pcfValues = (1.0f - intensity);
                float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;

                graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f));
            }
            
            float sizeX = 1.0f / (float)shadowMap->GetWidth();
            float sizeY = 1.0f / (float)shadowMap->GetHeight();
            graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
            
            Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
            if (lightQueue_->shadowSplits_.Size() > 1)
                lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
            if (lightQueue_->shadowSplits_.Size() > 2)
                lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
            if (lightQueue_->shadowSplits_.Size() > 3)
                lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
            
            graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
        }
    }
    
    // Set material-specific shader parameters and textures
    if (material_)
    {
        if (graphics->NeedParameterUpdate(SP_MATERIAL, material_))
        {
            // Update shader parameter animations
            material_->UpdateShaderParameterAnimations();

            const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
            for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
开发者ID:OvermindDL1,项目名称:Urho3D,代码行数:67,代码来源:Batch.cpp


示例6: _define_ship

int _define_ship(lua_State *L, ShipType::Tag tag, std::vector<ShipType::Id> *list)
{
	if (s_currentShipFile.empty())
		return luaL_error(L, "ship file contains multiple ship definitions");

	ShipType s;
	s.tag = tag;
	s.id = s_currentShipFile;

	LUA_DEBUG_START(L);
	LuaTable t(L, -1);

	s.name = t.Get("name", "");
	s.modelName = t.Get("model", "");
	s.linThrust[ShipType::THRUSTER_REVERSE] = t.Get("reverse_thrust", 0.0f);
	s.linThrust[ShipType::THRUSTER_FORWARD] = t.Get("forward_thrust", 0.0f);
	s.linThrust[ShipType::THRUSTER_UP] = t.Get("up_thrust", 0.0f);
	s.linThrust[ShipType::THRUSTER_DOWN] = t.Get("down_thrust", 0.0f);
	s.linThrust[ShipType::THRUSTER_LEFT] = t.Get("left_thrust", 0.0f);
	s.linThrust[ShipType::THRUSTER_RIGHT] = t.Get("right_thrust", 0.0f);
	s.angThrust = t.Get("angular_thrust", 0.0f);
	// invert values where necessary
	s.linThrust[ShipType::THRUSTER_FORWARD] *= -1.f;
	s.linThrust[ShipType::THRUSTER_LEFT] *= -1.f;
	s.linThrust[ShipType::THRUSTER_DOWN] *= -1.f;
	// angthrust fudge (XXX: why?)
	s.angThrust = s.angThrust / 2;

	lua_pushstring(L, "camera_offset");
	lua_gettable(L, -2);
	if (!lua_isnil(L, -1))
		fprintf(stderr, "ship definition for '%s' has deprecated 'camera_offset' field\n", s.id.c_str());
	lua_pop(L, 1);
	s.cameraOffset = t.Get("camera_offset", vector3d(0.0));

	for (int i=0; i<Equip::SLOT_MAX; i++) s.equipSlotCapacity[i] = 0;
	s.equipSlotCapacity[Equip::SLOT_CARGO] = t.Get("max_cargo", 0);
	s.equipSlotCapacity[Equip::SLOT_ENGINE] = t.Get("max_engine", 1);
	s.equipSlotCapacity[Equip::SLOT_LASER] = t.Get("max_laser", 1);
	s.equipSlotCapacity[Equip::SLOT_MISSILE] = t.Get("max_missile", 0);
	s.equipSlotCapacity[Equip::SLOT_ECM] = t.Get("max_ecm", 1);
	s.equipSlotCapacity[Equip::SLOT_SCANNER] = t.Get("max_scanner", 1);
	s.equipSlotCapacity[Equip::SLOT_RADARMAPPER] = t.Get("max_radarmapper", 1);
	s.equipSlotCapacity[Equip::SLOT_HYPERCLOUD] = t.Get("max_hypercloud", 1);
	s.equipSlotCapacity[Equip::SLOT_HULLAUTOREPAIR] = t.Get("max_hullautorepair", 1);
	s.equipSlotCapacity[Equip::SLOT_ENERGYBOOSTER] = t.Get("max_energybooster", 1);
	s.equipSlotCapacity[Equip::SLOT_ATMOSHIELD] = t.Get("max_atmoshield", 1);
	s.equipSlotCapacity[Equip::SLOT_CABIN] = t.Get("max_cabin", 50);
	s.equipSlotCapacity[Equip::SLOT_SHIELD] = t.Get("max_shield", 9999);
	s.equipSlotCapacity[Equip::SLOT_FUELSCOOP] = t.Get("max_fuelscoop", 1);
	s.equipSlotCapacity[Equip::SLOT_CARGOSCOOP] = t.Get("max_cargoscoop", 1);
	s.equipSlotCapacity[Equip::SLOT_LASERCOOLER] = t.Get("max_lasercooler", 1);
	s.equipSlotCapacity[Equip::SLOT_CARGOLIFESUPPORT] = t.Get("max_cargolifesupport", 1);
	s.equipSlotCapacity[Equip::SLOT_AUTOPILOT] = t.Get("max_autopilot", 1);

	s.capacity = t.Get("capacity", 0);
	s.hullMass = t.Get("hull_mass", 100);
	s.fuelTankMass = t.Get("fuel_tank_mass", 5);

	// fuel_use_rate can be given in two ways
	float thruster_fuel_use = 0;
	s.effectiveExhaustVelocity = t.Get("effective_exhaust_velocity", -1.0f);
	thruster_fuel_use = t.Get("thruster_fuel_use", -1.0f);
	if(s.effectiveExhaustVelocity < 0 && thruster_fuel_use < 0) {
		// default value of v_c is used
		s.effectiveExhaustVelocity = 55000000;
	} else if(s.effectiveExhaustVelocity < 0 && thruster_fuel_use >= 0) {
		// v_c undefined and thruster fuel use defined -- use it!
		s.effectiveExhaustVelocity = GetEffectiveExhaustVelocity(s.fuelTankMass, thruster_fuel_use, s.linThrust[ShipType::THRUSTER_FORWARD]);
	} else {
		if(thruster_fuel_use >= 0)
			printf("Warning: Both thruster_fuel_use and effective_exhaust_velocity defined for %s, using effective_exhaust_velocity.\n", s.modelName.c_str());
	}

	s.baseprice = t.Get("price", 0);
	s.baseprice *= 100; // in hundredths of credits

	s.minCrew = t.Get("min_crew", 1);
	s.maxCrew = t.Get("max_crew", 1);

	s.equipSlotCapacity[Equip::SLOT_ENGINE] = Clamp(s.equipSlotCapacity[Equip::SLOT_ENGINE], 0, 1);

	{
		int hyperclass;
		hyperclass = t.Get("hyperdrive_class", 1);
		if (!hyperclass) {
			s.hyperdrive = Equip::NONE;
		} else {
			s.hyperdrive = Equip::Type(Equip::DRIVE_CLASS1+hyperclass-1);
		}
	}

	for (int i = 0; i < ShipType::GUNMOUNT_MAX; i++) {
		s.gunMount[i].pos = vector3f(0,0,0);
		s.gunMount[i].dir = vector3f(0,0,1);
		s.gunMount[i].sep = 5;
		s.gunMount[i].orient = ShipType::DUAL_LASERS_HORIZONTAL;
	}

	lua_pushstring(L, "gun_mounts");
//.........这里部分代码省略.........
开发者ID:Faiva78,项目名称:pioneer,代码行数:101,代码来源:ShipType.cpp


示例7: SDL_GL_SetAttribute

/**
 * @return whether setting the video mode was successful
 *
 * Sets SDL video mode options/settings
 */
bool SpringApp::SetSDLVideoMode()
{
	int sdlflags = SDL_OPENGL | SDL_RESIZABLE;

	//! w/o SDL_NOFRAME, kde's windowmanager still creates a border (in fullscreen!) and forces a `window`-resize causing a lot of trouble (in the ::SaveWindowPosition)
	sdlflags |= globalRendering->fullScreen ? SDL_FULLSCREEN | SDL_NOFRAME : 0;

	const bool winBorderless = configHandler->GetBool("WindowBorderless");
	sdlflags |= winBorderless ? SDL_NOFRAME : 0;

	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); //! enable alpha channel ???

	globalRendering->depthBufferBits = configHandler->GetInt("DepthBufferBits");
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, globalRendering->depthBufferBits);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, configHandler->GetInt("StencilBufferBits"));
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	//! FullScreen AntiAliasing
	globalRendering->FSAA = Clamp(configHandler->GetInt("FSAALevel"), 0, 8);
	if (globalRendering->FSAA > 0) {
		make_even_number(globalRendering->FSAA);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, globalRendering->FSAA);
	}

	//! use desktop resolution?
	if ((globalRendering->viewSizeX<=0) || (globalRendering->viewSizeY<=0)) {
		const SDL_VideoInfo* screenInfo = SDL_GetVideoInfo(); //! it's a read-only struct (we don't need to free it!)
		globalRendering->viewSizeX = screenInfo->current_w;
		globalRendering->viewSizeY = screenInfo->current_h;
	}
	//! fallback if resolution couldn't be detected
	if ((globalRendering->viewSizeX<=0) || (globalRendering->viewSizeY<=0)) {
		globalRendering->viewSizeX = 1024;
		globalRendering->viewSizeY = 768;
	}

	//! screen will be freed by SDL_Quit()
	//! from: http://sdl.beuc.net/sdl.wiki/SDL_SetVideoMode
	//! Note 3: This function should be called in the main thread of your application.
	//! User note 1: Some have found that enabling OpenGL attributes like SDL_GL_STENCIL_SIZE (the stencil buffer size) before the video mode has been set causes the application to simply ignore those attributes, while enabling attributes after the video mode has been set works fine.
	//! User note 2: Also note that, in Windows, setting the video mode resets the current OpenGL context. You must execute again the OpenGL initialization code (set the clear color or the shade model, or reload textures, for example) after calling SDL_SetVideoMode. In Linux, however, it works fine, and the initialization code only needs to be executed after the first call to SDL_SetVideoMode (although there is no harm in executing the initialization code after each call to SDL_SetVideoMode, for example for a multiplatform application).
	SDL_Surface* screen = SDL_SetVideoMode(globalRendering->viewSizeX, globalRendering->viewSizeY, 32, sdlflags);
	if (!screen) {
		char buf[1024];
		SNPRINTF(buf, sizeof(buf), "Could not set video mode:\n%s", SDL_GetError());
		handleerror(NULL, buf, "ERROR", MBF_OK|MBF_EXCL);
		return false;
	}

#ifdef STREFLOP_H
	//! Something in SDL_SetVideoMode (OpenGL drivers?) messes with the FPU control word.
	//! Set single precision floating point math.
	streflop_init<streflop::Simple>();
#endif

	//! setup GL smoothing
	const int lineSmoothing = configHandler->GetInt("SmoothLines");
	if (lineSmoothing > 0) {
		GLenum hint = GL_FASTEST;
		if (lineSmoothing >= 3) {
			hint = GL_NICEST;
		} else if (lineSmoothing >= 2) {
			hint = GL_DONT_CARE;
		}
		glEnable(GL_LINE_SMOOTH);
		glHint(GL_LINE_SMOOTH_HINT, hint);
	}
	const int pointSmoothing = configHandler->GetInt("SmoothPoints");
	if (pointSmoothing > 0) {
		GLenum hint = GL_FASTEST;
		if (pointSmoothing >= 3) {
			hint = GL_NICEST;
		} else if (pointSmoothing >= 2) {
			hint = GL_DONT_CARE;
		}
		glEnable(GL_POINT_SMOOTH);
		glHint(GL_POINT_SMOOTH_HINT, hint);
	}

	//! setup LOD bias factor
	const float lodBias = Clamp(configHandler->GetFloat("TextureLODBias"), -4.f, 4.f);
	if (fabs(lodBias)>0.01f) {
		glTexEnvf(GL_TEXTURE_FILTER_CONTROL,GL_TEXTURE_LOD_BIAS, lodBias );
	}

	//! there must be a way to see if this is necessary, compare old/new context pointers?
	if (configHandler->GetBool("FixAltTab")) {
		//! free GL resources
		GLContext::Free();

		//! initialize any GL resources that were lost
//.........这里部分代码省略.........
开发者ID:FriedRice,项目名称:spring,代码行数:101,代码来源:SpringApp.cpp


示例8: Clamp

void cCuboid::ClampY(int a_MinY, int a_MaxY)
{
	p1.y = Clamp(p1.y, a_MinY, a_MaxY);
	p2.y = Clamp(p2.y, a_MinY, a_MaxY);
}
开发者ID:Jothle12,项目名称:MCServer,代码行数:5,代码来源:Cuboid.cpp


示例9: PiVerify

void SpaceStation::DockingUpdate(const double timeStep)
{
	vector3d p1, p2, zaxis;
	for (Uint32 i=0; i<m_shipDocking.size(); i++) {
		shipDocking_t &dt = m_shipDocking[i];
		if (!dt.ship) continue;
		// docked stage is m_type->NumDockingPorts() + 1 => ship docked
		if (dt.stage > m_type->NumDockingStages()) continue;

		double stageDuration = (dt.stage > 0 ?
				m_type->GetDockAnimStageDuration(dt.stage-1) :
				m_type->GetUndockAnimStageDuration(abs(dt.stage)-1));
		dt.stagePos += timeStep / stageDuration;

		if (dt.stage == 1) {
			// SPECIAL stage! Docking granted but waiting for ship to dock

			m_doorAnimationStep = 0.3; // open door

			if (dt.stagePos >= 1.0) {
				if (dt.ship == Pi::player)
					Pi::game->log->Add(GetLabel(), Lang::DOCKING_CLEARANCE_EXPIRED);
				dt.ship = 0;
				dt.stage = 0;
				m_doorAnimationStep = -0.3; // close door
			}
			continue;
		}

		if (dt.stagePos > 1.0) {
			// use end position of last segment for start position of new segment
			SpaceStationType::positionOrient_t dport;
			PiVerify(m_type->GetDockAnimPositionOrient(i, dt.stage, 1.0f, dt.fromPos, dport, dt.ship));
			matrix3x3d fromRot = matrix3x3d::FromVectors(dport.xaxis, dport.yaxis, dport.zaxis);
			dt.fromRot = Quaterniond::FromMatrix3x3(fromRot);
			dt.fromPos = dport.pos;

			// transition between docking stages
			dt.stagePos = 0;
			if (dt.stage >= 0) dt.stage++;
			else dt.stage--;
		}

		if (dt.stage < -m_type->ShipLaunchStage() && dt.ship->GetFlightState() != Ship::FLYING) {
			// launch ship
			dt.ship->SetFlightState(Ship::FLYING);
			dt.ship->SetAngVelocity(GetAngVelocity());
			if (m_type->IsSurfaceStation()) {
				dt.ship->SetThrusterState(1, 1.0);	// up
			} else {
				dt.ship->SetThrusterState(2, -1.0);	// forward
			}
			LuaEvent::Queue("onShipUndocked", dt.ship, this);
		}
		if (dt.stage < -m_type->NumUndockStages()) {
			// undock animation finished, clear port
			dt.stage = 0;
			dt.ship = 0;
			LockPort(i, false);
			m_doorAnimationStep = -0.3; // close door
		}
		else if (dt.stage > m_type->NumDockingStages()) {
			// set docked
			dt.ship->SetDockedWith(this, i);
			LuaEvent::Queue("onShipDocked", dt.ship, this);
			LockPort(i, false);
			m_doorAnimationStep = -0.3; // close door
		}
	}

	m_doorAnimationState = Clamp(m_doorAnimationState + m_doorAnimationStep*timeStep, 0.0, 1.0);
	if (m_doorAnimation)
		m_doorAnimation->SetProgress(m_doorAnimationState);
}
开发者ID:Action-Committee,项目名称:pioneer,代码行数:74,代码来源:SpaceStation.cpp


示例10: if


//.........这里部分代码省略.........
            if (astro->IsType(Object::PLANET)) {
                double dist = Pi::player->GetPosition().Length();
                double pressure, density;
                static_cast<Planet*>(astro)->GetAtmosphericState(dist, &pressure, &density);
                if (pressure < 0.001) {
                    // Stop playing surface noise once out of the atmosphere
                    planetSurfaceNoise.Stop();
                }
            }
        }
    } else {
		if (stationNoise.IsPlaying()) {
			float target[2] = {0.0f,0.0f};
			float dv_dt[2] = {1.0f,1.0f};
			stationNoise.VolumeAnimate(target, dv_dt);
			stationNoise.SetOp(Sound::OP_REPEAT | Sound::OP_STOP_AT_TARGET_VOLUME);
		}
		{
			if (Pi::game->IsNormalSpace()) {
				StarSystem *s = Pi::game->GetSpace()->GetStarSystem().Get();
				if (astroNoiseSeed != s->GetSeed()) {
					// change sound!
					astroNoiseSeed = s->GetSeed();
					float target[2] = {0.0f,0.0f};
					float dv_dt[2] = {0.1f,0.1f};
					starNoise.VolumeAnimate(target, dv_dt);
					starNoise.SetOp(Sound::OP_REPEAT | Sound::OP_STOP_AT_TARGET_VOLUME);
					// XXX the way Sound::Event works isn't totally obvious.
					// to destroy the object doesn't stop the sound. it is
					// really just a sound event reference
					starNoise = Sound::Event();
				}
			}
		}
		// when all the sounds are in we can use the body we are in frame of reference to
		if (!starNoise.IsPlaying()) {
			Frame *f = Pi::player->GetFrame();
			if (!f) return; // When player has no frame (game abort) then get outta here!!
			const SystemBody *sbody = f->GetSystemBody();
			const char *sample = 0;
			for (; sbody && !sample; sbody = f->GetSystemBody()) {
				switch (sbody->type) {
					case SystemBody::TYPE_BROWN_DWARF: sample = "Brown_Dwarf_Substellar_Object"; break;
					case SystemBody::TYPE_STAR_M: sample = "M_Red_Star"; break;
					case SystemBody::TYPE_STAR_K: sample = "K_Star"; break;
					case SystemBody::TYPE_WHITE_DWARF: sample = "White_Dwarf_Star"; break;
					case SystemBody::TYPE_STAR_G: sample = "G_Star"; break;
					case SystemBody::TYPE_STAR_F: sample = "F_Star"; break;
					case SystemBody::TYPE_STAR_A: sample = "A_Star"; break;
					case SystemBody::TYPE_STAR_B: sample = "B_Hot_Blue_STAR"; break;
					case SystemBody::TYPE_STAR_O: sample = "Blue_Super_Giant"; break;
					case SystemBody::TYPE_PLANET_GAS_GIANT: {
							if (sbody->mass > fixed(400,1)) {
								sample = "Very_Large_Gas_Giant";
							} else if (sbody->mass > fixed(80,1)) {
								sample = "Large_Gas_Giant";
							} else if (sbody->mass > fixed(20,1)) {
								sample = "Medium_Gas_Giant";
							} else {
								sample = "Small_Gas_Giant";
							}
						}
						break;
					default: sample = 0; break;
				}
				if (sample) {
					starNoise.Play(sample, 0.0f, 0.0f, Sound::OP_REPEAT);
					starNoise.VolumeAnimate(.3f*v_env, .3f*v_env, .05f, .05f);
				} else {
					// go up orbital hierarchy tree to see if we can find a sound
					f = f->GetParent();
					if (f == 0) break;
				}
			}
		}

		Body *astro;
		if ((astro = Pi::player->GetFrame()->GetBody())
			&& Pi::player->GetFrame()->IsRotFrame() && (astro->IsType(Object::PLANET))) {
			double dist = Pi::player->GetPosition().Length();
			double pressure, density;
			static_cast<Planet*>(astro)->GetAtmosphericState(dist, &pressure, &density);
			// maximum volume at around 2km/sec at earth density, pressure
			float volume = float(density * Pi::player->GetVelocity().Length() * 0.0005);
			volume = Clamp(volume, 0.0f, 1.0f) * v_env;
			if (atmosphereNoise.IsPlaying()) {
				float target[2] = {volume, volume};
				float dv_dt[2] = {1.0f,1.0f};
				atmosphereNoise.VolumeAnimate(target, dv_dt);
			} else {
				atmosphereNoise.Play("Atmosphere_Flying", volume, volume, Sound::OP_REPEAT);
			}
		} else {
			float target[2] = {0.0f,0.0f};
			float dv_dt[2] = {1.0f,1.0f};
			atmosphereNoise.VolumeAnimate(target, dv_dt);
			atmosphereNoise.SetOp(Sound::OP_REPEAT | Sound::OP_STOP_AT_TARGET_VOLUME);
		}
	}
}
开发者ID:Metamartian,项目名称:pioneer,代码行数:101,代码来源:AmbientSounds.cpp


示例11: GetFrame

// Calculates the ambiently and directly lit portions of the lighting model taking into account the atmosphere and sun positions at a given location
// 1. Calculates the amount of direct illumination available taking into account
//    * multiple suns
//    * sun positions relative to up direction i.e. light is dimmed as suns set
//    * Thickness of the atmosphere overhead i.e. as atmospheres get thicker light starts dimming earlier as sun sets, without atmosphere the light switches off at point of sunset
// 2. Calculates the split between ambient and directly lit portions taking into account
//    * Atmosphere density (optical thickness) of the sky dome overhead
//        as optical thickness increases the fraction of ambient light increases
//        this takes altitude into account automatically
//    * As suns set the split is biased towards ambient
void ModelBody::CalcLighting(double &ambient, double &direct, const Camera *camera)
{
	const double minAmbient = 0.05;
	ambient = minAmbient;
	direct = 1.0;
	Body *astro = GetFrame()->GetBody();
	if ( ! (astro && astro->IsType(Object::PLANET)) )
		return;

	Planet *planet = static_cast<Planet*>(astro);

	// position relative to the rotating frame of the planet
	vector3d upDir = GetInterpPositionRelTo(planet->GetFrame());
	const double planetRadius = planet->GetSystemBody()->GetRadius();
	const double dist = std::max(planetRadius, upDir.Length());
	upDir = upDir.Normalized();

	double pressure, density;
	planet->GetAtmosphericState(dist, &pressure, &density);
	double surfaceDensity;
	Color cl;
	planet->GetSystemBody()->GetAtmosphereFlavor(&cl, &surfaceDensity);

	// approximate optical thickness fraction as fraction of density remaining relative to earths
	double opticalThicknessFraction = density/EARTH_ATMOSPHERE_SURFACE_DENSITY;

	// tweak optical thickness curve - lower exponent ==> higher altitude before ambient level drops
	// Commenting this out, since it leads to a sharp transition at
	// atmosphereRadius, where density is suddenly 0
	//opticalThicknessFraction = pow(std::max(0.00001,opticalThicknessFraction),0.15); //max needed to avoid 0^power

	if (opticalThicknessFraction < 0.0001)
		return;

	//step through all the lights and calculate contributions taking into account sun position
	double light = 0.0;
	double light_clamped = 0.0;

	const std::vector<Camera::LightSource> &lightSources = camera->GetLightSources();
	for(std::vector<Camera::LightSource>::const_iterator l = lightSources.begin();
			l != lightSources.end(); ++l) {
		double sunAngle;
		// calculate the extent the sun is towards zenith
		if (l->GetBody()){
			// relative to the rotating frame of the planet
			const vector3d lightDir = (l->GetBody()->GetInterpPositionRelTo(planet->GetFrame()).Normalized());
			sunAngle = lightDir.Dot(upDir);
		} else {
			// light is the default light for systems without lights
			sunAngle = 1.0;
		}

		const double critAngle = -sqrt(dist*dist-planetRadius*planetRadius)/dist;

		//0 to 1 as sunangle goes from critAngle to 1.0
		double sunAngle2 = (Clamp(sunAngle, critAngle, 1.0)-critAngle)/(1.0-critAngle);

		// angle at which light begins to fade on Earth
		const double surfaceStartAngle = 0.3;
		// angle at which sun set completes, which should be after sun has dipped below the horizon on Earth
		const double surfaceEndAngle = -0.18;

		const double start = std::min((surfaceStartAngle*opticalThicknessFraction),1.0);
		const double end = std::max((surfaceEndAngle*opticalThicknessFraction),-0.2);

		sunAngle = (Clamp(sunAngle-critAngle, end, start)-end)/(start-end);

		light += sunAngle;
		light_clamped += sunAngle2;
	}

	light_clamped /= lightSources.size();
	light /= lightSources.size();

	// brightness depends on optical depth and intensity of light from all the stars
	direct = 1.0 -  Clamp((1.0 - light),0.0,1.0) * Clamp(opticalThicknessFraction,0.0,1.0);

	// ambient light fraction
	// alter ratio between directly and ambiently lit portions towards ambiently lit as sun sets
	const double fraction = ( 0.2 + 0.8 * (1.0-light_clamped) ) * Clamp(opticalThicknessFraction,0.0,1.0);

	// fraction of light left over to be lit directly
	direct = (1.0-fraction)*direct;

	// scale ambient by amount of light
	ambient = fraction*(Clamp((light),0.0,1.0))*0.25;

	ambient = std::max(minAmbient, ambient);
}
开发者ID:laarmen,项目名称:pioneer,代码行数:99,代码来源:ModelBody.cpp


示例12: gridForRefined

// GridAccel Method Definitions
GridAccel::GridAccel(const vector<Reference<Primitive> > &p,
                     bool forRefined, bool refineImmediately)
    : gridForRefined(forRefined) {
    PBRT_GRID_STARTED_CONSTRUCTION(this, p.size());
    // Create reader-writeer mutex for grid
    rwMutex = RWMutex::Create();

    // Initialize _primitives_ with primitives for grid
    if (refineImmediately)
        for (u_int i = 0; i < p.size(); ++i)
            p[i]->FullyRefine(primitives);
    else
        primitives = p;

    // Compute bounds and choose grid resolution
    for (u_int i = 0; i < primitives.size(); ++i)
        bounds = Union(bounds, primitives[i]->WorldBound());
    Vector delta = bounds.pMax - bounds.pMin;

    // Find _voxelsPerUnitDist_ for grid
    int maxAxis = bounds.MaximumExtent();
    float invMaxWidth = 1.f / delta[maxAxis];
    Assert(invMaxWidth > 0.f);
    float cubeRoot = 3.f * powf(float(primitives.size()), 1.f/3.f);
    float voxelsPerUnitDist = cubeRoot * invMaxWidth;
    for (int axis = 0; axis < 3; ++axis) {
        NVoxels[axis] = Round2Int(delta[axis] * voxelsPerUnitDist);
        NVoxels[axis] = Clamp(NVoxels[axis], 1, 64);
    }
    PBRT_GRID_BOUNDS_AND_RESOLUTION(&bounds, NVoxels);

    // Compute voxel widths and allocate voxels
    for (int axis = 0; axis < 3; ++axis) {
        Width[axis] = delta[axis] / NVoxels[axis];
        InvWidth[axis] = (Width[axis] == 0.f) ? 0.f : 1.f / Width[axis];
    }
    int nVoxels = NVoxels[0] * NVoxels[1] * NVoxels[2];
    voxels = AllocAligned<Voxel *>(nVoxels);
    memset(voxels, 0, nVoxels * sizeof(Voxel *));

    // Add primitives to grid voxels
    for (u_int i = 0; i < primitives.size(); ++i) {
        // Find voxel extent of primitive
        BBox pb = primitives[i]->WorldBound();
        int vmin[3], vmax[3];
        for (int axis = 0; axis < 3; ++axis) {
            vmin[axis] = posToVoxel(pb.pMin, axis);
            vmax[axis] = posToVoxel(pb.pMax, axis);
        }

        // Add primitive to overlapping voxels
        PBRT_GRID_VOXELIZED_PRIMITIVE(vmin, vmax);
        for (int z = vmin[2]; z <= vmax[2]; ++z)
            for (int y = vmin[1]; y <= vmax[1]; ++y)
                for (int x = vmin[0]; x <= vmax[0]; ++x) {
                    int o = offset(x, y, z);
                    if (!voxels[o]) {
                        // Allocate new voxel and store primitive in it
                        voxels[o] = voxelArena.Alloc<Voxel>();
                        *voxels[o] = Voxel(primitives[i]);
                    }
                    else {
                        // Add primitive to already-allocated voxel
                        voxels[o]->AddPrimitive(primitives[i]);
                    }
                }
    }
    PBRT_GRID_FINISHED_CONSTRUCTION(this);
}
开发者ID:jwzhang,项目名称:pbrt-v2,代码行数:70,代码来源:grid.cpp


示例13: if

void CameraApplication::MoveCamera(Entity* cameraEntity, float frameTime)
{
    if (!cameraEntity)
        return;

    Placeable* placeable = cameraEntity->Component<Placeable>();
    if (!placeable)
        return;
    
    InputAPI* input = framework->Input();

    bool changed = false;

    Transform t = placeable->transform.Get();

    float3 rotDelta = float3::zero;

    if (inputContext_->IsMouseButtonDown(Urho3D::MOUSEB_RIGHT))
    {
        rotDelta.x -= input->GetMouseMoveY() * cRotateSpeed;
        rotDelta.y -= input->GetMouseMoveX() * cRotateSpeed;
    }
    else if (inputContext_->GetNumTouches() > 0)
    {
        // Find a touch point that is not on top of the movement joystick button.
        for (int ti=0, len=input->GetNumTouches(); ti<len; ++ti)
        {
            Urho3D::TouchState *touch = input->GetTouch(ti);
            if (!touch->touchedElement_.Get())
            {
                rotDelta -= (float3(static_cast<float>(touch->delta_.y_), static_cast<float>(touch->delta_.x_), 0.f) * cRotateSpeed);
                break;
            }
        }
    }

    if (!rotDelta.Equals(float3::zero))
    {
        RotateChanged.Emit(rotDelta);

        t.rot.x += rotDelta.x;
        t.rot.y += rotDelta.y;
        t.rot.x = Clamp(t.rot.x, -90.0f, 90.0f);
        changed = true;
    }

    float3 moveVector = float3::zero;
    // Note right-handed coordinate system
    if (inputContext_->IsKeyDown(Urho3D::KEY_W))
        moveVector += float3(0.0f, 0.0f, -1.0f);
    if (inputContext_->IsKeyDown(Urho3D::KEY_S))
        moveVector += float3(0.0f, 0.0f, 1.0f);
    if (inputContext_->IsKeyDown(Urho3D::KEY_A))
        moveVector += float3(-1.0f, 0.0f, 0.0f);
    if (inputContext_->IsKeyDown(Urho3D::KEY_D))
        moveVector += float3(1.0f, 0.0f, 0.0f);
    if (inputContext_->IsKeyDown(Urho3D::KEY_SPACE))
        moveVector += float3(0.0f, 1.0f, 0.0f);
    if (inputContext_->IsKeyDown(Urho3D::KEY_C))
        moveVector += float3(0.0f, -1.0f, 0.0f);

    if (!moveVector.Equals(lastMoveVector_))
    {
        lastMoveVector_ = moveVector;
        MoveChanged.Emit(moveVector);
    }

    if (inputContext_->IsKeyPressed(Urho3D::KEY_SHIFT))
        moveVector *= 2;

    if (!moveVector.Equals(float3::zero))
    {
        movementHeld_ = Clamp(movementHeld_ + (frameTime * 4.f), 0.f, 1.0f);
        t.pos += t.Orientation() * (cMoveSpeed * frameTime * moveVector * movementHeld_);
        changed = true;
    }
    else
        movementHeld_ = 0.f;

    // If some other camera (like avatar) is active, do not actually move, only transmit the move signals
    if (changed && cameraEntity == lastCamera_)
        placeable->transform.Set(t);
}
开发者ID:realXtend,项目名称:tundra-urho3d,代码行数:83,代码来源:CameraApplication.cpp


示例14: Clamp

void PhysicsWorld::SetWarmStartFraction(float fraction)
{
	mParams.warmStartFraction = Clamp(fraction, 0.0f, 1.0f);
}
开发者ID:Reticulatas,项目名称:MochaEngineFinal,代码行数:4,代码来源:PhysicsScene.cpp


示例15: Clamp

void CEFX::SetAirAbsorptionFactor(ALfloat value)
{
	airAbsorptionFactor = Clamp(value, AL_MIN_AIR_ABSORPTION_FACTOR, AL_MAX_AIR_ABSORPTION_FACTOR);
}
开发者ID:DoctorEmmettBrown,项目名称:spring,代码行数:4,代码来源:EFX.cpp


示例16: ReleaseCapture

bool
GlueMapWindow::OnMouseUp(PixelScalar x, PixelScalar y)
{
    if (drag_mode != DRAG_NONE)
        ReleaseCapture();

    // Ignore single click event if double click detected
    if (ignore_single_click) {
        ignore_single_click = false;
        return true;
    }

    int click_time = mouse_down_clock.Elapsed();
    mouse_down_clock.Reset();

    DragMode old_drag_mode = drag_mode;
    drag_mode = DRAG_NONE;

    switch (old_drag_mode) {
    case DRAG_NONE:
        /* skip the arm_mapitem_list check below */
        return false;

#ifdef HAVE_MULTI_TOUCH
    case DRAG_MULTI_TOUCH_PAN:
        follow_mode = FOLLOW_SELF;
        ::PanTo(visible_projection.GetGeoScreenCenter());
        return true;
#endif

    case DRAG_PAN:
#ifndef ENABLE_OPENGL
        /* allow the use of the stretched last buffer for the next two
           redraws */
        scale_buffer = 2;
#endif

#ifdef ENABLE_OPENGL
        kinetic_x.MouseUp(x);
        kinetic_y.MouseUp(y);
        kinetic_timer.Schedule(30);
#endif
        break;

    case DRAG_SIMULATOR:
        if (click_time > 50 &&
                compare_squared(drag_start.x - x, drag_start.y - y,
                                Layout::Scale(36)) == 1) {
            GeoPoint location = visible_projection.ScreenToGeo(x, y);

            double distance = hypot(drag_start.x - x, drag_start.y - y);

            // This drag moves the aircraft (changes speed and direction)
            const Angle old_bearing = CommonInterface::Basic().track;
            const auto min_speed = fixed(1.1) *
                                   CommonInterface::GetComputerSettings().polar.glide_polar_task.GetVMin();
            const Angle new_bearing = drag_start_geopoint.Bearing(location);
            if (((new_bearing - old_bearing).AsDelta().AbsoluteDegrees() < fixed(30)) ||
                    (CommonInterface::Basic().ground_speed < min_speed))
                device_blackboard->SetSpeed(Clamp(fixed(distance) / Layout::FastScale(3),
                                                  min_speed, fixed(100)));

            device_blackboard->SetTrack(new_bearing);
            // change bearing without changing speed if direction change > 30
            // 20080815 JMW prevent dragging to stop glider

            return true;
        }

        break;

    case DRAG_GESTURE:
        const TCHAR* gesture = gestures.Finish();
        if (gesture && OnMouseGesture(gesture))
            return true;

        break;
    }

    if (arm_mapitem_list) {
        map_item_timer.Schedule(200);
        return true;
    }

    return false;
}
开发者ID:ThomasXBMC,项目名称:XCSoar,代码行数:86,代码来源:GlueMapWindowEvents.cpp


示例17: timeStep

// main
void PhysicsWorld::Step(float dt, unsigned char velocityIterations, unsigned char positionIterations)
{
	const TimeStep timeStep(dt, velocityIterations, positionIterations, mParams, mStats);
	Stopwatch timer;
	mStats.Clear();

	// update rigid bodies
	const float linearDampFactor = 1.0f - Clamp(mParams.linearDamping  * timeStep.dt, 0.0f, 1.0f);
	const float angularDampFactor = 1.0f - Clamp(mParams.angularDamping * timeStep.dt, 0.0f, 1.0f);
	timer.Start();
	for (auto &body : mRigidBodies)
	{
		// TODOKai mass
		if (!body.CollidersValid())
			body.ValidateColliders();

		// update
		body.UpdateMassAndLocalCentroid();
		body.UpdateOrientation();
		body.UpdatePositionFromGlobalCentroid();
		body.UpdateGlobalInverseInertiaTensor();
		body.UpdateProxies();

		timeStep.stats.colliders += body.mColliders.size();
	}
	timeStep.stats.rigidBodies = mRigidBodies.size();
	timeStep.stats.integration += timer.Stop();

	// broadphase
	timer.Start();
	auto &pairList = mBroadphase->ComputePairs();
	timeStep.stats.broadphasePairs = pairList.size();
	timeStep.stats.broadphase += timer.Stop();

	// narrowphase
	timer.Start();
	mContactManager.PreNarrowphase();
	for (ColliderPair &pair : pairList)
	{
		Collider *colliderA = pair.mCollider1;
		Collider *colliderB = pair.mCollider2;
		RigidBody &bodyA = *colliderA->mParent;
		RigidBody &bodyB = *colliderB->mParent;
		CPhysics* cphyA = bodyA.mParent->cphy;
		CPhysics* cphyB = bodyB.mParent->cphy;

		if (!bodyA.CanCollide(bodyB) || !colliderA->CanBeCollide(*colliderB))
			continue;

		// collision table check
		if (!cphyA->gameObject->GetState()->GetCollisionTable()->GetDoesIDsCollide(cphyA->GetCOllisionID(), cphyB->GetCOllisionID()))
			continue;

		// make sure colliderA is always less than colliderB in memory address for consistency
		if (colliderA > colliderB)
		{
			std::swap(colliderA, colliderB);
			auto temp = cphyA;
			cphyA = cphyB;
			cphyB = temp;
		}


		ContactManifold *manifold = new (mManifoldAllocator.Allocate()) ContactManifold();
		manifold->colliderA = colliderA;
		manifold->colliderB = colliderB;

		//TODO
		manifold->isColliding =
			Collide(*manifold, *colliderA->mGeometry, *colliderB->mGeometry, mContactAllocator);

		if (!manifold->isColliding
			|| !mContactManager.Add(*manifold, mParams.contactPersistenceThreshold * mParams.contactPersistenceThreshold))
		{
			// manifold not colliding OR persistent manifold already exists, delete
			manifold->~ContactManifold();
			mManifoldAllocator.Free(manifold);
		}
		else
		{
			//these will be deleted by the script subsystem
			CollisionData* dataA = new CollisionData();
			CollisionData* dataB = new CollisionData();

			// send manifold to OnCollide function
			{
				dataA->isA = true;
				dataA->collidedObj = cphyB->gameObject;
				dataA->selfCPhy = cphyA;
				dataA->collidedObjCPhy = cphyB;
				dataA->numContacts = manifold->numContacts;
				for (int i = 0; i < dataA->numContacts; ++i)
				{
					dataA->normals.push_back(manifold->contacts[i]->normal);
				}
				ScriptSubsystem::getInstance()->QueueEvent<CollisionData>(cphyA->gameObject, "OnCollisionEnter", dataA);
			}
			{
				dataB->isA = false;
//.........这里部分代码省略.........
开发者ID:Reticulatas,项目名称:MochaEngineFinal,

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ ClampChar函数代码示例发布时间:2022-05-30
下一篇:
C++ CkpvAccess函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap