public double GetValueFromTrackBar(bool isInteger, int trackBarValue) { double value; if (ConvenientDistribution == ConvenientDistributionEnum.Exponential) { double v = (double)trackBarValue / 1000; v = Math.Pow(v, ExponentialPower); value = Minimum + v * (Maximum - Minimum); } else { if (isInteger) { value = trackBarValue; } else { value = (double)trackBarValue / 1000; } } value = MathEx.Clamp(value, Minimum, Maximum); return(value); }
//Vector2 GetScreenTextureBaseSize() //{ // double baseHeight = UIControlsWorld.ScaleByResolutionBaseHeight; // return new Vector2( baseHeight * ParentContainer.AspectRatio, baseHeight ); //} void UpdateValueByMouse() { //!!!!может в стиль var rectangle = GetScreenRectangle() * new Vector2(ParentContainer.AspectRatio, 1); //var baseSize = GetScreenTextureBaseSize(); //rectangle.LeftTop *= baseSize; //rectangle.RightBottom *= baseSize; double valueCoef; if (!Vertical) { valueCoef = MousePosition.X; valueCoef -= .5f; valueCoef *= rectangle.Size.X / (rectangle.Size.X - rectangle.Size.Y); valueCoef += .5f; } else { valueCoef = MousePosition.Y; valueCoef -= .5f; valueCoef *= rectangle.Size.Y / (rectangle.Size.Y - rectangle.Size.X); valueCoef += .5f; } var valueRange = ValueRange.Value; var value = valueRange[0] + valueCoef * (valueRange[1] - valueRange[0]); MathEx.Clamp(ref value, valueRange.Minimum, valueRange.Maximum); Value = value; }
public void SetMaskValue(Vector2I position, float value) { //!!!!slowly. когда не проверять var mask = Mask.Value; if (mask != null) { int size = GetSqrt(Mask.Value.Length); if (size > 0 && position.X >= 0 && position.X < size && position.Y >= 0 && position.Y < size) { float v = value * 255.0f + .5f; var i = (int)v; mask[(size - 1 - position.Y) * size + position.X] = (byte)MathEx.Clamp(i, 0, 255); //!!!!не всю обновлять createdMaskImageNeedUpdate = true; unchecked { uniqueMaskDataCounter++; } } } }
public Color ToColor() { return(Color.FromArgb( (int)MathEx.Clamp(Alpha * 255, 0, 255), (int)MathEx.Clamp(Red * 255, 0, 255), (int)MathEx.Clamp(Green * 255, 0, 255), (int)MathEx.Clamp(Blue * 255, 0, 255))); }
/// <summary> /// Performs linear interpolation of <see cref="ColorByte"/>. /// </summary> /// <param name="value1">Source <see cref="ColorByte"/>.</param> /// <param name="value2">Destination <see cref="ColorByte"/>.</param> /// <param name="amount">Interpolation factor.</param> /// <returns>Interpolated <see cref="ColorByte"/>.</returns> public static ColorByte Lerp(ColorByte value1, ColorByte value2, double amount) { amount = MathEx.Clamp(amount, 0, 1); return(new ColorByte( (int)MathEx.Lerp(value1.Red, value2.Red, amount), (int)MathEx.Lerp(value1.Green, value2.Green, amount), (int)MathEx.Lerp(value1.Blue, value2.Blue, amount), (int)MathEx.Lerp(value1.Alpha, value2.Alpha, amount))); }
static uint ToRGBA(ColorValue color) { var alpha = (uint)MathEx.Clamp(color.Alpha * 255, 0, 255); var red = (uint)MathEx.Clamp(color.Red * 255, 0, 255); var green = (uint)MathEx.Clamp(color.Green * 255, 0, 255); var blue = (uint)MathEx.Clamp(color.Blue * 255, 0, 255); return(red << 24 | green << 16 | blue << 8 | alpha); }
public static float GetCameraDistanceMinSquared(Viewport.CameraSettingsClass cameraSettings, ref Bounds objectBounds) { var nearestInBounds = cameraSettings.Position; MathEx.Clamp(ref nearestInBounds.X, objectBounds.Minimum.X, objectBounds.Maximum.X); MathEx.Clamp(ref nearestInBounds.Y, objectBounds.Minimum.Y, objectBounds.Maximum.Y); MathEx.Clamp(ref nearestInBounds.Z, objectBounds.Minimum.Z, objectBounds.Maximum.Z); return((float)(cameraSettings.Position - nearestInBounds).LengthSquared()); }
int GetCellIndex(double x) { if (sizeX == 0) { return(0); } var a = (x - bounds.Minimum.X) / sizeX; var index = (int)(a * cells.Length); return(MathEx.Clamp(index, 0, cells.Length - 1)); }
public void Write(QuaternionF source, int bitsPerElement) { float x = source.X; float y = source.Y; float z = source.Z; float w = source.W; MathEx.Clamp(ref x, -1, 1); MathEx.Clamp(ref y, -1, 1); MathEx.Clamp(ref z, -1, 1); MathEx.Clamp(ref w, -1, 1); WriteRangedSingle(x, -1, 1, bitsPerElement); WriteRangedSingle(y, -1, 1, bitsPerElement); WriteRangedSingle(z, -1, 1, bitsPerElement); WriteRangedSingle(w, -1, 1, bitsPerElement); }
///// <summary> ///// Constructs an RGBA color from scalars representing red, green and blue values. Alpha value will be opaque. ///// </summary> ///// <param name="r">Red component value from 0 to 255.</param> ///// <param name="g">Green component value from 0 to 255.</param> ///// <param name="b">Blue component value from 0 to 255.</param> //public ColorPacked( int r, int g, int b ) //{ // _packedValue = 0xFF000000; // A = 255 // if( ( ( r | g | b ) & 0xFFFFFF00 ) != 0 ) // { // var clampedR = (uint)MathHelper.Clamp( r, Byte.MinValue, Byte.MaxValue ); // var clampedG = (uint)MathHelper.Clamp( g, Byte.MinValue, Byte.MaxValue ); // var clampedB = (uint)MathHelper.Clamp( b, Byte.MinValue, Byte.MaxValue ); // _packedValue |= ( clampedB << 16 ) | ( clampedG << 8 ) | ( clampedR ); // } // else // { // _packedValue |= ( (uint)b << 16 ) | ( (uint)g << 8 ) | ( (uint)r ); // } //} /// <summary> /// Constructs an RGBA color from scalars representing red, green, blue and alpha values. /// </summary> /// <param name="red">Red component value from 0 to 255.</param> /// <param name="green">Green component value from 0 to 255.</param> /// <param name="blue">Blue component value from 0 to 255.</param> /// <param name="alpha">Alpha component value from 0 to 255.</param> public ColorByte(int red, int green, int blue, int alpha = 255) { if (((red | green | blue | alpha) & 0xFFFFFF00) != 0) { var clampedR = (uint)MathEx.Clamp(red, Byte.MinValue, Byte.MaxValue); var clampedG = (uint)MathEx.Clamp(green, Byte.MinValue, Byte.MaxValue); var clampedB = (uint)MathEx.Clamp(blue, Byte.MinValue, Byte.MaxValue); var clampedA = (uint)MathEx.Clamp(alpha, Byte.MinValue, Byte.MaxValue); _packedValue = (clampedA << 24) | (clampedB << 16) | (clampedG << 8) | (clampedR); } else { _packedValue = ((uint)alpha << 24) | ((uint)blue << 16) | ((uint)green << 8) | ((uint)red); } }
private void UpdateAnimationTime() { if (this.PlayAnimation.Value == null) { return; } if (this.PlayAnimationName != this.PlayAnimation.Value.Name) { ResetTime(); } double engineTime = EngineApp.EngineTime; double num = engineTime - this.currentEngineTime; this.currentEngineTime = engineTime; this.currentAnimationTime += num * (double)this.Speed; if (this.PlayAnimation.Value is Component_SkeletonAnimation skeletonAnimation) { double trackStartTime = (double)skeletonAnimation.TrackStartTime; double length = (double)skeletonAnimation.Length; if (length > 0.0) { if ((bool)this.AutoRewind) { while (this.currentAnimationTime > trackStartTime + length) { this.currentAnimationTime -= length; } while (this.currentAnimationTime < trackStartTime) { this.currentAnimationTime += length; } } else { MathEx.Clamp(ref this.currentAnimationTime, trackStartTime, trackStartTime + length); } } else { this.currentAnimationTime = trackStartTime; } } else { this.currentAnimationTime = 0.0; } }
void Simulate(float delta) { if (Changing) { var oldValue = Value.Value; //calculate new value var newValue = oldValue; var step = ChangeSpeed * delta; if (ChangingForward) { newValue += step; } else { newValue -= step; } newValue = MathEx.Clamp(newValue, ValueRange.Value.Minimum, ValueRange.Value.Maximum); //update value Value = newValue; //play tick sound { bool play = false; if (SoundTickFrequency > 0) { for (var tickTime = ValueRange.Value.Minimum; tickTime <= ValueRange.Value.Maximum; tickTime += SoundTickFrequency) { var before = oldValue < tickTime; var after = newValue < tickTime; if (before != after) { play = true; break; } } } if (play) { SoundPlay(SoundTick); } } } }
public unsafe void SetPixel(Vector2I position, Vector4F value) { if (position.X < 0 || position.X >= size.X || position.Y < 0 || position.Y >= size.Y) { return; fixed(byte *pData = data) { switch (format) { case PixelFormat.Float32RGBA: { var p = (Vector4F *)pData + position.Y * size.X + position.X; p->X = value.X; p->Y = value.Y; p->Z = value.Z; p->W = value.W; } break; case PixelFormat.Float32RGB: { var p = (Vector3F *)pData + position.Y * size.X + position.X; p->X = value.X; p->Y = value.Y; p->Z = value.Z; } break; case PixelFormat.A8R8G8B8: { var p = pData + (position.Y * size.X + position.X) * 4; p[3] = (byte)MathEx.Clamp((int)(value.W * 255.0), 0, 255); p[2] = (byte)MathEx.Clamp((int)(value.X * 255.0), 0, 255); p[1] = (byte)MathEx.Clamp((int)(value.Y * 255.0), 0, 255); p[0] = (byte)MathEx.Clamp((int)(value.Z * 255.0), 0, 255); } break; default: throw new Exception($"ImageUtility: SetPixel: Format \"{format}\" is not supported."); //Log.Fatal( "ImageUtility: SetPixel: Format is not supported." ); //break; } } }
void UpdateAnimationTime() { double t = EngineApp.EngineTime; if (currentEngineTime != t) { double increment = t - currentEngineTime; currentEngineTime = t; currentAnimationTime += increment * Speed; var animation = PlayAnimation.Value as Component_Animation; if (animation != null) { double animationStartTime = 0; double animationLength = animation.Length; if (animationLength > 0) { if (AutoRewind) { while (currentAnimationTime > animationStartTime + animationLength) { currentAnimationTime -= animationLength; } while (currentAnimationTime < animationStartTime) { currentAnimationTime += animationLength; } } else { MathEx.Clamp(ref currentAnimationTime, animationStartTime, animationStartTime + animationLength); } } else { currentAnimationTime = 0; } } else { currentAnimationTime = 0; } } }
public float GetMaskValue(Vector2I position) //public byte GetMaskValue( Vector2I position ) { //!!!!slowly. когда не проверять var mask = Mask.Value; if (mask != null) { int size = GetSqrt(Mask.Value.Length); if (size > 0) { var position2 = new Vector2I(MathEx.Clamp(position.X, 0, size - 1), MathEx.Clamp(position.Y, 0, size - 1)); float v = mask[(size - 1 - position2.Y) * size + position2.X]; return(v * (1.0f / 255.0f)); } } return(0); }
public int GetTrackBarValue(bool isInteger, double value) { if (ConvenientDistribution == ConvenientDistributionEnum.Exponential) { double v = MathEx.Saturate((value - Minimum) / (Maximum - Minimum)); v = Math.Pow(v, 1.0 / ExponentialPower); return(MathEx.Clamp((int)(v * 1000), 0, 1000)); } else { GetTrackBarMinMax(isInteger, out int min, out int max); if (isInteger) { return(MathEx.Clamp((int)(value), min, max)); } else { return(MathEx.Clamp((int)(value * 1000), min, max)); } } }
//Vector2 GetScreenTextureBaseSize() //{ // double baseHeight = UIControlsWorld.ScaleByResolutionBaseHeight; // return new Vector2( baseHeight * ParentContainer.AspectRatio, baseHeight ); //} void UpdateValueByCursor(Vector2?cursorScreenPosition = null) { var style = GetStyle(); var valuesRay = style.GetSliderValuesRayInScreenCoords(this); Vector2 mouse = cursorScreenPosition != null ? cursorScreenPosition.Value : ConvertLocalToScreen(MousePosition); double valueCoef = 0; if (Vertical) { if (valuesRay.Direction.Y != 0) { valueCoef = (mouse.Y - valuesRay.Origin.Y) / valuesRay.Direction.Y; } } else { if (valuesRay.Direction.X != 0) { valueCoef = (mouse.X - valuesRay.Origin.X) / valuesRay.Direction.X; } } var valueRange = ValueRange.Value; var value = valueRange[0] + valueCoef * (valueRange[1] - valueRange[0]); var step = Step.Value; if (step != 0) { value += step / 2; value /= step; value = (int)value; value *= step; } MathEx.Clamp(ref value, valueRange.Minimum, valueRange.Maximum); Value = value; }
///////////////////////////////////////////// //public class ItemMouseEventArgs : EventArgs //{ // int itemIndex; // object item; // public ItemMouseEventArgs( int itemIndex, object item ) // { // this.itemIndex = itemIndex; // this.item = item; // } // public int ItemIndex // { // get { return itemIndex; } // } // public object Item // { // get { return item; } // } //} //public delegate void ItemMouseEventHandler( object sender, ItemMouseEventArgs e ); //public event ItemMouseEventHandler ItemMouseDoubleClick; ///// <summary> ///// The index of selected item from the item list. ///// </summary> //[DefaultValue( -1 )] //[Category( "List Box" )] //public int SelectedIndex //{ // get { return selectedIndex; } // set // { // if( value < -1 || value >= items.Count ) // throw new Exception( "EComboBox: SelectedIndex: Set invalid value" ); // if( selectedIndex != value ) // { // if( selectedIndex != -1 && itemButtons.Count > selectedIndex ) // itemButtons[ selectedIndex ].Highlighted = false; // selectedIndex = value; // OnSelectedIndexChange(); // if( selectedIndex != -1 && itemButtons.Count > selectedIndex ) // { // bool active = true; // if( hideSelectionWhenDisabled && !EnabledInHierarchy ) // active = false; // if( active ) // itemButtons[ selectedIndex ].Highlighted = true; // } // } // //change scroll bar position // if( scrollBar != null && itemButton != null && selectedIndex != -1 ) // { // double itemScreenSizeY = GetItemScreenSizeY(); // double screenSizeY = GetScreenSize().Y - GetOffsetByTypeFromLocal( ScaleType.Screen, // GetLocalOffsetByValue( clipRectangleBorders ) ).Y * 2; // double itemsScreenSizeY = itemScreenSizeY * (double)items.Count; // double scrollScreenSizeY = itemsScreenSizeY - screenSizeY; // if( scrollScreenSizeY > 0 ) // { // double currentScrollScreenPosY = scrollBar.Value * scrollScreenSizeY; // double itemScrollScreenPosY = itemScreenSizeY * (double)selectedIndex; // Range itemScrollScreenRangeY = new Range( itemScrollScreenPosY, // itemScrollScreenPosY + itemScreenSizeY ); // if( itemScrollScreenRangeY.Minimum < currentScrollScreenPosY ) // { // currentScrollScreenPosY = itemScrollScreenRangeY.Minimum; // } // else // { // if( itemScrollScreenRangeY.Maximum > currentScrollScreenPosY + screenSizeY ) // { // currentScrollScreenPosY = itemScrollScreenRangeY.Maximum // + itemScreenSizeY - screenSizeY; // } // } // scrollBar.Value = currentScrollScreenPosY / scrollScreenSizeY; // } // } // } //} //void ItemButton_MouseDoubleClick( object sender, EMouseButtons button ) //{ // if( !EnabledInHierarchy ) // return; // UIButton b = (UIButton)sender; // if( b.UserData == null ) // return; // int index = (int)b.UserData; // if( index >= items.Count ) // return; // OnItemMouseDoubleClick( index ); //} //protected void OnItemMouseDoubleClick( int itemIndex ) //{ // if( ItemMouseDoubleClick != null ) // ItemMouseDoubleClick( this, new ItemMouseEventArgs( itemIndex, items[ itemIndex ] ) ); //} protected override bool OnMouseWheel(int delta) { var cursorInsideArea = CursorIsInArea(); if (VisibleInHierarchy && cursorInsideArea /*new Rectangle( 0, 0, 1, 1 ).Contains( MousePosition )*/ && EnabledInHierarchy) { var scrollBar = GetScrollBar(); if (scrollBar != null && scrollBar.EnabledInHierarchy && scrollBar.VisibleInHierarchy) { var v = scrollBar.Value.Value; //!!!! v -= (double)delta / 700.0f / 10; //v -= (double)delta / 700.0f; MathEx.Clamp(ref v, scrollBar.ValueRange.Value.Minimum, scrollBar.ValueRange.Value.Maximum); scrollBar.Value = v; return(true); } } return(base.OnMouseWheel(delta)); }
public HSVColor(double hue, double saturation, double value) { MathEx.Clamp(ref hue, 0, 360); MathEx.Clamp(ref saturation, 0, 1); MathEx.Clamp(ref value, 0, 1); //if( hue < 0 || hue > 360 ) // throw new ArgumentOutOfRangeException( "hue", "must be in the range [0, 360]" ); //if( saturation < 0 || saturation > 100 ) // throw new ArgumentOutOfRangeException( "saturation", "must be in the range [0, 100]" ); //if( value < 0 || value > 100 ) // throw new ArgumentOutOfRangeException( "value", "must be in the range [0, 100]" ); //if( hue < 0 || hue > 360 ) // throw new ArgumentOutOfRangeException( "hue", "must be in the range [0, 360]" ); //if( saturation < 0 || saturation > 100 ) // throw new ArgumentOutOfRangeException( "saturation", "must be in the range [0, 100]" ); //if( value < 0 || value > 100 ) // throw new ArgumentOutOfRangeException( "value", "must be in the range [0, 100]" ); this.hue = hue; this.saturation = saturation; this.value = value; }
protected virtual void OnRenderList(UIList control, CanvasRenderer renderer) { var rect = control.GetScreenRectangle(); renderer.AddQuad(rect, new ColorValue(0, 0, 0)); //renderer.AddQuad( rect, new ColorValue( 0.2, 0.2, 0.2 ) ); var rect2 = rect; rect2.Expand(-control.GetScreenOffsetByValue(new UIMeasureValueVector2(UIMeasure.Units, 2, 2))); //border var color = new ColorValue(0.75, 0.75, 0.75); renderer.AddQuad(new Rectangle(rect.Left, rect.Top, rect2.Left, rect.Bottom), color); renderer.AddQuad(new Rectangle(rect2.Left, rect.Top, rect2.Right, rect2.Top), color); renderer.AddQuad(new Rectangle(rect2.Right, rect.Top, rect.Right, rect.Bottom), color); renderer.AddQuad(new Rectangle(rect.Left, rect2.Bottom, rect2.Right, rect.Bottom), color); var font = control.Font.Value; if (font == null) { font = renderer.DefaultFont; } var fontSize = control.GetFontSizeScreen(); var itemSize = GetListItemSizeScreen(control, renderer); var totalItemsHeight = itemSize * control.Items.Count; var scrollBar = control.GetScrollBar(); //!!!!тут? //update scroll bar properties if (scrollBar != null) { double screenSizeY = rect2.Size.Y; double scrollScreenSizeY = totalItemsHeight - screenSizeY; scrollBar.Visible = control.AlwaysShowScrollBar || totalItemsHeight > screenSizeY; if (scrollBar.Visible) { scrollBar.ValueRange = new Range(0, scrollScreenSizeY); } //ensure visible if (listEnsureVisible != -1) { if ((float)listEnsureVisible * itemSize > screenSizeY / 2) { var factor = (float)listEnsureVisible / (float)(control.Items.Count - 1); var v = scrollScreenSizeY * factor; scrollBar.Value = MathEx.Clamp(v, 0, scrollBar.ValueRange.Value.Maximum); } else { scrollBar.Value = 0; } listEnsureVisible = -1; } //if( scrollBar.Visible ) //{ // if( scrollScreenSizeY > 0 ) // { // double currentScrollScreenPosY = scrollBar.Value * scrollScreenSizeY; // double itemScrollScreenPosY = itemSize * (double)control.SelectedIndex; // Range itemScrollScreenRangeY = new Range( itemScrollScreenPosY, itemScrollScreenPosY + itemSize ); // if( itemScrollScreenRangeY.Minimum < currentScrollScreenPosY ) // { // currentScrollScreenPosY = itemScrollScreenRangeY.Minimum; // } // else // { // if( itemScrollScreenRangeY.Maximum > currentScrollScreenPosY + screenSizeY ) // currentScrollScreenPosY = itemScrollScreenRangeY.Maximum + itemSize - screenSizeY; // } // scrollBar.Value = currentScrollScreenPosY / scrollScreenSizeY; // } // else // scrollBar.Value = 0; //} //else // scrollBar.Value = 0; } //items if (control.Items.Count != 0) { renderer.PushClipRectangle(rect2); var positionY = rect2.Top; if (scrollBar != null && scrollBar.VisibleInHierarchy && scrollBar.EnabledInHierarchy) { positionY -= scrollBar.Value; } for (int n = 0; n < control.Items.Count; n++) { var item = control.Items[n]; var itemRectangle = new Rectangle(rect2.Left, positionY, rect2.Right, positionY + itemSize); if (scrollBar != null && scrollBar.EnabledInHierarchy && scrollBar.VisibleInHierarchy) { itemRectangle.Right -= scrollBar.GetScreenSize().X; } if (itemRectangle.Intersects(rect2)) { renderer.PushClipRectangle(itemRectangle); if (n == control.SelectedIndex) { var color2 = control.ReadOnlyInHierarchy ? new ColorValue(0.5, 0.5, 0.5) : new ColorValue(0, 0, 0.8); renderer.AddQuad(itemRectangle, color2); } var positionX = rect2.Left + control.GetScreenOffsetByValue(new UIMeasureValueVector2(UIMeasure.Units, 2, 0)).X; renderer.AddText(font, fontSize, item, new Vector2(positionX, itemRectangle.GetCenter().Y), EHorizontalAlignment.Left, EVerticalAlignment.Center, new ColorValue(1, 1, 1)); renderer.PopClipRectangle(); } positionY += itemSize; } renderer.PopClipRectangle(); } }
public static bool Convert2DToDDS(string virtualFileName, string outputRealFileName, DDSImage.FormatEnum outputFormat, bool normalMap, bool generateMipmaps, out Vector2I sourceFileSize, out PixelFormat sourceFileFormat, out string error) { sourceFileSize = Vector2I.Zero; sourceFileFormat = PixelFormat.Unknown; if (!ImageUtility.LoadFromVirtualFile(virtualFileName, out var data, out var size, out var depth, out var format, out var numFaces, out var numMipmaps, out error)) { return(false); } sourceFileSize = size; sourceFileFormat = format; byte[] rgba = new byte[size.X * size.Y * 4]; if (format != PixelFormat.R8G8B8A8) { for (int y = 0; y < size.Y; y++) { for (int x = 0; x < size.X; x++) { byte r; byte g; byte b; byte a = 255; int offset; switch (format) { case PixelFormat.R8G8B8: offset = (y * size.X + x) * 3; r = data[offset + 2]; g = data[offset + 1]; b = data[offset + 0]; break; case PixelFormat.X8R8G8B8: offset = (y * size.X + x) * 4; r = data[offset + 2]; g = data[offset + 1]; b = data[offset + 0]; break; case PixelFormat.A8R8G8B8: offset = (y * size.X + x) * 4; a = data[offset + 3]; r = data[offset + 2]; g = data[offset + 1]; b = data[offset + 0]; break; case PixelFormat.L8: offset = (y * size.X + x); r = g = b = data[offset]; break; case PixelFormat.ShortRGB: unsafe { fixed(byte *pData = data) { ushort *pData2 = (ushort *)pData; offset = (y * size.X + x) * 3; r = (byte)((float)pData2[offset + 0] / ushort.MaxValue * 255.0f); g = (byte)((float)pData2[offset + 1] / ushort.MaxValue * 255.0f); b = (byte)((float)pData2[offset + 2] / ushort.MaxValue * 255.0f); } } break; case PixelFormat.ShortRGBA: unsafe { fixed(byte *pData = data) { ushort *pData2 = (ushort *)pData; offset = (y * size.X + x) * 4; r = (byte)((float)pData2[offset + 0] / ushort.MaxValue * 255.0f); g = (byte)((float)pData2[offset + 1] / ushort.MaxValue * 255.0f); b = (byte)((float)pData2[offset + 2] / ushort.MaxValue * 255.0f); a = (byte)((float)pData2[offset + 3] / ushort.MaxValue * 255.0f); } } break; case PixelFormat.Float32RGB: unsafe { fixed(byte *pData = data) { float *pData2 = (float *)pData; offset = (y * size.X + x) * 3; r = (byte)MathEx.Clamp((float)pData2[offset + 0] * 255.0f, 0.0f, 255.0f); g = (byte)MathEx.Clamp((float)pData2[offset + 1] * 255.0f, 0.0f, 255.0f); b = (byte)MathEx.Clamp((float)pData2[offset + 2] * 255.0f, 0.0f, 255.0f); } } break; case PixelFormat.Float32RGBA: unsafe { fixed(byte *pData = data) { float *pData2 = (float *)pData; offset = (y * size.X + x) * 4; r = (byte)MathEx.Clamp((float)pData2[offset + 0] * 255.0f, 0.0f, 255.0f); g = (byte)MathEx.Clamp((float)pData2[offset + 1] * 255.0f, 0.0f, 255.0f); b = (byte)MathEx.Clamp((float)pData2[offset + 2] * 255.0f, 0.0f, 255.0f); a = (byte)MathEx.Clamp((float)pData2[offset + 3] * 255.0f, 0.0f, 255.0f); } } break; default: error = $"Conversion from \'{format}\' format is not supported."; return(false); } //copy to rgba array offset = (y * size.X + x) * 4; rgba[offset + 0] = r; rgba[offset + 1] = g; rgba[offset + 2] = b; rgba[offset + 3] = a; } } } var image = GenerateDDS(rgba, size, outputFormat, normalMap, generateMipmaps, out error); if (image == null) { return(false); } if (!WriteToFile(outputRealFileName, image, out error)) { return(false); } error = ""; return(true); //MapFormats mapFormat = textureData.normalMap ? NormalMapFormat : BaseMapFormat; //DDSImage.FormatTypes ddsFormat = DDSImage.FormatTypes.DXT1; //switch( mapFormat ) //{ //case MapFormats.DDS_DXT1: // ddsFormat = DDSImage.FormatTypes.DXT1; // break; //case MapFormats.DDS_DXT5: // ddsFormat = DDSImage.FormatTypes.DXT5; // break; //case MapFormats.DDS_3DC: // ddsFormat = DDSImage.FormatTypes._3DC; // break; //case MapFormats.DDS_ARGB: // ddsFormat = DDSImage.FormatTypes.A8R8G8B8; // break; //} //DDSImage ddsImage = DDSImageManager.Instance.Generate( rgba, size, ddsFormat, true ); //bool oldExists = File.Exists( outputRealFullPath ); //using( FileStream stream = new FileStream( outputRealFullPath, FileMode.Create ) ) //{ // DDSImageManager.WriteFile( stream, ddsImage ); //} //createdFiles.Add( new CreatedFileItem( outputRealFullPath, oldExists ) ); //error = null; //return true; }
private void ParentMeshInSpace_GetRenderSceneDataAddToFrameData(Component_MeshInSpace sender, ViewportRenderingContext context, GetRenderSceneDataMode mode, ref Component_RenderingPipeline.RenderSceneData.MeshItem item) { if (!CalculateOnCPU) { Component_Skeleton skeleton = ReplaceSkeleton; if (skeleton == null) { skeleton = ParentMeshInSpace?.Mesh.Value?.Skeleton; } if (skeleton != null) { var animation = PlayAnimation.Value; if (animation != null) { UpdateAnimationTime(); //settings.animationStates = new AnimationStateItem[ 1 ]; //settings.animationStates[ 0 ] = new AnimationStateItem( animation, currentLocalTime, 1 ); var skeletonAnimation = animation as Component_SkeletonAnimation; var track = skeletonAnimation?.Track.Value; if (track != null || CalculateBoneTransforms != null) { Update(skeleton, track, currentAnimationTime); if (transformMatrixRelativeToSkin != null && transformMatrixRelativeToSkin.Length != 0) { item.AnimationData = new Component_RenderingPipeline.RenderSceneData.MeshItem.AnimationDataClass(); bool dualQuaternion = false; // GetSkinningMode( skeleton ) == Component_Skeleton.SkinningModeEnum.DualQuaternion; if (dualQuaternion) { item.AnimationData.Mode = 2; } else { item.AnimationData.Mode = 1; } //create dynamic texture var size = new Vector2I(4, MathEx.NextPowerOfTwo(transformMatrixRelativeToSkin.Length)); var bonesTexture = context.DynamicTexture_Alloc(ViewportRenderingContext.DynamicTextureType.DynamicTexture, Component_Image.TypeEnum._2D, size, PixelFormat.Float32RGBA, 0, false); //try get array from texture to minimize memory allocations var surfaces = bonesTexture.Result.GetData(); if (surfaces == null) { surfaces = new GpuTexture.SurfaceData[] { new GpuTexture.SurfaceData(0, 0, new byte[size.X * size.Y * 16]) } } ; var data = surfaces[0].data; //copy data to the texture unsafe { fixed(byte *pData2 = data) { Matrix4F *pData = (Matrix4F *)pData2; for (int n = 0; n < transformMatrixRelativeToSkin.Length; n++) { pData[n] = transformMatrixRelativeToSkin[n]; } } } bonesTexture.Result.SetData(new GpuTexture.SurfaceData[] { new GpuTexture.SurfaceData(0, 0, data) }); item.AnimationData.BonesTexture = bonesTexture; } } } } } } void RenderSkeleton(Viewport viewport) { // ParentMeshInSpace.Transform is automaticaly applyed to ParentMeshInSpace.Mesh, skeleton must be transformed manually var transformMatrix = ParentMeshInSpace?.Transform.Value?.ToMatrix4() ?? Matrix4.Identity; var skeletonArrows = GetCurrentAnimatedSkeletonArrows(); if (skeletonArrows != null) { var color = new ColorValue(0, 0.5, 1, 0.7); //ToDo : Вынести в другое место. viewport.Simple3DRenderer.SetColor(color, color * ProjectSettings.Get.HiddenByOtherObjectsColorMultiplier); foreach (var arrow in skeletonArrows) { viewport.Simple3DRenderer.AddArrow(transformMatrix * arrow.Start, transformMatrix * arrow.End); } } } bool CheckNeedModifiableMesh() { if (CalculateOnCPU) { if (ReplaceSkeleton.ReferenceSpecified) { return(true); } var mesh = ParentMeshInSpace?.Mesh.Value; if (mesh != null && mesh.Skeleton.ReferenceSpecified) { return(true); } if (PlayAnimation.ReferenceSpecified) { return(true); } } return(false); } void UpdateModifiableMesh(ViewportRenderingContext context) { var originalMesh = ParentMeshInSpace.Mesh.Value; var modifiableMesh = ParentMeshInSpace.ModifiableMesh; Component_Skeleton skeleton = ReplaceSkeleton; if (skeleton == null) { skeleton = originalMesh.Skeleton; } if (skeleton != null) { //!!!!сериализовывать var animation = PlayAnimation.Value; if (animation != null) { UpdateAnimationTime(); //settings.animationStates = new AnimationStateItem[ 1 ]; //settings.animationStates[ 0 ] = new AnimationStateItem( animation, currentLocalTime, 1 ); var skeletonAnimation = animation as Component_SkeletonAnimation; var track = skeletonAnimation?.Track.Value; if (track != null || CalculateBoneTransforms != null) { Update(skeleton, track, currentAnimationTime); CalculateCPU(skeleton, originalMesh, modifiableMesh); } } if (needResetToOriginalMesh) { needResetToOriginalMesh = false; if (CalculateOnCPU) { ResetToOriginalMesh(originalMesh, modifiableMesh); } } } } ///////////////////////////////////////// void ResetTime(bool needResetToOriginalMesh) { if (needResetToOriginalMesh) { this.needResetToOriginalMesh = true; } currentEngineTime = EngineApp.EngineTime; currentAnimationTime = (PlayAnimation.Value as Component_SkeletonAnimation)?.TrackStartTime ?? 0; } void UpdateAnimationTime() { double t = EngineApp.EngineTime; double increment = t - currentEngineTime; currentEngineTime = t; currentAnimationTime += increment * Speed; var animation = PlayAnimation.Value as Component_SkeletonAnimation; if (animation != null) { double animationStartTime = animation.TrackStartTime; double animationLength = animation.Length; if (animationLength > 0) { if (AutoRewind) { while (currentAnimationTime > animationStartTime + animationLength) { currentAnimationTime -= animationLength; } while (currentAnimationTime < animationStartTime) { currentAnimationTime += animationLength; } } else { MathEx.Clamp(ref currentAnimationTime, animationStartTime, animationStartTime + animationLength); } } else { currentAnimationTime = animationStartTime; } } else { currentAnimationTime = 0; } }