public void Render() { // Record all the commands we need to render the scene into the command list. PopulateCommandList(); // Execute the command list. commandQueue.ExecuteCommandList(commandList); // Acquire our wrapped render target resource for the current back buffer. device11on12.AcquireWrappedResources(new SharpDX.Direct3D11.Resource[] { wrappedBackBuffers[frameIndex] }, 1); direct2DRenderTarget[frameIndex].BeginDraw(); int time = Environment.TickCount % 10000; int t = time / 2000; float f = (time - (t * 2000)) / 2000.0F; textBrush.Color = Color4.Lerp(colors[t], colors[t + 1], f); direct2DRenderTarget[frameIndex].DrawText("Hello Text", textFormat, new SharpDX.Mathematics.Interop.RawRectangleF((float)Math.Sin(Environment.TickCount / 1000.0F) * 200 + 400, 10, 2000, 500), textBrush); direct2DRenderTarget[frameIndex].EndDraw(); //Release wrapped render target resource device11on12.ReleaseWrappedResources(new SharpDX.Direct3D11.Resource[] { wrappedBackBuffers[frameIndex] }, 1); // Flush to submit the 11 command list to the shared command queue. deviceContext11.Flush(); // Present the frame. swapChain.Present(1, 0); WaitForPreviousFrame(); }
/// <summary> /// Does perpixel processing with given function /// </summary> /// <param name="procFunc"></param> public void PerpixelProcessing(Func <Color4, Color4> procFunc, float amount = 1) { for (int i = 0; i < RawImageData.Length; i++) { RawImageData[i] = Color4.Lerp(RawImageData[i], procFunc(RawImageData[i]), amount); } }
/// <summary> /// Updates the field by interpolating between two sampled values over the particle's lifetime /// </summary> /// <param name="pool">Target <see cref="ParticlePool"/></param> private unsafe void UpdateDoubleSampler(ParticlePool pool) { var colorField = pool.GetField(ParticleFields.Color); var lifeField = pool.GetField(ParticleFields.Life); var randField = pool.GetField(ParticleFields.RandomSeed); foreach (var particle in pool) { var life = 1f - (*((float *)particle[lifeField])); // The Life field contains remaining life, so for sampling we take (1 - life) var randSeed = particle.Get(randField); var lerp = randSeed.GetFloat(RandomOffset.Offset1A + SeedOffset); var colorMin = SamplerMain.Evaluate(life); var colorMax = SamplerOptional.Evaluate(life); var color = Color4.Lerp(colorMin, colorMax, lerp); // Premultiply alpha color.R *= color.A; color.G *= color.A; color.B *= color.A; (*((Color4 *)particle[colorField])) = color; } }
internal override void OnUpdate() { DayWatch watch = DayWatch.Now; PrevPosition = Position; Position = watch.SunPosition * 180f; float amount = watch.SunHeight; Color4 c; if (watch.IsDay) { if (amount < 0.4) { c = Color4.Lerp(new Color4(1, 1, 1, 0), new Color4(1, 1, 0.2f, 0), 1 - (amount / 0.4f)); } else { c = Color4.Lerp(new Color4(1, 1, 1, 0.8f), new Color4(1, 1, 1, 0), 1 - (amount - 0.4f) / 0.6f); } } else { c = new Color4(1, 1, 0.2f, 0); } Color = c.ToVector4(); Position.X += World.Instance.Player.Position.X; Position.Y += 0; Position.Z += World.Instance.Player.Position.Z; }
/// <summary> /// Sample with filtering /// </summary> /// <param name="x">value within range 0..1</param> /// <param name="y">value within range 0..1</param> /// <param name="wrap"></param> /// <returns></returns> public Color4 Sample(float x, float y, bool wrap = true, bool useCosineInterpolation = false) { var tx = Frac(x * Width); var ty = Frac(y * Height); int x0 = Wrap((int)(x * Width), Width); int x1 = Wrap((int)(x * Width + 1), Width); int y0 = Wrap((int)(y * Height), Height); int y1 = Wrap((int)(y * Height + 1), Height); // xy var v00 = Sample(x0, y0, wrap); var v01 = Sample(x0, y1, wrap); var v10 = Sample(x1, y0, wrap); var v11 = Sample(x1, y1, wrap); if (useCosineInterpolation) { var v0x = CosLerp(v00, v01, ty); var v1x = CosLerp(v10, v11, ty); return(CosLerp(v0x, v1x, tx)); } else { var v0x = Color4.Lerp(v00, v01, ty); var v1x = Color4.Lerp(v10, v11, ty); return(Color4.Lerp(v0x, v1x, tx)); } }
public unsafe override void Initialize(ParticlePool pool, int startIdx, int endIdx, int maxCapacity) { if (!pool.FieldExists(ParticleFields.Color4) || !pool.FieldExists(ParticleFields.RandomSeed)) { return; } var colField = pool.GetField(ParticleFields.Color4); var rndField = pool.GetField(ParticleFields.RandomSeed); var i = startIdx; while (i != endIdx) { var particle = pool.FromIndex(i); var randSeed = particle.Get(rndField); var color = Color4.Lerp(ColorMin, ColorMax, randSeed.GetFloat(RandomOffset.Offset1A + SeedOffset)); // Premultiply alpha // This can't be done in advance for ColorMin and ColorMax because it will change the math color.R *= color.A; color.G *= color.A; color.B *= color.A; (*((Color4 *)particle[colField])) = color; i = (i + 1) % maxCapacity; } }
internal void ClearTarget() { DayWatch watch = DayWatch.Now; BackgroundColor = Color4.Lerp(new Color4(0.8f, 0.8f, 1f), new Color4(0f, 0f, 0f), 1f - watch.SunHeight); device.ImmediateContext.ClearRenderTargetView(renderView, BackgroundColor); device.ImmediateContext.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); }
public Color4 Evaluate(float offset) { GradientStop gsFrom; GradientStop gsTo; FindStops(offset, out gsFrom, out gsTo); return(Color4.Lerp(gsFrom.Color, gsTo.Color, offset * (gsTo.Offset - gsFrom.Offset))); }
Color4 SunColor(Vector3 dir) { Color4 dusk = new Color4(Temperature.Get(2000), 1); Color4 zenith = new Color4(Temperature.Get(Params.SunTemperature), 1); Vector3 ndir = dir.Normalized(); return(Color4.Lerp(dusk, zenith, (float)Math.Pow(ndir.Y, 0.5f))); }
protected override PixelShaderInput LerpPixelShaderInput(PixelShaderInput from, PixelShaderInput to, float perc) { var v = new PixelShaderInput(); v.TransformedPosition = TransformedPosition.Lerp(from.TransformedPosition, to.TransformedPosition, perc); v.Color = Color4.Lerp(from.Color, to.Color, perc); return(v); }
/// <summary>Blend the colors together</summary> public void Blend(ControlState state, float elapsedTime, float rate) { if ((States == null) || (States.Length == 0)) { return; // Nothing to do } Color4 destColor = States[(int)state]; Current = Color4.Lerp(Current, destColor, 1.0f - (float)Math.Pow(rate, 30 * elapsedTime)); }
private Color4 ColorForStatus(CircleStatus status) { if (status.MinDistance >= 2 * CircleRadius - Precision) { return(Color4.Green); } var relativeDistance = status.MinDistance / CircleRadius; return(Color4.Lerp(Color4.Red, Color4.Yellow, MathHelper.Clamp(MathHelper.Pow(relativeDistance - 1, 32), 0, 1))); }
public override void Update() { base.Update(); if (Keyboard.IsKeyDown(Profiles.Current.KeyUp)) { Force += new Vector2((float)Math.Cos(Orientation), (float)Math.Sin(Orientation)) * 5000000.0f; if (!isThrusting) { Sounds.Jet.Start(); isThrusting = true; } MakeExhaustFire(); } else if (isThrusting) { Sounds.Jet.Stop(); isThrusting = false; } if (Keyboard.IsKeyDown(Profiles.Current.KeyLeft)) { Torque += 50000000.0f; } if (Keyboard.IsKeyDown(Profiles.Current.KeyRight)) { Torque -= 50000000.0f; } if (Keyboard.IsKeyDown(Key.Escape)) { if (GameRoot.Instance.isRunning) { GameRoot.Instance.Stop(); } } if (Keyboard.IsKeyDown(Profiles.Current.KeyStop)) { Velocity *= 0.97f; Omega *= 0.97f; float hue1 = 6; float hue2 = (hue1 + rand.NextFloat(0, 2)) % 6f; Color4 color1 = ColorUtil.HSVToColor(hue1, 0.5f, 1); Color4 color2 = ColorUtil.HSVToColor(hue2, 0.5f, 1); for (int i = 0; i < 30; i++) { float speed = 1.0f * (1.0f - 1 / rand.NextFloat(1, 5)); Color4 color = Color4.Lerp(color1, color2, rand.NextFloat(0, 1)); Vector2 dir = rand.NextVector2(1, 1); ParticleManager.CreateParticle(Instance.Position + dir * 40, color, 190, Vector2.One, dir * speed, 0.2f); } } }
public static Func <Vector2, Color4> RadialColorGradient(Func <double, double> easingFunc, Vector2 centre, float radius, Color4 centreColor, Color4 perimiterColor) { return((Vector2 v) => { if (radius == 0) { return perimiterColor; } return centreColor.Lerp(perimiterColor, (float)easingFunc((v - centre).Length / radius)); }); }
public static Vertex Lerp(Vertex min, Vertex max, float factor) { Vertex v = new Vertex(); v.position = Vector3.Lerp(min.position, max.position, factor); v.rhw = MathUtility.Lerp(min.rhw, max.rhw, factor); v.u = MathUtility.Lerp(min.u, max.u, factor); v.v = MathUtility.Lerp(min.v, max.v, factor); v.color = Color4.Lerp(min.color, max.color, factor); return(v); }
public void Quantize(int numLevels, float amount = 1) { //Saturate( 0 ); PerpixelProcessing(v => { var v1 = new Color4(); v1.Red = QuantizeValue(v.Red, numLevels); v1.Green = QuantizeValue(v.Green, numLevels); v1.Blue = QuantizeValue(v.Blue, numLevels); v1.Alpha = QuantizeValue(v.Alpha, numLevels); return(Color4.Lerp(v, v1, amount)); }); }
/// <summary> /// Updates the field by interpolating between two sampled values over the particle's lifetime /// </summary> /// <param name="pool">Target <see cref="ParticlePool"/></param> private unsafe void UpdateDoubleSampler(ParticlePool pool) { var colorField = pool.GetField(ParticleFields.Color); var lifeField = pool.GetField(ParticleFields.Life); var randField = pool.GetField(ParticleFields.RandomSeed); int count = pool.NextFreeIndex; for (int i = 0; i < count; i++) { Particle particle = pool.FromIndex(i); var life = 1f - (*((float *)particle[lifeField])); // The Life field contains remaining life, so for sampling we take (1 - life) var randSeed = particle.Get(randField); var lerp = randSeed.GetFloat(RandomOffset.Offset1A + SeedOffset); var colorMin = SamplerMain.Evaluate(life); var colorMax = SamplerOptional.Evaluate(life); var color = Color4.Lerp(colorMin, colorMax, lerp); // preserve any colors? if (pool.SpecificColors != null) { if (color.A < 0f) { color.A = pool.SpecificColors[i].A; } if (color.R < 0f) { color.R = pool.SpecificColors[i].R; } if (color.G < 0f) { color.G = pool.SpecificColors[i].G; } if (color.B < 0f) { color.B = pool.SpecificColors[i].B; } } // Premultiply alpha color.R *= color.A; color.G *= color.A; color.B *= color.A; (*((Color4 *)particle[colorField])) = color; } }
/// <summary> /// Updates the highlight material animation /// </summary> public void UpdateHighlighting(GameBase game) { float elapsedTotalSeconds = (float)game.UpdateTime.Elapsed.TotalSeconds; if (highlightTimer > 0) { if ((highlightTimer -= elapsedTotalSeconds) <= 0.0f) { highlightTimer = 0.0f; } float c = highlightTimer / HighlightDuration; var color = Color4.Lerp(Color, new Color4(2.0f, 0.1f, 0.1f, 1.0f), c); Color4 deviceSpaceColor = color.ToColorSpace(game.GraphicsDevice.ColorSpace); deviceSpaceColor.A = 0.33f; HighlightMaterial.Passes[0].Parameters.Set(MaterialKeys.DiffuseValue, deviceSpaceColor); HighlightMaterial.Passes[0].Parameters.Set(MaterialKeys.EmissiveValue, deviceSpaceColor); HighlightMaterial.Passes[0].Parameters.Set(MaterialKeys.EmissiveIntensity, 1.0f); } }
public unsafe override void Initialize(ParticlePool pool, int startIdx, int endIdx, int maxCapacity) { if (!pool.FieldExists(ParticleFields.Color4) || !pool.FieldExists(ParticleFields.RandomSeed)) { return; } var colField = pool.GetField(ParticleFields.Color4); var rndField = pool.GetField(ParticleFields.RandomSeed); var i = startIdx; while (i != endIdx) { var particle = pool.FromIndex(i); var randSeed = particle.Get(rndField); (*((Color4 *)particle[colField])) = Color4.Lerp(ColorMin, ColorMax, randSeed.GetFloat(RandomOffset.Offset1A + SeedOffset)); i = (i + 1) % maxCapacity; } }
/// <summary> /// Gets the sun color based on time of day /// </summary> /// <param name="timeOfDay">Time of day class</param> /// <returns>Returns the color base on time of day meridian angle</returns> private Color4 GetSunColor(TimeOfDay timeOfDay) { float angle = MathUtil.Clamp(timeOfDay.MeridianAngle - MathUtil.PiOverTwo, 0, MathUtil.Pi); for (int i = 0; i < this.SunColorPalette.Count; i++) { if (this.SunColorPalette[i].Item1 > angle) { if (i > 0) { var from = this.SunColorPalette[i - 1]; var to = this.SunColorPalette[i]; float amount = (angle - from.Item1) / (to.Item1 - from.Item1); return(Color4.Lerp(from.Item2, to.Item2, amount)); } else { return(this.SunColorPalette[i].Item2); } } } return(Color4.White); }
/// <summary> /// Performs a linear interpolation between two colors /// </summary> /// <param name="color1">Color 1</param> /// <param name="color2">Color 2</param> /// <param name="value">Value between interpolated colors</param> /// <returns></returns> public static Color Lerp(Color color1, Color color2, float value) { return(new Color(Color4.Lerp(color1.RawColor, color2.RawColor, value))); }
public override void Draw(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) { base.Draw(context, renderView, renderViewStage, startIndex, endIndex); BlendStateDescription? previousBlendState = null; DepthStencilStateDescription?previousDepthStencilState = null; EffectInstance previousEffect = null; //TODO string comparison ...? var isPicking = RenderSystem.RenderStages[renderViewStage.Index].Name == "Picking"; var hasBegin = false; for (var index = startIndex; index < endIndex; index++) { var renderNodeReference = renderViewStage.SortedRenderNodes[index].RenderNode; var renderNode = GetRenderNode(renderNodeReference); var spriteState = (RenderSpriteStudio)renderNode.RenderObject; var depthStencilState = DepthStencilStates.DepthRead; foreach (var node in spriteState.SortedNodes) { if (node.Sprite?.Texture == null || node.Sprite.Region.Width <= 0 || node.Sprite.Region.Height <= 0f || node.Hide != 0) { continue; } // Update the sprite batch BlendStateDescription spriteBlending; switch (node.BaseNode.AlphaBlending) { case SpriteStudioBlending.Mix: spriteBlending = BlendStates.AlphaBlend; break; case SpriteStudioBlending.Multiplication: spriteBlending = MultBlendState; break; case SpriteStudioBlending.Addition: spriteBlending = BlendStates.Additive; break; case SpriteStudioBlending.Subtraction: spriteBlending = SubBlendState; break; default: throw new ArgumentOutOfRangeException(); } // TODO: this should probably be moved to Prepare() // Project the position // TODO: This could be done in a SIMD batch, but we need to figure-out how to plugin in with RenderMesh object var worldPosition = new Vector4(spriteState.WorldMatrix.TranslationVector, 1.0f); Vector4 projectedPosition; Vector4.Transform(ref worldPosition, ref renderView.ViewProjection, out projectedPosition); var projectedZ = projectedPosition.Z / projectedPosition.W; var blendState = isPicking ? BlendStates.Default : spriteBlending; // TODO: the current impementation to determine if the sprite is selected does not work. This should be fixed later at some point //var currentEffect = isPicking ? GetOrCreatePickingSpriteEffect() : ShadowObject.IsObjectSelected(spriteState.SpriteStudioComponent) ? GetOrCreateSelectedSpriteEffect() : null; var currentEffect = isPicking ? GetOrCreatePickingSpriteEffect() : null; // TODO remove this code when material are available if (previousEffect != currentEffect || blendState != previousBlendState || depthStencilState != previousDepthStencilState) { if (hasBegin) { sprite3DBatch.End(); } sprite3DBatch.Begin(context.GraphicsContext, renderView.ViewProjection, SpriteSortMode.Deferred, blendState, null, depthStencilState, RasterizerStates.CullNone, currentEffect); hasBegin = true; } previousEffect = currentEffect; previousBlendState = blendState; previousDepthStencilState = depthStencilState; var sourceRegion = node.Sprite.Region; var texture = node.Sprite.Texture; // skip the sprite if no texture is set. if (texture == null) { continue; } var color4 = Color4.White; if (isPicking) { // TODO move this code corresponding to picking out of the runtime code. color4 = new Color4(RuntimeIdHelper.ToRuntimeId(spriteState.Source)); } else { if (node.BlendFactor > 0.0f) { switch (node.BlendType) //todo this should be done in a shader { case SpriteStudioBlending.Mix: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; case SpriteStudioBlending.Multiplication: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; case SpriteStudioBlending.Addition: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; case SpriteStudioBlending.Subtraction: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; default: throw new ArgumentOutOfRangeException(); } } else { color4 *= node.FinalTransparency; } } Matrix.Multiply(ref node.ModelTransform, ref spriteState.WorldMatrix, out var worldMatrix); // calculate normalized position of the center of the sprite (takes into account the possible rotation of the image) var normalizedCenter = new Vector2(node.Sprite.Center.X / sourceRegion.Width - 0.5f, 0.5f - node.Sprite.Center.Y / sourceRegion.Height); if (node.Sprite.Orientation == ImageOrientation.Rotated90) { var oldCenterX = normalizedCenter.X; normalizedCenter.X = -normalizedCenter.Y; normalizedCenter.Y = oldCenterX; } // apply the offset due to the center of the sprite var size = node.Sprite.Size; var centerOffset = Vector2.Modulate(normalizedCenter, size); worldMatrix.M41 -= centerOffset.X * worldMatrix.M11 + centerOffset.Y * worldMatrix.M21; worldMatrix.M42 -= centerOffset.X * worldMatrix.M12 + centerOffset.Y * worldMatrix.M22; // draw the sprite sprite3DBatch.Draw(texture, ref worldMatrix, ref sourceRegion, ref size, ref color4, node.Sprite.Orientation, SwizzleMode.None, projectedZ); } } if (hasBegin) { sprite3DBatch.End(); } }
/// <summary> /// スプライト頂点データを更新する /// </summary> /// <param name="drawSprite"></param> /// <returns></returns> public int VertexUpdate( MCDrawSquareAmountSprite drawSprite ) { int dwTmp; var pSprite = drawSprite.Sprite; int divNo = drawSprite.DivNo; float startX, startY, midX, midY, endX, endY; float startU, startV, midU, midV, endU, endV; float factorU, factorV; startX = pSprite.Anchor.X; // -0.5f; startY = pSprite.Anchor.Y; // +0.5f; if (pSprite.flags.SpriteType == (uint)MC_SPRITE_DATA.SIMPLE) { endX = pSprite.Width + startX; endY = -(pSprite.Height - startY); startU = pSprite.spl.StartU; startV = pSprite.spl.StartV; endU = pSprite.spl.EndU; endV = pSprite.spl.EndV; } else { endX = (pSprite.div.DivW_U * pSprite.Width) + startX; endY = -((pSprite.div.DivH_V * pSprite.Height) - startY); if (pSprite.div.Col == 0) { factorV = (1.0f / pSprite.div.Row); startU = 0.0f; startV = factorV * divNo; endU = 1.0f; endV = startV + factorV; } else if (pSprite.div.Row == 0) { factorU = (1.0f / pSprite.div.Col); startU = factorU * divNo; startV = 0.0f; endU = startU + factorU; endV = 1.0f; } else { dwTmp = divNo % pSprite.div.Col; startU = pSprite.div.DivW_U * dwTmp; dwTmp = divNo / pSprite.div.Col; startV = pSprite.div.DivH_V * dwTmp; endU = startU + pSprite.div.DivW_U; endV = startV + pSprite.div.DivH_V; } } midX = (startX + endX) * 0.5f; midY = (startY + endY) * 0.5f; midU = (startU + endU) * 0.5f; midV = (startV + endV) * 0.5f; //------------------------- // 中間色の作成 //------------------------- var aColor = drawSprite.Colors; Color4[] aMidColor = new Color4[5]; aMidColor[0] = Color4.Lerp(aColor[0], aColor[1], 0.5f); aMidColor[1] = Color4.Lerp(aColor[1], aColor[2], 0.5f); aMidColor[2] = Color4.Lerp(aColor[2], aColor[3], 0.5f); aMidColor[3] = Color4.Lerp(aColor[3], aColor[4], 0.5f); aMidColor[4] = Color4.Lerp(aMidColor[0], aMidColor[2], 0.5f); //------------------------------ // 頂点情報 // // 7--0--1 // | | | // 6--8--2 // | | | // 5--4--3 //------------------------------ MC_VERTEX_PCTx[] aV = new MC_VERTEX_PCTx[] { new MC_VERTEX_PCTx(new MCVector3(midX, startY, 0), aMidColor[0], midU, startV), // 0 new MC_VERTEX_PCTx(new MCVector3(endX, startY, 0), aColor[1], endU, startV), // 1 new MC_VERTEX_PCTx(new MCVector3(endX, midY, 0), aMidColor[1], endU, midV), // 2 new MC_VERTEX_PCTx(new MCVector3(endX, endY, 0), aColor[2], endU, endV), // 3 new MC_VERTEX_PCTx(new MCVector3(midX, endY, 0), aMidColor[2], midU, endV), // 4 new MC_VERTEX_PCTx(new MCVector3(startX, endY, 0), aColor[3], startU, endV), // 5 new MC_VERTEX_PCTx(new MCVector3(startX, midY, 0), aMidColor[3], startU, midV), // 6 new MC_VERTEX_PCTx(new MCVector3(startX, startY, 0), aColor[0], startU, startV), // 7 new MC_VERTEX_PCTx(new MCVector3(midX, midY, 0), aMidColor[4], midU, midV), // 8 new MC_VERTEX_PCTx(new MCVector3(midX, startY, 0), aMidColor[0], midU, startV), // 9(0), }; Action <int> SG_UV_C_9_SET = (_idx) => { aV[_idx].u = midU; aV[_idx].v = startV; aV[_idx].c = aMidColor[0]; }; Action <int> SG_UV_C_0_SET = (_idx) => { aV[_idx].u = midU; aV[_idx].v = startV; aV[_idx].c = aMidColor[0]; }; Action <int> SG_UV_C_1_SET = (_idx) => { aV[_idx].u = endU; aV[_idx].v = startV; aV[_idx].c = aColor[1]; }; Action <int> SG_UV_C_2_SET = (_idx) => { aV[_idx].u = endU; aV[_idx].v = midV; aV[_idx].c = aMidColor[1]; }; Action <int> SG_UV_C_3_SET = (_idx) => { aV[_idx].u = endU; aV[_idx].v = endV; aV[_idx].c = aColor[2]; }; Action <int> SG_UV_C_4_SET = (_idx) => { aV[_idx].u = midU; aV[_idx].v = endV; aV[_idx].c = aMidColor[2]; }; Action <int> SG_UV_C_5_SET = (_idx) => { aV[_idx].u = startU; aV[_idx].v = endV; aV[_idx].c = aColor[3]; }; Action <int> SG_UV_C_6_SET = (_idx) => { aV[_idx].u = startU; aV[_idx].v = midV; aV[_idx].c = aMidColor[3]; }; Action <int> SG_UV_C_7_SET = (_idx) => { aV[_idx].u = startU; aV[_idx].v = midV; aV[_idx].c = aColor[0]; }; Action <int> SG_UV_C_8_SET = (_idx) => { aV[_idx].u = midU; aV[_idx].v = midV; aV[_idx].c = aMidColor[4]; }; // 回転 if ((drawSprite.Flip & SPRITE_FLIP.R90) != 0) { SG_UV_C_2_SET(9); SG_UV_C_2_SET(0); SG_UV_C_3_SET(1); SG_UV_C_4_SET(2); SG_UV_C_5_SET(3); SG_UV_C_6_SET(4); SG_UV_C_7_SET(5); SG_UV_C_0_SET(6); SG_UV_C_1_SET(7); } else if ((drawSprite.Flip & SPRITE_FLIP.R180) != 0) { SG_UV_C_4_SET(9); SG_UV_C_4_SET(0); SG_UV_C_5_SET(1); SG_UV_C_6_SET(2); SG_UV_C_7_SET(3); SG_UV_C_0_SET(4); SG_UV_C_1_SET(5); SG_UV_C_2_SET(6); SG_UV_C_3_SET(7); } else if ((drawSprite.Flip & SPRITE_FLIP.R270) != 0) { SG_UV_C_6_SET(9); SG_UV_C_6_SET(0); SG_UV_C_7_SET(1); SG_UV_C_0_SET(2); SG_UV_C_1_SET(3); SG_UV_C_2_SET(4); SG_UV_C_3_SET(5); SG_UV_C_4_SET(6); SG_UV_C_5_SET(7); } SPRITE_FLIP tempFlip = (SPRITE_FLIP)(drawSprite.Flip & SPRITE_FLIP.V_H); Color4 tmpColor; float tmpUV; Action <int, int> SG_UV_C_SWAP = (_idx1, _idx2) => { tmpUV = aV[_idx2].u; aV[_idx2].u = aV[_idx1].u; aV[_idx1].u = tmpUV; tmpUV = aV[_idx2].v; aV[_idx2].v = aV[_idx1].v; aV[_idx1].v = tmpUV; tmpColor = aV[_idx2].c; aV[_idx2].c = aV[_idx1].c; aV[_idx1].c = tmpColor; }; if (tempFlip == SPRITE_FLIP.HORIZONTAL) { //-------------- // 左右反転 //-------------- SG_UV_C_SWAP(7, 1); SG_UV_C_SWAP(6, 2); SG_UV_C_SWAP(5, 3); } else if (tempFlip == SPRITE_FLIP.VERTICAL) { //-------------- // 上下反転 //-------------- SG_UV_C_SWAP(7, 5); SG_UV_C_SWAP(0, 4); SG_UV_C_4_SET(9); SG_UV_C_SWAP(1, 3); } else if (tempFlip == SPRITE_FLIP.V_H) { //-------------- // 上下左右反転 //-------------- SG_UV_C_SWAP(7, 3); SG_UV_C_SWAP(0, 4); SG_UV_C_4_SET(9); SG_UV_C_SWAP(1, 5); SG_UV_C_SWAP(6, 2); } // 頂点の変形 VertexTransformation(drawSprite, aV); DataStream MappedResource; var box = App.ImmediateContext.MapSubresource( m_vertexBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out MappedResource); unsafe { var pV = (MC_VERTEX_PCTx *)MappedResource.DataPointer; for (int i = 0; i < VERTEX_NUM; ++i) { pV[i].Set(aV[i].p, aV[i].c, aV[i].u, aV[i].v); } } App.ImmediateContext.UnmapSubresource(m_vertexBuffer, 0); return(0); }
protected override void DrawCore(RenderContext context, RenderItemCollection renderItems, int fromIndex, int toIndex) { var viewParameters = context.Parameters; var device = context.GraphicsDevice; var viewProjection = viewParameters.Get(TransformationKeys.ViewProjection); BlendState previousBlendState = null; DepthStencilState previousDepthStencilState = null; Effect previousEffect = null; var isPicking = context.IsPicking(); bool hasBegin = false; for (var i = fromIndex; i <= toIndex; i++) { var renderItem = renderItems[i]; var spriteState = (SpriteStudioProcessor.Data)renderItem.DrawContext; var transfoComp = spriteState.TransformComponent; var depthStencilState = device.DepthStencilStates.None; foreach (var node in spriteState.SpriteStudioComponent.SortedNodes) { if (node.Sprite?.Texture == null || node.Sprite.Region.Width <= 0 || node.Sprite.Region.Height <= 0f || node.Hide) { continue; } // Update the sprite batch BlendState spriteBlending; switch (node.BaseNode.AlphaBlending) { case SpriteStudioBlending.Mix: spriteBlending = device.BlendStates.AlphaBlend; break; case SpriteStudioBlending.Multiplication: spriteBlending = MultBlendState; break; case SpriteStudioBlending.Addition: spriteBlending = device.BlendStates.Additive; break; case SpriteStudioBlending.Subtraction: spriteBlending = SubBlendState; break; default: throw new ArgumentOutOfRangeException(); } var blendState = isPicking ? device.BlendStates.Opaque : renderItems.HasTransparency ? spriteBlending : device.BlendStates.Opaque; var currentEffect = isPicking ? GetOrCreatePickingSpriteEffect() : spriteState.SpriteStudioComponent.Tags.Get(IsEntitySelected) ? GetOrCreateSelectedSpriteEffect() : null; // TODO remove this code when material are available if (previousEffect != currentEffect || blendState != previousBlendState || depthStencilState != previousDepthStencilState) { if (hasBegin) { sprite3DBatch.End(); } sprite3DBatch.Begin(viewProjection, SpriteSortMode.Deferred, blendState, null, depthStencilState, device.RasterizerStates.CullNone, currentEffect); hasBegin = true; } previousEffect = currentEffect; previousBlendState = blendState; previousDepthStencilState = depthStencilState; var sourceRegion = node.Sprite.Region; var texture = node.Sprite.Texture; // skip the sprite if no texture is set. if (texture == null) { continue; } var color4 = Color4.White; if (isPicking) { // TODO move this code corresponding to picking out of the runtime code. color4 = new Color4(spriteState.SpriteStudioComponent.Id); } else { if (node.BlendFactor > 0.0f) { switch (node.BlendType) //todo this should be done in a shader { case SpriteStudioBlending.Mix: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; case SpriteStudioBlending.Multiplication: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; case SpriteStudioBlending.Addition: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; case SpriteStudioBlending.Subtraction: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; default: throw new ArgumentOutOfRangeException(); } } else { color4 *= node.FinalTransparency; } } var worldMatrix = node.ModelTransform * transfoComp.WorldMatrix; // calculate normalized position of the center of the sprite (takes into account the possible rotation of the image) var normalizedCenter = new Vector2(node.Sprite.Center.X / sourceRegion.Width - 0.5f, 0.5f - node.Sprite.Center.Y / sourceRegion.Height); if (node.Sprite.Orientation == ImageOrientation.Rotated90) { var oldCenterX = normalizedCenter.X; normalizedCenter.X = -normalizedCenter.Y; normalizedCenter.Y = oldCenterX; } // apply the offset due to the center of the sprite var size = node.Sprite.Size; var centerOffset = Vector2.Modulate(normalizedCenter, size); worldMatrix.M41 -= centerOffset.X * worldMatrix.M11 + centerOffset.Y * worldMatrix.M21; worldMatrix.M42 -= centerOffset.X * worldMatrix.M12 + centerOffset.Y * worldMatrix.M22; // draw the sprite sprite3DBatch.Draw(texture, ref worldMatrix, ref sourceRegion, ref size, ref color4, node.Sprite.Orientation, SwizzleMode.None, renderItem.Depth); } } sprite3DBatch.End(); }
private void RenderFrame() { Input.XInputInput.Update(); if ((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.Back) == SharpDX.XInput.GamepadButtonFlags.Back) { renderForm.Close(); } if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.Start) == SharpDX.XInput.GamepadButtonFlags.Start) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.Start) != SharpDX.XInput.GamepadButtonFlags.Start)) { swapChain.GetFullscreenState(out SharpDX.Mathematics.Interop.RawBool fs, out Output o); o?.Dispose(); swapChain.SetFullscreenState(!fs, null); } fishManager.Update(); fishRenderer.Update(); foodManager.Update(); //theta = 0.0f; if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.X) == SharpDX.XInput.GamepadButtonFlags.X) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.X) != SharpDX.XInput.GamepadButtonFlags.X)) { camState = !camState; } if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadUp) == SharpDX.XInput.GamepadButtonFlags.DPadUp) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadUp) != SharpDX.XInput.GamepadButtonFlags.DPadUp)) { Wireframe = !Wireframe; } if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadLeft) == SharpDX.XInput.GamepadButtonFlags.DPadLeft) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadLeft) != SharpDX.XInput.GamepadButtonFlags.DPadLeft)) { frameSkip = frameSkip > 1 ? frameSkip - 1 : 1; } if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadRight) == SharpDX.XInput.GamepadButtonFlags.DPadRight) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadRight) != SharpDX.XInput.GamepadButtonFlags.DPadRight)) { frameSkip++; } if (!camState) { SetCamera(Matrix.LookAtLH(new Vector3((float)Math.Sin(Math.Sin(theta) * 0.1f), 0, (float)Math.Cos(Math.Sin(theta) * 0.1f)) * -1.3333f, Vector3.Zero, Vector3.Up), //Matrix.LookAtLH(Vector3.BackwardLH * 5, Vector3.Zero, Vector3.Up), //Matrix.OrthoLH(16.0f / 9.0f * 2.0f, 2.0f, 0, 10.0f)); Matrix.PerspectiveFovLH(MathUtil.DegreesToRadians(75.0f), RenderWidth / (float)RenderHeight, 0.1f, 20.0f)); } else { SetCamera(Matrix.LookAtLH(new Vector3(fishManager.FishList[0].Position * 0.75f, -1.33333f), new Vector3(fishManager.FishList[0].Position * 0.75f, 0.0f), Vector3.Up), Matrix.PerspectiveFovLH(MathUtil.DegreesToRadians(45.0f), RenderWidth / (float)RenderHeight, 0.1f, 20.0f)); } theta += (float)Math.PI / 30.0f / 60.0f * (Input.XInputInput.State[0].LeftThumbY / (float)short.MaxValue + 0.25f) * 4.0f; if (frameNumber % (ulong)frameSkip == 0 && (Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.LeftShoulder) != SharpDX.XInput.GamepadButtonFlags.LeftShoulder) { DeviceContext.Rasterizer.State = Wireframe ? RasterizerStates.Wire : RasterizerStates.Back; //DeviceContext.OutputMerger.SetRenderTargets(renderTargetView); DeviceContext.PixelShader.SetShaderResource(0, null); DeviceContext.OutputMerger.SetRenderTargets(colorTarget.DSV, colorTarget.RTV); DeviceContext.OutputMerger.DepthStencilState = DepthStencilStates.Enabled; DeviceContext.ClearRenderTargetView(renderTargetView, new Color(0.0f, 0.0f, 0.0f)); colorTarget.Clear(Color4.Lerp(new Color4(0, 0, 0.04f, 0.0f), new Color4(0.08f, 0.08f, 0.2f, 0.0f), Math.Max(0, -(float)Math.Cos(theta)))); //RenderDebugTri(); var intensity = Math.Max(0, -(float)Math.Cos(theta)); var sunDir = new Vector3((float)Math.Sin(theta), (float)Math.Cos(theta), 1.0f); Sun.Set(sunDir, new Vector3(1.0f, 1.0f, 1.0f), intensity); fishGlow.Intensity = Math.Max(0, ((float)Math.Cos(intensity * MathUtil.Pi) + 0.2f) / 1.2f); raysRenderer.Intensity = 0.02f * (1 - fishGlow.Intensity); fishGlow.Intensity *= 0.75f; decorRenderer.Render(); fishRenderer.Render(); DeviceContext.OutputMerger.SetRenderTargets(colorTarget.DSV, renderTargetView); //var pos = new Vector3(fishManager.FishList[0].Position, 0); //var np = Vector3.Transform(pos, Projection * View); var np = Vector3.Transform(sunDir * new Vector3(1, 1, 0) * -10, Projection * View); DeviceContext.OutputMerger.DepthStencilState = DepthStencilStates.Disabled; DeviceContext.Rasterizer.State = RasterizerStates.Back; raysRenderer.CentrePoint = new Vector2(-sunDir.X * RenderWidth * 10.0f, sunDir.Y * RenderHeight * 10.0f);//new Vector2((np.X / np.W / 2.0f + 0.5f) * RenderWidth, (-np.Y / np.W / 2.0f + 0.5f) * RenderHeight); raysRenderer.Render(colorTarget.SRV, 1.0f / 60.0f); fishGlow.Render(); DeviceContext.Rasterizer.State = Wireframe ? RasterizerStates.Wire : RasterizerStates.Back; DeviceContext.OutputMerger.DepthStencilState = DepthStencilStates.Enabled; foodRenderer.Render(); decorRenderer.Render2(); try { if ((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.RightShoulder) != SharpDX.XInput.GamepadButtonFlags.RightShoulder) { swapChain.Present(1, PresentFlags.None); } else { swapChain.Present(0, PresentFlags.None); } } catch (Exception e) { Console.WriteLine(Device.DeviceRemovedReason.ToString()); Console.ReadLine(); renderForm.Close(); } } frameNumber++; }
public static object Linear(Color4KeyFrame start, Color4KeyFrame end, float time) { float newValue = Map(start.Time, end.Time, time); return(Color4.Lerp(start.Value, end.Value, newValue)); }
public void Saturate(float saturation) { PerpixelProcessing(v => Color4.Lerp(Desaturate(v), v, saturation)); }
/// <inheritdoc /> public unsafe override void Initialize(ParticlePool pool, int startIdx, int endIdx, int maxCapacity) { if (!pool.FieldExists(ParticleFields.Color) || !pool.FieldExists(ParticleFields.RandomSeed)) { return; } // Collect the total number of living particles in the parent pool which have a Color field var parentPool = Parent?.Pool; var parentParticlesCount = parentPool?.LivingParticles ?? 0; var colorFieldParent = parentPool?.GetField(ParticleFields.Color) ?? ParticleFieldAccessor <Color4> .Invalid(); if (!colorFieldParent.IsValid()) { parentParticlesCount = 0; } var spawnControlField = GetSpawnControlField(); var colorField = pool.GetField(ParticleFields.Color); var rndField = pool.GetField(ParticleFields.RandomSeed); var sequentialParentIndex = 0; var sequentialParentParticles = 0; var parentIndex = 0; var i = startIdx; while (i != endIdx) { var particle = pool.FromIndex(i); var randSeed = particle.Get(rndField); var color = Color4.Lerp(ColorMin, ColorMax, randSeed.GetFloat(RandomOffset.Offset1A + SeedOffset)); // If there are living parent particles, the newly created particle will inherit Color from one of them if (parentParticlesCount > 0) { var parentParticleColor = new Color4(1, 1, 1, 1); // Spawn is fixed - parent particles have spawned a very specific number of children each if (spawnControlField.IsValid()) { while (sequentialParentParticles == 0) { // Early out - no more fixed number children. Rest of the particles (if any) are skipped intentionally if (sequentialParentIndex >= parentParticlesCount) { return; } parentIndex = sequentialParentIndex; var tempParentParticle = parentPool.FromIndex(parentIndex); sequentialParentIndex++; var childrenAttribute = (*((ParticleChildrenAttribute *)tempParentParticle[spawnControlField])); sequentialParentParticles = (int)childrenAttribute.ParticlesToEmit; } sequentialParentParticles--; var parentParticle = parentPool.FromIndex(parentIndex); parentParticleColor = (*((Color4 *)parentParticle[colorFieldParent])); } // Spawn is not fixed - pick a parent at random else { parentIndex = (int)(parentParticlesCount * randSeed.GetFloat(RandomOffset.Offset1A + ParentSeedOffset)); var parentParticle = parentPool.FromIndex(parentIndex); parentParticleColor = (*((Color4 *)parentParticle[colorFieldParent])); } color *= parentParticleColor; } // Premultiply alpha // This can't be done in advance for ColorMin and ColorMax because it will change the math color.R *= color.A; color.G *= color.A; color.B *= color.A; (*((Color4 *)particle[colorField])) = color; i = (i + 1) % maxCapacity; } }
public static void Update() { isUpdating = true; foreach (Entity entity in Entities) { entity.PreUpdate(); } IEnumerable <CollisionData> Collisions = GetProbableCollisions(); foreach (CollisionData data in Collisions) { bool collision = data.Check(); if (collision) { Random rand = new Random(); data.CalculateN(); data.CalculateJ(); ((PhysicsEntity)data.Object1).Collision(data); data.Swap(); ((PhysicsEntity)data.Object1).Collision(data); float hue1 = 2; float hue2 = (hue1 + rand.NextFloat(0, 2)) % 6f; Color4 color1 = ColorUtil.HSVToColor(hue1, 0.5f, 1); Color4 color2 = ColorUtil.HSVToColor(hue2, 0.5f, 1); for (int i = 0; i < 150; i++) { float speed = 12.0f * (1.0f - 1 / rand.NextFloat(1, 3)); Color4 color = Color4.Lerp(color1, color2, rand.NextFloat(0, 1)); Vector2 dir = rand.NextVector2(1, 1); ParticleManager.CreateParticle((data.Point1 + data.Point2) / 2, color, 190, Vector2.One, dir * speed, 0.2f); } } } foreach (Entity entity in Entities) { entity.Update(); } foreach (Entity entity in Entities) { entity.PostUpdate(); } isUpdating = false; for (int i = Entities.Count - 1; i >= 0; i--) { Entity ent = Entities[i]; if (ent.isExpired) { Disposer.RemoveAndDispose(ref ent); Entities.RemoveAt(i); } } Entities.AddRange(addedEntities); addedEntities.Clear(); }
public void LerpTest() { Assert.That(Color4.Lerp(0, Color4.Orange, Color4.Black), Is.EqualTo(Color4.Orange)); Assert.That(Color4.Lerp(0.5f, Color4.Gray, Color4.Black), Is.EqualTo(Color4.DarkGray)); Assert.That(Color4.Lerp(1, Color4.Black, Color4.Black), Is.EqualTo(Color4.Black)); }