public void UpdateThrustFlame() { ThrustRadiusRand = MyUtils.GetRandomFloat(0.9f, 1.1f); ThrustLengthRand = CurrentStrength * 10 * MyUtils.GetRandomFloat(0.6f, 1.0f) * BlockDefinition.FlameLengthScale; ThrustThicknessRand = MyUtils.GetRandomFloat(ThrustRadiusRand * 0.90f, ThrustRadiusRand); }
private void GridViewBind() { GridView1.DataSource = MyUtils.UserBoard(10); GridView1.DataBind(); }
private static void Generator(int version, int seed, float size, out MyCompositeShapeGeneratedData data) { Debug.Assert(size != 0, "Size could not be zero."); if (size == 0) { size = MyUtils.GetRandomFloat(128, 512); } var random = MyRandom.Instance; using (var stateToken = random.PushSeed(seed)) { data = new MyCompositeShapeGeneratedData(); data.FilledShapes = new MyCsgShapeBase[2]; data.RemovedShapes = new MyCsgShapeBase[2]; data.MacroModule = new MySimplexFast(seed: seed, frequency: 7f / size); switch (random.Next() & 0x1) { case 0: data.DetailModule = new MyRidgedMultifractalFast( seed: seed, quality: MyNoiseQuality.Low, frequency: random.NextFloat() * 0.09f + 0.11f, layerCount: 1); break; case 1: default: data.DetailModule = new MyBillowFast( seed: seed, quality: MyNoiseQuality.Low, frequency: random.NextFloat() * 0.07f + 0.13f, layerCount: 1); break; } float halfSize = size * 0.5f; float storageSize = VRageMath.MathHelper.GetNearestBiggerPowerOfTwo(size); float halfStorageSize = storageSize * 0.5f; float storageOffset = halfStorageSize - halfSize; MyCsgShapeBase primaryShape; { // determine primary shape var primaryType = random.Next() % 3; switch (primaryType) { case 0: //ShapeType.Torus { var secondaryRadius = (random.NextFloat() * 0.05f + 0.1f) * size; var torus = new MyCsgTorus( translation: new Vector3(halfStorageSize), invRotation: CreateRandomRotation(random), primaryRadius: (random.NextFloat() * 0.1f + 0.2f) * size, secondaryRadius: secondaryRadius, secondaryHalfDeviation: (random.NextFloat() * 0.4f + 0.4f) * secondaryRadius, deviationFrequency: random.NextFloat() * 0.8f + 0.2f, detailFrequency: random.NextFloat() * 0.6f + 0.4f); primaryShape = torus; } break; case 1: //ShapeType.Sphere default: { var sphere = new MyCsgSphere( translation: new Vector3(halfStorageSize), radius: (random.NextFloat() * 0.1f + 0.35f) * size, halfDeviation: (random.NextFloat() * 0.05f + 0.05f) * size + 1f, deviationFrequency: random.NextFloat() * 0.8f + 0.2f, detailFrequency: random.NextFloat() * 0.6f + 0.4f); primaryShape = sphere; } break; } } { // add some additional shapes int filledShapeCount = 0; data.FilledShapes[filledShapeCount++] = primaryShape; while (filledShapeCount < data.FilledShapes.Length) { var fromBorders = size * (random.NextFloat() * 0.2f + 0.1f) + 2f; var fromBorders2 = 2f * fromBorders; var sizeMinusFromBorders2 = size - fromBorders2; var shapeType = random.Next() % 3; switch (shapeType) { case 0: //ShapeType.Sphere { Vector3 center = CreateRandomPointOnBox(random, sizeMinusFromBorders2) + fromBorders; float radius = fromBorders * (random.NextFloat() * 0.4f + 0.35f); MyCsgSphere sphere = new MyCsgSphere( translation: center + storageOffset, radius: radius, halfDeviation: radius * (random.NextFloat() * 0.1f + 0.1f), deviationFrequency: random.NextFloat() * 0.8f + 0.2f, detailFrequency: random.NextFloat() * 0.6f + 0.4f); data.FilledShapes[filledShapeCount++] = sphere; } break; case 1: //ShapeType.Capsule { var start = CreateRandomPointOnBox(random, sizeMinusFromBorders2) + fromBorders; var end = new Vector3(size) - start; if ((random.Next() % 2) == 0) { MyUtils.Swap(ref start.X, ref end.X); } if ((random.Next() % 2) == 0) { MyUtils.Swap(ref start.Y, ref end.Y); } if ((random.Next() % 2) == 0) { MyUtils.Swap(ref start.Z, ref end.Z); } float radius = (random.NextFloat() * 0.25f + 0.5f) * fromBorders; MyCsgCapsule capsule = new MyCsgCapsule( pointA: start + storageOffset, pointB: end + storageOffset, radius: radius, halfDeviation: (random.NextFloat() * 0.25f + 0.5f) * radius, deviationFrequency: (random.NextFloat() * 0.4f + 0.4f), detailFrequency: (random.NextFloat() * 0.6f + 0.4f)); data.FilledShapes[filledShapeCount++] = capsule; } break; case 2: //ShapeType.Torus { Vector3 center = CreateRandomPointInBox(random, sizeMinusFromBorders2) + fromBorders; var rotation = CreateRandomRotation(random); var borderDistance = ComputeBoxSideDistance(center, size); var secondaryRadius = (random.NextFloat() * 0.15f + 0.1f) * borderDistance; var torus = new MyCsgTorus( translation: center + storageOffset, invRotation: rotation, primaryRadius: (random.NextFloat() * 0.2f + 0.5f) * borderDistance, secondaryRadius: secondaryRadius, secondaryHalfDeviation: (random.NextFloat() * 0.25f + 0.2f) * secondaryRadius, deviationFrequency: random.NextFloat() * 0.8f + 0.2f, detailFrequency: random.NextFloat() * 0.6f + 0.4f); data.FilledShapes[filledShapeCount++] = torus; } break; } } } { // make some holes int removedShapesCount = 0; while (removedShapesCount < data.RemovedShapes.Length) { var fromBorders = size * (random.NextFloat() * 0.2f + 0.1f) + 2f; var fromBorders2 = 2f * fromBorders; var sizeMinusFromBorders2 = size - fromBorders2; var shapeType = random.Next() % 7; switch (shapeType) { // Sphere case 0: { Vector3 center = CreateRandomPointInBox(random, sizeMinusFromBorders2) + fromBorders; float borderDistance = ComputeBoxSideDistance(center, size); float radius = (random.NextFloat() * 0.4f + 0.3f) * borderDistance; MyCsgSphere sphere = new MyCsgSphere( translation: center + storageOffset, radius: radius, halfDeviation: (random.NextFloat() * 0.3f + 0.35f) * radius, deviationFrequency: (random.NextFloat() * 0.8f + 0.2f), detailFrequency: (random.NextFloat() * 0.6f + 0.4f)); data.RemovedShapes[removedShapesCount++] = sphere; break; } // Torus case 1: case 2: case 3: { Vector3 center = CreateRandomPointInBox(random, sizeMinusFromBorders2) + fromBorders; var rotation = CreateRandomRotation(random); var borderDistance = ComputeBoxSideDistance(center, size); var secondaryRadius = (random.NextFloat() * 0.15f + 0.1f) * borderDistance; var torus = new MyCsgTorus( translation: center + storageOffset, invRotation: rotation, primaryRadius: (random.NextFloat() * 0.2f + 0.5f) * borderDistance, secondaryRadius: secondaryRadius, secondaryHalfDeviation: (random.NextFloat() * 0.25f + 0.2f) * secondaryRadius, deviationFrequency: random.NextFloat() * 0.8f + 0.2f, detailFrequency: random.NextFloat() * 0.6f + 0.4f); data.RemovedShapes[removedShapesCount++] = torus; } break; // Capsule default: { var start = CreateRandomPointOnBox(random, sizeMinusFromBorders2) + fromBorders; var end = new Vector3(size) - start; if ((random.Next() % 2) == 0) { MyUtils.Swap(ref start.X, ref end.X); } if ((random.Next() % 2) == 0) { MyUtils.Swap(ref start.Y, ref end.Y); } if ((random.Next() % 2) == 0) { MyUtils.Swap(ref start.Z, ref end.Z); } float radius = (random.NextFloat() * 0.25f + 0.5f) * fromBorders; MyCsgCapsule capsule = new MyCsgCapsule( pointA: start + storageOffset, pointB: end + storageOffset, radius: radius, halfDeviation: (random.NextFloat() * 0.25f + 0.5f) * radius, deviationFrequency: random.NextFloat() * 0.4f + 0.4f, detailFrequency: random.NextFloat() * 0.6f + 0.4f); data.RemovedShapes[removedShapesCount++] = capsule; } break; } } } { // generating materials // What to do when we (or mods) change the number of materials? Same seed will then produce different results. FillMaterials(version); Action <List <MyVoxelMaterialDefinition> > shuffleMaterials = (list) => { int n = list.Count; while (n > 1) { int k = (int)random.Next() % n; n--; var value = list[k]; list[k] = list[n]; list[n] = value; } }; shuffleMaterials(m_depositMaterials); if (m_surfaceMaterials.Count == 0) { if (m_depositMaterials.Count == 0) { data.DefaultMaterial = m_coreMaterials[(int)random.Next() % m_coreMaterials.Count]; } else { data.DefaultMaterial = m_depositMaterials[(int)random.Next() % m_depositMaterials.Count]; } } else { data.DefaultMaterial = m_surfaceMaterials[(int)random.Next() % m_surfaceMaterials.Count]; } int depositCount = Math.Max((int)Math.Log(size), data.FilledShapes.Length); data.Deposits = new MyCompositeShapeOreDeposit[depositCount]; var depositSize = size / 10f; MyVoxelMaterialDefinition material = data.DefaultMaterial; int currentMaterial = 0; for (int i = 0; i < data.FilledShapes.Length; ++i) { if (i == 0) { if (m_coreMaterials.Count == 0) { if (m_depositMaterials.Count == 0) { if (m_surfaceMaterials.Count != 0) { material = m_surfaceMaterials[(int)random.Next() % m_surfaceMaterials.Count]; } } else { material = m_depositMaterials[currentMaterial++]; } } else { material = m_coreMaterials[(int)random.Next() % m_coreMaterials.Count]; } } else { if (m_depositMaterials.Count == 0) { if (m_surfaceMaterials.Count != 0) { material = m_surfaceMaterials[(int)random.Next() % m_surfaceMaterials.Count]; } } else { material = m_depositMaterials[currentMaterial++]; } } data.Deposits[i] = new MyCompositeShapeOreDeposit(data.FilledShapes[i].DeepCopy(), material); data.Deposits[i].Shape.ShrinkTo(random.NextFloat() * 0.15f + 0.6f); if (currentMaterial == m_depositMaterials.Count) { currentMaterial = 0; shuffleMaterials(m_depositMaterials); } } for (int i = data.FilledShapes.Length; i < depositCount; ++i) { var center = CreateRandomPointInBox(random, size * 0.7f) + storageOffset + size * 0.15f; var radius = random.NextFloat() * depositSize + 8f; random.NextFloat(); random.NextFloat();//backwards compatibility MyCsgShapeBase shape = new MyCsgSphere(center, radius); if (m_depositMaterials.Count == 0) { material = m_surfaceMaterials[currentMaterial++]; } else { material = m_depositMaterials[currentMaterial++]; } data.Deposits[i] = new MyCompositeShapeOreDeposit(shape, material); if (m_depositMaterials.Count == 0) { if (currentMaterial == m_surfaceMaterials.Count) { currentMaterial = 0; shuffleMaterials(m_surfaceMaterials); } } else { if (currentMaterial == m_depositMaterials.Count) { currentMaterial = 0; shuffleMaterials(m_depositMaterials); } } } m_surfaceMaterials.Clear(); m_coreMaterials.Clear(); m_depositMaterials.Clear(); } } }
// This method is like a constructor (which we can't use because billboards are allocated from a pool). // It starts/initializes a billboard. Refs used only for optimalization public static void CreateBillboard(VRageRender.MyBillboard billboard, ref MyQuadD quad, string material, string blendMaterial, float textureBlendRatio, ref Vector4 color, ref Vector3D origin, Vector2 uvOffset, bool colorize = false, bool near = false, bool lowres = false, int customViewProjection = -1, float reflectivity = 0) { System.Diagnostics.Debug.Assert(material != null); if (string.IsNullOrEmpty(material) || !MyTransparentMaterials.ContainsMaterial(material)) { material = "ErrorMaterial"; color = Vector4.One; } billboard.Material = material; billboard.BlendMaterial = blendMaterial; billboard.BlendTextureRatio = textureBlendRatio; MyUtils.AssertIsValid(quad.Point0); MyUtils.AssertIsValid(quad.Point1); MyUtils.AssertIsValid(quad.Point2); MyUtils.AssertIsValid(quad.Point3); // Billboard vertices billboard.Position0 = quad.Point0; billboard.Position1 = quad.Point1; billboard.Position2 = quad.Point2; billboard.Position3 = quad.Point3; billboard.UVOffset = uvOffset; billboard.UVSize = Vector2.One; billboard.EnableColorize = colorize; if (billboard.EnableColorize) { billboard.Size = (float)(billboard.Position0 - billboard.Position2).Length(); } // Distance for sorting // IMPORTANT: Must be calculated before we do color and alpha misting, because we need distance there Vector3D cameraPosition = customViewProjection == -1 ? MyTransparentGeometry.Camera.Translation : VRageRender.MyRenderProxy.BillboardsViewProjectionWrite[customViewProjection].CameraPosition; billboard.DistanceSquared = (float)Vector3D.DistanceSquared(cameraPosition, origin); // Color billboard.Color = color; billboard.ColorIntensity = 1; billboard.Reflectivity = reflectivity; billboard.Near = near; billboard.Lowres = lowres; billboard.CustomViewProjection = customViewProjection; billboard.ParentID = -1; billboard.SoftParticleDistanceScale = 1; // Alpha depends on distance to camera. Very close bilboards are more transparent, so player won't see billboard errors or rotating billboards var mat = MyTransparentMaterials.GetMaterial(billboard.Material); if (mat.AlphaMistingEnable) { billboard.Color *= MathHelper.Clamp(((float)Math.Sqrt(billboard.DistanceSquared) - mat.AlphaMistingStart) / (mat.AlphaMistingEnd - mat.AlphaMistingStart), 0, 1); } billboard.Color *= mat.Color; billboard.ContainedBillboards.Clear(); }
public static string FormatDataSize(double size) { string p = MyUtils.FormatByteSizePrefix(ref size); return($"{size:N}{p}B"); }
public void Update() { VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("ParticleLight-Update"); bool created = false; if (Enabled) { if (m_renderObjectID == MyRenderProxy.RENDER_ID_UNASSIGNED) { InitLight(); created = true; } } else { if (m_renderObjectID != MyRenderProxy.RENDER_ID_UNASSIGNED) { CloseLight(); } VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock(); return; } Vector3 localPosition; Position.GetInterpolatedValue(m_effect.GetElapsedTime(), out localPosition); Vector3 localPositionVar; PositionVar.GetInterpolatedValue(m_effect.GetElapsedTime(), out localPositionVar); Vector3 localPositionVarRnd = new Vector3( MyUtils.GetRandomFloat(-localPositionVar.X, localPositionVar.X), MyUtils.GetRandomFloat(-localPositionVar.Y, localPositionVar.Y), MyUtils.GetRandomFloat(-localPositionVar.Z, localPositionVar.Z)); localPosition += localPositionVarRnd; Vector4 color; Color.GetInterpolatedValue(m_effect.GetElapsedTime(), out color); float colorVar; ColorVar.GetInterpolatedValue(m_effect.GetElapsedTime(), out colorVar); float colorVarRnd = MyUtils.GetRandomFloat(1 - colorVar, 1 + colorVar); color.X = MathHelper.Clamp(color.X * colorVarRnd, 0, 1); color.Y = MathHelper.Clamp(color.Y * colorVarRnd, 0, 1); color.Z = MathHelper.Clamp(color.Z * colorVarRnd, 0, 1); float range; Range.GetInterpolatedValue(m_effect.GetElapsedTime(), out range); float rangeVar; RangeVar.GetInterpolatedValue(m_effect.GetElapsedTime(), out rangeVar); float rangeVarRnd = MyUtils.GetRandomFloat(-rangeVar, rangeVar); range += rangeVarRnd; float intensity; Intensity.GetInterpolatedValue(m_effect.GetElapsedTime(), out intensity); float intensityVar; IntensityVar.GetInterpolatedValue(m_effect.GetElapsedTime(), out intensityVar); float intensityRnd = MyUtils.GetRandomFloat(-intensityVar, intensityVar); intensity += intensityRnd; if (m_effect.IsStopped) { intensity = 0; } Vector3D position = Vector3D.Transform(localPosition * m_effect.GetEmitterScale(), m_effect.WorldMatrix); if ((m_position != position) || (m_color != color) || (m_range != range) || (m_intensity != intensity) || created) { m_color = color; m_intensity = intensity; m_range = range; m_position = position; MyLightLayout light = new MyLightLayout() { Range = m_range * m_effect.GetEmitterScale(), Color = new Vector3(m_color), Falloff = 1, GlossFactor = 1, DiffuseFactor = 1, }; UpdateRenderLightData renderLightData = new UpdateRenderLightData() { ID = m_renderObjectID, Position = m_position, Type = LightTypeEnum.PointLight, ParentID = -1, UseInForwardRender = true, SpecularColor = new Vector3(m_color), PointLightOn = true, PointLightIntensity = m_intensity, PointLight = light, }; MyRenderProxy.UpdateRenderLight(ref renderLightData); } VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock(); }
void ClampSmokesToGenerate() { m_smokesToGenerate = MyUtils.GetClampInt(m_smokesToGenerate, 0, MyGatlingConstants.SMOKES_MAX); }
private void UpdateScattering(ref MatrixD weaponAnimMatrix, MyHandItemDefinition handItemDefinition) { MyEngineerToolBase currentWeapon = base.Character.CurrentWeapon as MyEngineerToolBase; bool flag = false; if (handItemDefinition.ScatterSpeed > 0f) { bool hasHitBlock = false; if (currentWeapon != null) { hasHitBlock = currentWeapon.HasHitBlock; } flag = this.IsShooting & hasHitBlock; if (!flag && (this.m_currentScatterToAnimRatio >= 1f)) { this.m_currentScatterBlend = 0f; } else { if (this.m_currentScatterBlend == 0f) { this.m_lastScatterPos = Vector3.Zero; } if (this.m_currentScatterBlend == handItemDefinition.ScatterSpeed) { this.m_lastScatterPos = this.m_currentScatterPos; this.m_currentScatterBlend = 0f; } if ((this.m_currentScatterBlend == 0f) || (this.m_currentScatterBlend == handItemDefinition.ScatterSpeed)) { this.m_currentScatterPos = new Vector3(MyUtils.GetRandomFloat(-handItemDefinition.ShootScatter.X / 2f, handItemDefinition.ShootScatter.X / 2f), MyUtils.GetRandomFloat(-handItemDefinition.ShootScatter.Y / 2f, handItemDefinition.ShootScatter.Y / 2f), MyUtils.GetRandomFloat(-handItemDefinition.ShootScatter.Z / 2f, handItemDefinition.ShootScatter.Z / 2f)); } this.m_currentScatterBlend += 0.01f; if (this.m_currentScatterBlend > handItemDefinition.ScatterSpeed) { this.m_currentScatterBlend = handItemDefinition.ScatterSpeed; } Vector3 vector = Vector3.Lerp(this.m_lastScatterPos, this.m_currentScatterPos, this.m_currentScatterBlend / handItemDefinition.ScatterSpeed); weaponAnimMatrix.Translation += (1f - this.m_currentScatterToAnimRatio) * vector; } this.m_currentScatterToAnimRatio += flag ? -0.1f : 0.1f; if (this.m_currentScatterToAnimRatio > 1f) { this.m_currentScatterToAnimRatio = 1f; } else if (this.m_currentScatterToAnimRatio < 0f) { this.m_currentScatterToAnimRatio = 0f; } } }
protected void btnSendCode_Click(object sender, EventArgs e) { if (regexEmailValid.IsValid && RequiredFieldValidator1.IsValid) { DB_Helper db = new DB_Helper(); string em = txtEmail.Text; if (em.StartsWith("ACTIVATE")) { db.Execute(string.Format("update Users set email_verified=1 where id_user = {0}", MyUtils.ID_USER)); MyUtils.RefreshUserRow(); } else { int id_user = db.ExecuteScalarInt("select id_user from users where email=" + MyUtils.safe(em), 0); if (id_user > 0 && id_user != MyUtils.ID_USER) { Session["message"] = "ERROR: This email is already used by a different user."; return; } db.Execute("update users set email=" + MyUtils.safe(em) + " where id_user="******"EMAIL_ACTIVATE", MyUtils.ID_USER); Session["message"] = "OK: Activation email was sent. Please check your inbox."; } } else { Session["message"] = "ERROR: Invalid email."; } bool needtoverify = Convert.ToUInt32(MyUtils.GetUserField("email_verified")) == 0; if (!needtoverify) { Response.Redirect("/Account/"); Session["message"] = "Account is active."; } }
public void SetHalfPixel(int screenSizeX, int screenSizeY) { m_D3DEffect.SetValue(m_halfPixel, MyUtils.GetHalfPixel(screenSizeX, screenSizeY)); }
private void FindAndCaculateFromAdvancedStatic(GridSimulationData simData) { // Instead of using uniform distribution of support between all fixed nodes, calculate non-uniform distribution based on vectors for few closest nodes // Use this distribution when setting support weight and transferring mass // SupportingWeights: x * support // ? TransferMass: x * numStaticBlocksForCurrentDynamicBlock * TransferMass int keepLookingDistance = (int)ClosestDistanceThreshold; // How far keep looking when closest static block is found simData.Queue.Clear(); // Set initial distance to max for all dynamic foreach (var dyn in simData.DynamicBlocks) { dyn.Distance = int.MaxValue; } // Wide search from all static blocks foreach (var stat in simData.StaticBlocks) { stat.Distance = 0; var path = new PathInfo() { EndNode = stat, StartNode = stat, Distance = 0, DirectionRatio = 1 }; #if ENHANCED_DEBUG path.PathNodes.Add(stat); #endif simData.Queue.Enqueue(path); } while (simData.Queue.Count > 0) { var path = simData.Queue.Dequeue(); foreach (var neighbour in path.EndNode.Neighbours) { if (neighbour.IsStatic) { continue; } PathInfo neighbourPath; if (!neighbour.Paths.TryGetValue(path.StartNode, out neighbourPath)) { if ((path.Distance - keepLookingDistance) <= neighbour.Distance) { neighbour.Distance = Math.Min(neighbour.Distance, path.Distance); neighbourPath = new PathInfo(); neighbourPath.Distance = path.Distance + 1; neighbourPath.StartNode = path.StartNode; neighbourPath.EndNode = neighbour; #if ENHANCED_DEBUG neighbourPath.PathNodes = path.PathNodes.ToList(); neighbourPath.PathNodes.Add(neighbour); #endif neighbourPath.Parents.Add(path); float t = neighbour.PhysicalMaterial.HorisontalTransmissionMultiplier * path.EndNode.PhysicalMaterial.HorisontalTransmissionMultiplier; float massRatio = MathHelper.Clamp(path.EndNode.Mass / (neighbour.Mass + path.EndNode.Mass), 0, 1); t *= neighbour.Mass * massRatio; //Horisontal transmission is very low on weak objects (floor, roof). Should be correctly get from mount point area float[] horisontalTransmission = new float[] { t, 1, t }; int component = ((Vector3D)(neighbour.Pos - path.EndNode.Pos)).AbsMaxComponent(); neighbourPath.DirectionRatio = path.DirectionRatio * DirectionRatios[component] * horisontalTransmission[component]; neighbour.Paths.Add(path.StartNode, neighbourPath); simData.Queue.Enqueue(neighbourPath); path.StartNode.OwnedPaths.Push(neighbourPath); } } else if (neighbourPath.Distance == path.Distance + 1) // Another path with same length { neighbourPath.Parents.Add(path); } } } // Iterate all dynamic blocks and calculate support ratio for each static foreach (var dyn in simData.DynamicBlocks) { dyn.PathCount = 1; if (dyn.Pos == new Vector3I(-6, 6, 0)) { } // Uniform distribution //foreach (var s in dyn.Paths) //{ // s.Value.Ratio = 1.0f / dyn.Paths.Count; //} //continue; // Non-uniform distribution // Calculate angle between one vector and all other // Split weight support based on sum angle ratio float totalAngles = 0; if (dyn.Paths.Count > 1) { foreach (var s in dyn.Paths) { Vector3 localVector1 = (dyn.Pos - s.Value.StartNode.Pos) * m_grid.GridSize; Vector3 worldVector1 = Vector3.TransformNormal(localVector1, m_grid.WorldMatrix); // float sumAngle = 0; float sumAngleReduced = 0; foreach (var s2 in dyn.Paths) { if (s.Key == s2.Key) { continue; } Vector3 localVector2 = (dyn.Pos - s2.Value.StartNode.Pos) * m_grid.GridSize; Vector3 worldVector2 = Vector3.TransformNormal(localVector2, m_grid.WorldMatrix); float angle = MyUtils.GetAngleBetweenVectorsAndNormalise(worldVector1, worldVector2); float dot1 = Math.Abs(Vector3.Normalize(worldVector1).Dot(Vector3.Up)); float dot2 = Math.Abs(Vector3.Normalize(worldVector2).Dot(Vector3.Up)); float lowerBound = 0.1f; dot1 = MathHelper.Lerp(lowerBound, 1, dot1); dot2 = MathHelper.Lerp(lowerBound, 1, dot2); float reducedAngle = angle; if (!MyPetaInputComponent.OLD_SI) { //Reduce dependent on gravity reducedAngle = angle * dot1 * s.Value.DirectionRatio; } //sumAngle += angle; sumAngleReduced += reducedAngle; } s.Value.Ratio = sumAngleReduced; totalAngles += sumAngleReduced; } foreach (var s in dyn.Paths) { if (totalAngles > 0) { s.Value.Ratio /= totalAngles; if (s.Value.Ratio < 0.000001f) { s.Value.Ratio = 0; } } else { s.Value.Ratio = 1; } } } else { foreach (var s in dyn.Paths) { s.Value.Ratio = 1.0f; } } } // Iterate all static blocks and calculate support mass and mass transfer foreach (var staticBlock in simData.StaticBlocks) { // Initial mass and ratio foreach (var path in staticBlock.OwnedPaths) { path.EndNode.TransferMass = 0; } // For each block in path (ordered by distance, furthest first) while (staticBlock.OwnedPaths.Count > 0) { var pathInfo = staticBlock.OwnedPaths.Pop(); var node = pathInfo.EndNode; Debug.Assert(pathInfo.StartNode == staticBlock, "Wrong path"); Debug.Assert(!node.IsStatic, "Static node unexpected"); float outgoing = node.TransferMass + node.Mass * pathInfo.Ratio; //float outgoindTotal = 0; //foreach (var p in pathInfo.Parents) // outgoindTotal += p.DirectionRatio; if (node.Pos == new Vector3I(-1, 1, 0)) { } float outgoingPerParent = outgoing / pathInfo.Parents.Count; foreach (var parent in pathInfo.Parents) { var delta = parent.EndNode.Pos - node.Pos; // Node to parent int index, parentIndex; if (delta.X + delta.Y + delta.Z > 0) { index = delta.Y + delta.Z * 2; // UnitX = 0, UnitY = 1, UnitZ = 2 parentIndex = index + 3; } else { index = -delta.X * 3 - delta.Y * 4 - delta.Z * 5; // // -UnitX = 3, -UnitY = 4, -UnitZ = 5 parentIndex = index - 3; } //outgoingPerParent = outgoing * parent.DirectionRatio / outgoindTotal; #if ENHANCED_DEBUG node.OutgoingNodeswWithWeights[index].Add(new Tuple <Node, float>(parent.EndNode, outgoingPerParent)); #endif if (index == 0 || index == 2 || index == 3 || index == 5) { node.SupportingWeights[index] -= node.PhysicalMaterial.HorisontalFragility * outgoingPerParent; } else { node.SupportingWeights[index] -= outgoingPerParent; } if (parentIndex == 0 || parentIndex == 2 || parentIndex == 3 || parentIndex == 5) { parent.EndNode.SupportingWeights[parentIndex] += parent.EndNode.PhysicalMaterial.HorisontalFragility * outgoingPerParent; } else { parent.EndNode.SupportingWeights[parentIndex] += outgoingPerParent; } #if ENHANCED_DEBUG parent.EndNode.SupportingNodeswWithWeights[parentIndex].Add(new Tuple <Node, float>(node, outgoingPerParent)); #endif parent.EndNode.TransferMass += outgoingPerParent; } node.TransferMass -= outgoing; } } using (Stats.Timing.Measure("SI - Sum", VRage.Stats.MyStatTypeEnum.Sum | VRage.Stats.MyStatTypeEnum.DontDisappearFlag)) { foreach (var node in simData.All) { //node.Value.TotalSupportingWeight = 0; } foreach (var node in simData.All) { if (node.Key == new Vector3I(-1, 1, 0)) { } float sum = 0; for (int i = 0; i < 6; i++) { float sideWeight = node.Value.SupportingWeights[i]; sum += Math.Abs(sideWeight); //sum = Math.Max(sum, Math.Abs(node.Value.SupportingWeights[i])); } if (!(sum == 0 && node.Value.PathCount == 0)) { // sum = sum * 2 - 1; node.Value.TotalSupportingWeight += node.Value.IsStatic ? 0 : (sum * 0.5f / node.Value.PathCount); } } // Idea behind blur: // When block is supporting too much weight, it deforms still supports something, but allows neighbour block to support more weight, thus sharing support List <Node> supportingNeighbours = new List <Node>(); foreach (var node in simData.All) { supportingNeighbours.Clear(); float totalSharedSupport = node.Value.TotalSupportingWeight; float totalMass = node.Value.Mass; foreach (var neighbour in node.Value.Neighbours) { bool isHorisontalNeighbour = neighbour.Pos.Y == node.Key.Y; bool isVerticallySupported = neighbour.Paths.Any(x => (x.Key.Pos.X == node.Key.X && x.Key.Pos.Z == node.Key.Z)); if (isHorisontalNeighbour && isVerticallySupported) { totalSharedSupport += neighbour.TotalSupportingWeight; totalMass += neighbour.Mass; supportingNeighbours.Add(neighbour); } } if (supportingNeighbours.Count > 0) { float supportPerNode = totalSharedSupport / totalMass; foreach (var neighbour in supportingNeighbours) { neighbour.TotalSupportingWeight = supportPerNode * neighbour.Mass; } node.Value.TotalSupportingWeight = supportPerNode * node.Value.Mass; } } foreach (var node in simData.All) { simData.TotalMax = Math.Max(simData.TotalMax, node.Value.TotalSupportingWeight); } // var timeMs = (Stopwatch.GetTimestamp() - ts) / (float)Stopwatch.Frequency * 1000.0f; //Console.WriteLine(String.Format("Generated structural integrity, time: {0}ms, object name: {1}", timeMs, m_grid.ToString())); } }
private void UpdatePlayerPainters() { ActiveMarks.Clear(); foreach (var pair in PlayerDummyTargets) { IMyPlayer player; if (Players.TryGetValue(pair.Key, out player)) { var painted = pair.Value.PaintedTarget; MyEntity target; if (!painted.Dirty && painted.EntityId != 0 && Tick - painted.LastInfoTick < 300 && !MyUtils.IsZero(painted.LocalPosition) && MyEntities.TryGetEntityById(painted.EntityId, out target)) { var rep = MyIDModule.GetRelationPlayerPlayer(PlayerId, player.IdentityId); var self = rep == MyRelationsBetweenPlayers.Self; var friend = rep == MyRelationsBetweenPlayers.Allies; var neut = rep == MyRelationsBetweenPlayers.Neutral; var color = neut ? new Vector4(1, 1, 1, 1) : self ? new Vector4(0.025f, 1f, 0.25f, 2) : friend ? new Vector4(0.025f, 0.025f, 1, 2) : new Vector4(1, 0.025f, 0.025f, 2); ActiveMarks.Add(new MyTuple <IMyPlayer, Vector4, GridAi.FakeTarget>(player, color, painted)); } } } }
public static string GetRandomDebrisVoxel() { return(MyUtils.GetRandomItem(m_debrisVoxels)); }
void hotKeyHook_KeyPressed(object sender, MyUtils.KeyPressedEventArgs e) { restoreMe(); String wordToDefine = getWordToDefine(); String definitionUrl = getWiktionaryUrl(wordToDefine); goToUrl(definitionUrl); }
public EditInstrumentViewModel(Instrument model, IDataClient client, IClosableView view, IDialogCoordinator dialogCoordinator) : base(model, new InstrumentValidator()) { _view = view; DialogCoordinator = dialogCoordinator; if (model.Sessions == null) { model.Sessions = new List <InstrumentSession>(); } if (model.Tags == null) { model.Tags = new List <Tag>(); } foreach (var session in model.Sessions) { Sessions.Add(new SessionViewModel(session)); } ContractMonths = new ObservableCollection <KeyValuePair <int, string> >(); //fill the continuous futures contrat month combobox for (int i = 1; i < 10; i++) { ContractMonths.Add(new KeyValuePair <int, string>(i, MyUtils.Ordinal(i) + " Contract")); } Load = ReactiveCommand.CreateFromTask(async _ => { var tags = client.GetTags(); var sessionTemplates = client.GetSessionTemplates(); var exchanges = client.GetExchanges(); var underlyingSymbols = client.GetUnderlyingSymbols(); var datasources = client.GetDatasources(); await Task.WhenAll(tags, sessionTemplates, exchanges, underlyingSymbols, datasources).ConfigureAwait(true); var responses = new ApiResponse[] { tags.Result, sessionTemplates.Result, exchanges.Result, underlyingSymbols.Result, datasources.Result }; if (await responses.DisplayErrors(this, DialogCoordinator).ConfigureAwait(true)) { return; } foreach (var tag in tags.Result.Result.Select(x => new CheckBoxTag(x, model.Tags.Contains(x)))) { AllTags.Add(tag); tag.PropertyChanged += Tag_PropertyChanged; } Exchanges.AddRange(exchanges.Result.Result); foreach (var template in sessionTemplates.Result.Result) { SessionTemplates.Add(template); } foreach (var us in underlyingSymbols.Result.Result) { UnderlyingSymbols.Add(us); } foreach (var ds in datasources.Result.Result) { Datasources.Add(ds); } }); //Sessions AddNewSession = ReactiveCommand.Create(() => AddSession()); RemoveSession = ReactiveCommand.Create <SessionViewModel>(ExecRemoveSession); //Save var saveCanExecute = this .WhenAnyValue(x => x.HasErrors) .Select(x => !x); Save = ReactiveCommand.CreateFromTask(async _ => { if (model.ID == null || model.ID <= 0) { //adding a new instrument return(await client.AddInstrument(model).ConfigureAwait(true)); } else { //updating an existing one return(await client.UpdateInstrument(model).ConfigureAwait(true)); } } , saveCanExecute); Save.Subscribe(async result => { var errors = await result.DisplayErrors(this, DialogCoordinator).ConfigureAwait(true); if (!errors) { AddedInstrument = result.Result; _view.Close(); } }); this.Validate(); }
private void DrawGravityIndicator(MyHudGravityIndicator indicator, MyHudCharacterInfo characterInfo) { if (indicator.Entity == null) { return; } Vector3 gravity = MyGravityProviderSystem.CalculateGravityInPoint(MySession.GetCameraControllerEnum() == MyCameraControllerEnum.Entity || MySession.GetCameraControllerEnum() == MyCameraControllerEnum.ThirdPersonSpectator ? indicator.Entity.PositionComp.WorldAABB.Center : MySpectatorCameraController.Static.Position); //gravity += MyPhysics.HavokWorld.Gravity; bool anyGravity = !MyUtils.IsZero(gravity.Length()); // Background and text drawing MyFontEnum font; StringBuilder text; m_hudIndicatorText.Clear(); m_hudIndicatorText.AppendFormatedDecimal("", gravity.Length() / 9.81f, 1, " g"); MyGuiPaddedTexture bg; if (anyGravity) { font = MyFontEnum.Blue; text = MyTexts.Get(MySpaceTexts.HudInfoGravity); bg = MyGuiConstants.TEXTURE_HUD_BG_MEDIUM_DEFAULT; } else { font = MyFontEnum.Red; text = MyTexts.Get(MySpaceTexts.HudInfoNoGravity); bg = MyGuiConstants.TEXTURE_HUD_BG_MEDIUM_RED; } bool drawOxygen = MySession.Static.Settings.EnableOxygen; Vector2 bgSizeDelta = new Vector2(0.015f, 0f); float oxygenLevel = 0f; Vector2 bgSize = bg.SizeGui + bgSizeDelta; Vector2 bgPos, textPos, gTextPos, position; MyGuiDrawAlignEnum align; if (indicator.Entity is MyCharacter) { bgPos = new Vector2(0.99f, 0.99f); bgPos = ConvertHudToNormalizedGuiPosition(ref bgPos); textPos = bgPos - bgSize * new Vector2(0.94f, 0.98f) + bg.PaddingSizeGui * Vector2.UnitY * 0.2f; gTextPos = bgPos - bgSize * new Vector2(0.56f, 0.98f) + bg.PaddingSizeGui * Vector2.UnitY * 0.2f; align = MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_BOTTOM; position = bgPos - bgSize * new Vector2(0.5f, 0.5f) + bg.PaddingSizeGui * Vector2.UnitY * 0.5f; oxygenLevel = (indicator.Entity as MyCharacter).EnvironmentOxygenLevel; } else { bgPos = new Vector2(0.01f, 1f - (characterInfo.Data.GetGuiHeight() + 0.02f)); bgPos = ConvertHudToNormalizedGuiPosition(ref bgPos); textPos = bgPos + bgSize * new Vector2(1 - 0.94f, -0.98f) + bg.PaddingSizeGui * Vector2.UnitY * 0.2f; gTextPos = bgPos + bgSize * new Vector2(1 - 0.56f, -0.98f) + bg.PaddingSizeGui * Vector2.UnitY * 0.2f; align = MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_BOTTOM; position = bgPos - bgSize * new Vector2(-0.5f, 0.5f) + bg.PaddingSizeGui * Vector2.UnitY * 0.5f; var cockpit = indicator.Entity as MyCockpit; if (cockpit != null && cockpit.Pilot != null) { oxygenLevel = cockpit.Pilot.EnvironmentOxygenLevel; } else { drawOxygen = false; } } if (drawOxygen) { bgSizeDelta += new Vector2(0f, 0.025f); } MyGuiManager.DrawSpriteBatch(bg.Texture, bgPos, bg.SizeGui + bgSizeDelta, Color.White, align); MyGuiManager.DrawString(font, text, textPos, m_textScale); if (drawOxygen) { var oxygenFont = MyFontEnum.Blue; var oxygenText = new StringBuilder("Oxygen: "); if (oxygenLevel == 0f) { oxygenText.Append("None"); oxygenFont = MyFontEnum.Red; } else if (oxygenLevel < 0.5f) { oxygenText.Append("Low"); oxygenFont = MyFontEnum.Red; } else { oxygenText.Append("High"); } MyGuiManager.DrawString(oxygenFont, oxygenText, textPos - new Vector2(0f, 0.025f), m_textScale); } if (anyGravity) { MyGuiManager.DrawString(MyFontEnum.White, m_hudIndicatorText, gTextPos, m_textScale); } position = MyGuiManager.GetHudSize() * ConvertNormalizedGuiToHud(ref position); if (MyVideoSettingsManager.IsTripleHead()) { position.X += 1.0f; } // Draw each of gravity indicators. foreach (var generatorGravity in MyGravityProviderSystem.GravityVectors) { DrawGravityVectorIndicator(position, generatorGravity, MyHudTexturesEnum.gravity_arrow, Color.Gray); } //if (MyPhysics.HavokWorld.Gravity != Vector3.Zero) // DrawGravityVectorIndicator(position, MyPhysics.HavokWorld.Gravity, MyHudTexturesEnum.gravity_arrow, Color.Gray); if (anyGravity) { DrawGravityVectorIndicator(position, gravity, MyHudTexturesEnum.gravity_arrow, Color.White); } // Draw center MyAtlasTextureCoordinate centerTextCoord; if (anyGravity) { centerTextCoord = GetTextureCoord(MyHudTexturesEnum.gravity_point_white); } else { centerTextCoord = GetTextureCoord(MyHudTexturesEnum.gravity_point_red); } float hudSizeX = MyGuiManager.GetSafeFullscreenRectangle().Width / MyGuiManager.GetHudSize().X; float hudSizeY = MyGuiManager.GetSafeFullscreenRectangle().Height / MyGuiManager.GetHudSize().Y; Vector2 rightVector = Vector2.UnitX; MyRenderProxy.DrawSpriteAtlas( m_atlas, position, centerTextCoord.Offset, centerTextCoord.Size, rightVector, new Vector2(hudSizeX, hudSizeY), MyHudConstants.HUD_COLOR_LIGHT, Vector2.One * 0.005f); }
private void ImportBtn_Click(object sender, RoutedEventArgs e) { Stopwatch sw = new Stopwatch(); sw.Start(); //check that we've got the relevant data needed if (!Data.Columns.Contains("Date") && !Data.Columns.Contains("DateTime")) { MessageBox.Show("Must have a date column."); return; } if ((BarSize)FrequencyComboBox.SelectedItem < BarSize.OneDay && !Data.Columns.Contains("DateTime") && !Data.Columns.Contains("Time")) { MessageBox.Show("Must have time column at this frequency"); return; } if (!Data.Columns.Contains("Open") || !Data.Columns.Contains("High") || !Data.Columns.Contains("Low") || !Data.Columns.Contains("Close")) { MessageBox.Show("Must have all OHLC columns."); return; } //make sure the timezone is set, and get it if (string.IsNullOrEmpty(_instrument.Exchange.Timezone)) { MessageBox.Show("Instrument's exchange has no set timezone, can't import."); return; } var tzInfo = TimeZoneInfo.FindSystemTimeZoneById(_instrument.Exchange.Timezone); //get the multipliers decimal priceMultiplier; int volumeMultiplier; bool parseWorked = decimal.TryParse(PriceMultiplier.Text, out priceMultiplier); if (!parseWorked) { priceMultiplier = 1; } parseWorked = int.TryParse(VolumeMultiplier.Text, out volumeMultiplier); if (!parseWorked) { volumeMultiplier = 1; } //lines to skip int toSkip; parseWorked = int.TryParse(StartingLine.Text, out toSkip); if (!parseWorked) { toSkip = 1; } //get the frequency var frequency = (BarSize)FrequencyComboBox.SelectedItem; //separator char[] separator = DelimiterBox.Text.ToCharArray(); List <OHLCBar> bars = new List <OHLCBar>(); string[] columns = new string[Data.Columns.Count]; for (int i = 0; i < Data.Columns.Count; i++) { columns[i] = Data.Columns[i].ColumnName; } //determining time: if the freq is >= one day, then the time is simply the session end for this day Dictionary <int, TimeSpan> sessionEndTimes = new Dictionary <int, TimeSpan>(); //1 day and up: we can load it all in one go with no trouble, also may require adjustment bool periodicSaving = frequency < BarSize.OneDay; OHLCBar bar; var barsCount = 0; using (StreamReader sr = new StreamReader(FilePathTextBox.Text)) { string line; while ((line = sr.ReadLine()) != null) { barsCount++; if (barsCount < toSkip) { continue; } try { bar = ParseLine(line.Split(separator), columns, priceMultiplier, volumeMultiplier); } catch (Exception ex) { MessageBox.Show("Importing error: " + ex.Message); return; } //only add the bar if it falls within the specified date range if (bar.DT >= MinDT.Value && bar.DT <= MaxDT.Value) { bars.Add(bar); } //with 30 bars, we make a check to ensure that the user has entered the correct frequency if (bars.Count == 30) { //the reason we have to use a bunch of bars and look for the most frequent timespan between them //is that session breaks, daily breaks, weekends, etc. can have different timespans despite the //correct frequency being chosen List <int> secDiffs = new List <int>(); for (int i = 1; i < bars.Count; i++) { secDiffs.Add((int)Math.Round((bars[i].DT - bars[i - 1].DT).TotalSeconds)); } int mostFrequent = secDiffs.MostFrequent(); if ((int)Math.Round(frequency.ToTimeSpan().TotalSeconds) != mostFrequent) { MessageBox.Show("You appear to have selected the wrong frequency."); return; } } if (periodicSaving && bars.Count > 1000) { //convert to exchange timezone ConvertTimeZone(bars, tzInfo); //low frequencies, < 1 day. No adjustment required and inserting data at intervals instead of all at once IDataClient client; //client.PushData(new DataAdditionRequest(frequency, _instrument, bars, OverwriteCheckbox.IsChecked.HasValue && OverwriteCheckbox.IsChecked.Value, false)); //todo remove dependency on DataStorageFactory using (var storage = DataStorageFactory.Get()) { try { storage.AddData(bars, _instrument, frequency, OverwriteCheckbox.IsChecked.HasValue && OverwriteCheckbox.IsChecked.Value, false); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } } bars.Clear(); } } } if (bars.Count == 0) { return; } //convert to exchange timezone ConvertTimeZone(bars, tzInfo); //if only the date column is set, we need to get the session info and generate the closing time ourselves if (frequency >= BarSize.OneDay && !Data.Columns.Contains("Time") && !Data.Columns.Contains("DateTime")) { //get the closing time for every day of the week var dotwValues = MyUtils.GetEnumValues <DayOfTheWeek>(); foreach (DayOfTheWeek d in dotwValues) { if (_instrument.Sessions.Any(x => x.ClosingDay == d && x.IsSessionEnd)) { var endTime = _instrument.Sessions.First(x => x.ClosingDay == d && x.IsSessionEnd).ClosingTime; sessionEndTimes.Add((int)d, endTime); } else { sessionEndTimes.Add((int)d, TimeSpan.FromSeconds(0)); } } for (int i = 0; i < bars.Count; i++) { int dayOfWeek = bars[i].DT.DayOfWeek.ToInt(); bars[i].DT = bars[i].DT.Date + sessionEndTimes[dayOfWeek]; } } //if there are no dividends/splits, but there IS an adjclose column, use that to adjust data right here //if there are divs/splits, adjustment will be done by the local storage if (frequency >= BarSize.OneDay && !Data.Columns.Contains("Dividends") && !Data.Columns.Contains("Splits") && Data.Columns.Contains("AdjClose")) { //if we have an adjusted close to work off of, we just use the ratio to get the OHL for (int i = 0; i < bars.Count; i++) { if (bars[i].AdjClose == null) { continue; } decimal ratio = bars[i].AdjClose.Value / bars[i].Close; bars[i].AdjOpen = bars[i].Open * ratio; bars[i].AdjHigh = bars[i].High * ratio; bars[i].AdjLow = bars[i].Low * ratio; } } //sort by date if (frequency >= BarSize.OneDay) { bars.Sort((x, y) => x.DT.CompareTo(y.DT)); } //try to import //todo remove dependency on DataStorageFactory using (var storage = DataStorageFactory.Get()) { try { storage.AddData(bars, _instrument, frequency, OverwriteCheckbox.IsChecked.HasValue && OverwriteCheckbox.IsChecked.Value, frequency >= BarSize.OneDay); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } } sw.Stop(); MessageBox.Show(string.Format("Imported {0} bars in {1} ms.", barsCount, sw.ElapsedMilliseconds)); }
public MyStringId GetRandomTransitionEnum() { return(m_musicTransitionCues.Keys.ElementAt(MyUtils.GetRandomInt(m_musicTransitionCues.Count))); }
public override void RecreateControls(bool constructor) { base.RecreateControls(constructor); CloseButtonEnabled = true; var caption = AddCaption(MyCommonTexts.ScreenCaptionPlayers); var captionCenter = MyUtils.GetCoordCenterFromAligned(caption.Position, caption.Size, caption.OriginAlign); var captionBottomCenter = captionCenter + new Vector2(0f, 0.5f * caption.Size.Y); Vector2 sizeScale = Size.Value / MyGuiConstants.TEXTURE_SCREEN_BACKGROUND.SizeGui; Vector2 topLeft = -0.5f * Size.Value + sizeScale * MyGuiConstants.TEXTURE_SCREEN_BACKGROUND.PaddingSizeGui * 1.1f; float verticalSpacing = 0.0045f; m_lobbyTypeCombo = new MyGuiControlCombobox( position: new Vector2(-topLeft.X, captionBottomCenter.Y + verticalSpacing), openAreaItemsCount: 3); m_lobbyTypeCombo.OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_TOP; m_lobbyTypeCombo.AddItem((int)LobbyTypeEnum.Private, MyCommonTexts.ScreenPlayersLobby_Private); m_lobbyTypeCombo.AddItem((int)LobbyTypeEnum.FriendsOnly, MyCommonTexts.ScreenPlayersLobby_Friends); m_lobbyTypeCombo.AddItem((int)LobbyTypeEnum.Public, MyCommonTexts.ScreenPlayersLobby_Public); m_lobbyTypeCombo.SelectItemByKey((int)MyMultiplayer.Static.GetLobbyType()); MyGuiControlBase aboveControl; m_inviteButton = new MyGuiControlButton( position: new Vector2(-m_lobbyTypeCombo.Position.X, m_lobbyTypeCombo.Position.Y + m_lobbyTypeCombo.Size.Y + verticalSpacing), originAlign: MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, text: MyTexts.Get(MyCommonTexts.ScreenPlayers_Invite)); aboveControl = m_inviteButton; m_promoteButton = new MyGuiControlButton( position: aboveControl.Position + new Vector2(0f, aboveControl.Size.Y + verticalSpacing), originAlign: MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, text: MyTexts.Get(MyCommonTexts.ScreenPlayers_Promote)); aboveControl = m_promoteButton; m_demoteButton = new MyGuiControlButton( position: aboveControl.Position + new Vector2(0f, aboveControl.Size.Y + verticalSpacing), originAlign: MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, text: MyTexts.Get(MyCommonTexts.ScreenPlayers_Demote)); aboveControl = m_demoteButton; m_kickButton = new MyGuiControlButton( position: aboveControl.Position + new Vector2(0f, aboveControl.Size.Y + verticalSpacing), originAlign: MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, text: MyTexts.Get(MyCommonTexts.ScreenPlayers_Kick)); aboveControl = m_kickButton; m_banButton = new MyGuiControlButton( position: aboveControl.Position + new Vector2(0f, aboveControl.Size.Y + verticalSpacing), originAlign: MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, text: MyTexts.Get(MyCommonTexts.ScreenPlayers_Ban)); aboveControl = m_banButton; var maxPlayersLabel = new MyGuiControlLabel( position: aboveControl.Position + new Vector2(0f, aboveControl.Size.Y + verticalSpacing), originAlign: MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, text: MyTexts.GetString(MyCommonTexts.MaxPlayers)); aboveControl = maxPlayersLabel; m_maxPlayersSlider = new MyGuiControlSlider( position: aboveControl.Position + new Vector2(0f, aboveControl.Size.Y), width: 0.15f, originAlign: MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, minValue: 2, maxValue: MyMultiplayer.Static != null ? MyMultiplayer.Static.MaxPlayers : 16, labelText: new StringBuilder("{0}").ToString(), labelDecimalPlaces: 0, labelSpaceWidth: 0.02f, defaultValue: Sync.IsServer ? MySession.Static.MaxPlayers : MyMultiplayer.Static.MemberLimit, intValue: true); m_maxPlayersSlider.ValueChanged = MaxPlayersSlider_Changed; aboveControl = m_maxPlayersSlider; m_playersTable = new MyGuiControlTable() { Position = new Vector2(-m_inviteButton.Position.X, m_inviteButton.Position.Y), Size = new Vector2(1200f / MyGuiConstants.GUI_OPTIMAL_SIZE.X, 1f) - m_inviteButton.Size * 1.05f, VisibleRowsCount = 21, OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_TOP, ColumnsCount = 5, }; float PlayerNameWidth = 0.3f; float FactionTagWidth = 0.12f; float FactionNameWidth = MyPerGameSettings.EnableMutePlayer ? 0.3f : 0.34f; float MutedWidth = MyPerGameSettings.EnableMutePlayer ? 0.13f : 0; m_playersTable.SetCustomColumnWidths(new float[] { PlayerNameWidth, FactionTagWidth, FactionNameWidth, MutedWidth, 1 - PlayerNameWidth - FactionTagWidth - FactionNameWidth - MutedWidth }); m_playersTable.SetColumnName(PlayerNameColumn, MyTexts.Get(MyCommonTexts.ScreenPlayers_PlayerName)); m_playersTable.SetColumnName(PlayerFactionTagColumn, MyTexts.Get(MyCommonTexts.ScreenPlayers_FactionTag)); m_playersTable.SetColumnName(PlayerFactionNameColumn, MyTexts.Get(MyCommonTexts.ScreenPlayers_FactionName)); m_playersTable.SetColumnName(PlayerMutedColumn, new StringBuilder(MyTexts.GetString(MyCommonTexts.ScreenPlayers_Muted))); m_playersTable.SetColumnName(GameAdminColumn, MyTexts.Get(MyCommonTexts.ScreenPlayers_GameAdmin)); m_playersTable.SetColumnComparison(0, (a, b) => (a.Text.CompareToIgnoreCase(b.Text))); m_playersTable.ItemSelected += playersTable_ItemSelected; // CH: To show the clients correctly, we would need to know, whether the game is a dedicated-server-hosted game. // We don't know that, so I just show all clients with players foreach (var player in Sync.Players.GetOnlinePlayers()) { if (player.Id.SerialId != 0) { continue; } for (int i = 0; i < m_playersTable.RowsCount; ++i) { var row = m_playersTable.GetRow(i); if (row.UserData is ulong && (ulong)row.UserData == player.Id.SteamId) { continue; } } AddPlayer(player.Id.SteamId); } m_inviteButton.ButtonClicked += inviteButton_ButtonClicked; m_promoteButton.ButtonClicked += promoteButton_ButtonClicked; m_demoteButton.ButtonClicked += demoteButton_ButtonClicked; m_kickButton.ButtonClicked += kickButton_ButtonClicked; m_banButton.ButtonClicked += banButton_ButtonClicked; m_lobbyTypeCombo.ItemSelected += lobbyTypeCombo_OnSelect; Controls.Add(m_inviteButton); Controls.Add(m_promoteButton); Controls.Add(m_demoteButton); Controls.Add(m_kickButton); Controls.Add(m_banButton); Controls.Add(m_playersTable); Controls.Add(m_lobbyTypeCombo); Controls.Add(m_maxPlayersSlider); Controls.Add(maxPlayersLabel); UpdateButtonsEnabledState(); }
public bool Intersects(ref BoundingSphereD localSphere) { MyPrecalcComponent.AssertUpdateThread(); // Get min and max cell coordinate where boundingBox can fit BoundingBoxD sphereBoundingBox = BoundingBoxD.CreateInvalid(); sphereBoundingBox.Include(ref localSphere); Vector3I cellCoordMin, cellCoordMax; { Vector3D minD = sphereBoundingBox.Min; Vector3D maxD = sphereBoundingBox.Max; MyVoxelCoordSystems.LocalPositionToGeometryCellCoord(ref minD, out cellCoordMin); MyVoxelCoordSystems.LocalPositionToGeometryCellCoord(ref maxD, out cellCoordMax); } // Fix min and max cell coordinates so they don't overlap the voxelmap ClampCellCoord(ref cellCoordMin); ClampCellCoord(ref cellCoordMax); MyCellCoord cell = new MyCellCoord(); for (cell.CoordInLod.X = cellCoordMin.X; cell.CoordInLod.X <= cellCoordMax.X; cell.CoordInLod.X++) { for (cell.CoordInLod.Y = cellCoordMin.Y; cell.CoordInLod.Y <= cellCoordMax.Y; cell.CoordInLod.Y++) { for (cell.CoordInLod.Z = cellCoordMin.Z; cell.CoordInLod.Z <= cellCoordMax.Z; cell.CoordInLod.Z++) { // If no overlap between bounding box of data cell and the sphere BoundingBox cellBoundingBox; MyVoxelCoordSystems.GeometryCellCoordToLocalAABB(ref cell.CoordInLod, out cellBoundingBox); if (cellBoundingBox.Intersects(ref localSphere) == false) { continue; } // Get cell from cache. If not there, precalc it and store in the cache. // If null is returned, we know that cell doesn't contain any triangleVertexes so we don't need to do intersections. CellData cachedData = GetCell(ref cell); if (cachedData == null) { continue; } for (int i = 0; i < cachedData.VoxelTrianglesCount; i++) { MyVoxelTriangle voxelTriangle = cachedData.VoxelTriangles[i]; MyTriangle_Vertexes triangle; cachedData.GetUnpackedPosition(voxelTriangle.VertexIndex0, out triangle.Vertex0); cachedData.GetUnpackedPosition(voxelTriangle.VertexIndex1, out triangle.Vertex1); cachedData.GetUnpackedPosition(voxelTriangle.VertexIndex2, out triangle.Vertex2); BoundingBox localTriangleAABB = BoundingBox.CreateInvalid(); localTriangleAABB.Include(ref triangle.Vertex0); localTriangleAABB.Include(ref triangle.Vertex1); localTriangleAABB.Include(ref triangle.Vertex2); // First test intersection of triangle's bounding box with line's bounding box. And only if they overlap or intersect, do further intersection tests. if (localTriangleAABB.Intersects(ref localSphere)) { PlaneD trianglePlane = new PlaneD(triangle.Vertex0, triangle.Vertex1, triangle.Vertex2); if (MyUtils.GetSphereTriangleIntersection(ref localSphere, ref trianglePlane, ref triangle) != null) { // If intersection found - we are finished. We don't need to look for more. return(true); } } } } } } return(false); }
public static void SpawnCargoShip(bool checkGravity) { Init( ); Wrapper.GameAction(() => { if (ExtenderOptions.IsDebugging) { Essentials.Log.Info("Spawn cargo ship"); } // Select a spawn group to spawn MySpawnGroupDefinition spawnGroup = PickRandomSpawnGroup( ); if (spawnGroup == null) { return; } spawnGroup.ReloadPrefabs( ); double spawnDistance = NEUTRAL_SHIP_SPAWN_DISTANCE; Vector3D playerPosition = Vector3D.Zero; bool isWorldLimited = MyEntities.IsWorldLimited( ); int numPlayers = 0; if (isWorldLimited) { spawnDistance = Math.Min(spawnDistance, MyEntities.WorldSafeHalfExtent( ) - spawnGroup.SpawnRadius); } else { // In infinite worlds players can be thousands of kilometers away, so spawn ship around random player // so cargo ships will be spawned around every player at some time var players = MySession.Static.Players.GetOnlinePlayers( ); // In DS there can be no players connected numPlayers = Math.Max(0, players.Count - 1); int randomPlayerPosition = MyUtils.GetRandomInt(0, numPlayers); int i = 0; foreach (var player in players) { if (i == randomPlayerPosition) { if (player.Character != null) { playerPosition = player.GetPosition( ); } break; } i++; } } if (spawnDistance < 0.0f) { if (ExtenderOptions.IsDebugging) { Essentials.Log.Info("Not enough space in the world to spawn such a huge spawn group!"); } return; } double forbiddenRadius = NEUTRAL_SHIP_FORBIDDEN_RADIUS; BoundingBoxD spawnBox; if (isWorldLimited) { spawnBox = new BoundingBoxD(new Vector3D(playerPosition - spawnDistance), new Vector3D(playerPosition + spawnDistance)); } else { // We need to extend bouding box so cargo ships aren't spawned near other players GetSafeBoundingBoxForPlayers(playerPosition, spawnDistance, out spawnBox); // Forbidden radius is sphere around all players in box. // Bounding box is generated from players positions so their distance to center shall be same for all players forbiddenRadius += spawnBox.HalfExtents.Max( ) - NEUTRAL_SHIP_FORBIDDEN_RADIUS; } // Get the direction to the center and deviate it randomly Vector3D?origin = MyUtils.GetRandomBorderPosition(ref spawnBox); origin = MyEntities.FindFreePlace(origin.Value, spawnGroup.SpawnRadius); if (!origin.HasValue) { if (ExtenderOptions.IsDebugging) { Essentials.Log.Info("Couldn't find free place for cargo spawn"); } return; } // Radius in arc units of the forbidden sphere in the center, when viewed from origin float centerArcRadius = (float)Math.Atan(forbiddenRadius / (origin.Value - spawnBox.Center).Length( )); // Generate direction with elevation from centerArcRadius radians to (cAR + N_S_D_S) radians Vector3D direction = -Vector3D.Normalize(origin.Value); float theta = MyUtils.GetRandomFloat(centerArcRadius, centerArcRadius + NEUTRAL_SHIP_DIRECTION_SPREAD); float phi = MyUtils.GetRandomRadian( ); Vector3D cosVec = Vector3D.CalculatePerpendicularVector(direction); Vector3D sinVec = Vector3D.Cross(direction, cosVec); cosVec *= (Math.Sin(theta) * Math.Cos(phi)); sinVec *= (Math.Sin(theta) * Math.Sin(phi)); direction = direction * Math.Cos(theta) + cosVec + sinVec; Vector3D destination = Vector3D.Zero; RayD ray = new RayD(origin.Value, direction); double?intersection = ray.Intersects(spawnBox); Vector3D directionMult; if (!intersection.HasValue || intersection.Value < NEUTRAL_SHIP_MINIMAL_ROUTE_LENGTH) { directionMult = direction * NEUTRAL_SHIP_MINIMAL_ROUTE_LENGTH; } else { directionMult = direction * intersection.Value; } destination = origin.Value + directionMult; Vector3D upVector = Vector3D.CalculatePerpendicularVector(direction); Vector3D rightVector = Vector3D.Cross(direction, upVector); MatrixD originMatrix = MatrixD.CreateWorld(origin.Value, direction, upVector); // CH:TODO: Convex cast to detect collision // Check ships' path to avoid possible collisions. (TODO: But only if it is said in the definitions) m_raycastHits.Clear( ); foreach (var shipPrefab in spawnGroup.Prefabs) { var prefabDef = MyDefinitionManager.Static.GetPrefabDefinition(shipPrefab.SubtypeId); Debug.Assert(prefabDef != null); Vector3D shipPosition = Vector3.Transform(shipPrefab.Position, originMatrix); Vector3D shipDestination = shipPosition + directionMult; float radius = prefabDef == null ? 10.0f : prefabDef.BoundingSphere.Radius; if (checkGravity) { //these point checks could be done in the trajectory intersect, but checking points is faster than ray intersect if (MyGravityProviderSystem.IsPositionInNaturalGravity(shipPosition, spawnGroup.SpawnRadius)) { if (ExtenderOptions.IsDebugging) { Essentials.Log.Info("Failed to spawn cargo ship: Spawn location is in gravity well"); } return; } if (MyGravityProviderSystem.IsPositionInNaturalGravity(shipDestination, spawnGroup.SpawnRadius)) { if (ExtenderOptions.IsDebugging) { Essentials.Log.Info("Failed to spawn cargo ship: Destination is in gravity well"); } } if (MyGravityProviderSystem.DoesTrajectoryIntersectNaturalGravity(shipPosition, shipDestination, spawnGroup.SpawnRadius + 500)) { if (ExtenderOptions.IsDebugging) { Essentials.Log.Info("Failed to spawn cargo ship: Ship path intersects gravity well"); } return; } } MyPhysics.CastRay(shipPosition, shipDestination, m_raycastHits, MyPhysics.CollisionLayers.ObjectDetectionCollisionLayer); if (m_raycastHits.Count > 0) { if (ExtenderOptions.IsDebugging) { Essentials.Log.Info("Failed to spawn cargo ship: Ship path intersects another object"); } return; } for (int i = 0; i < 4; ++i) { Vector3D shiftVector = upVector * m_upVecMultipliers[i] * radius + rightVector * m_rightVecMultipliers[i] * radius; MyPhysics.CastRay(shipPosition + shiftVector, shipDestination + shiftVector, m_raycastHits, MyPhysics.CollisionLayers.ObjectDetectionCollisionLayer); if (m_raycastHits.Count > 0) { if (ExtenderOptions.IsDebugging) { Essentials.Log.Info("Failed to spawn cargo ship: Ship path intersects another object"); } return; } } } long spawnGroupId = MyPirateAntennas.GetPiratesId( ); // The ships were collision-free. Now spawn them foreach (var shipPrefab in spawnGroup.Prefabs) { // Yes, this could have been saved in the previous loop, but compared to (e.g.) raycasts, this does not take too much time to recalculate Vector3D shipPosition = Vector3D.Transform((Vector3D)shipPrefab.Position, originMatrix); Vector3D shipDestination = shipPosition + directionMult; Vector3D up = Vector3D.CalculatePerpendicularVector(-direction); m_tmpGridList.Clear( ); // CH: We don't want a new identity for each ship anymore. We should handle that in a better way... /*if (shipPrefab.ResetOwnership) * { * if (spawnGroupId == 0) * { * //This is not an NPC so that it doesn't show up in assign ownership drop down menu * MyIdentity spawnGroupIdentity = Sync.Players.CreateNewIdentity("Neutral NPC"); * spawnGroupId = spawnGroupIdentity.IdentityId; * } * }*/ // Deploy ship MyPrefabManager.Static.SpawnPrefab( resultList: m_tmpGridList, prefabName: shipPrefab.SubtypeId, position: shipPosition, forward: direction, up: up, initialLinearVelocity: shipPrefab.Speed * direction, beaconName: shipPrefab.BeaconText, spawningOptions: VRage.Game.ModAPI.SpawningOptions.RotateFirstCockpitTowardsDirection | VRage.Game.ModAPI.SpawningOptions.SpawnRandomCargo | VRage.Game.ModAPI.SpawningOptions.DisableDampeners, ownerId: shipPrefab.ResetOwnership ? spawnGroupId : 0, updateSync: true); /* * foreach (var grid in m_tmpGridList) * { * var cockpit = grid.GetFirstBlockOfType<MyCockpit>(); * if (cockpit != null) * { * MySimpleAutopilot ai = new MySimpleAutopilot(shipDestination, (Vector3)direction); * cockpit.AttachAutopilot(ai); * break; * } * } */ m_tmpGridList.Clear( ); } }); }
void SendData(BarSize barSize) { foreach (KeyValuePair <RequestGrouping, ConcurrentDictionary <int, RealTimeDataRequest> > pair in _connectedRequests) { // @ToDo: Performance: if many entries exists in this list, this could be an performance issue. if (pair.Key.Frequency != barSize) { continue; } if (_connectedRequests.Count == 0) { continue; } int historicalRequestId; if (!_historicalRequests.TryGetValue(pair.Key, out historicalRequestId)) { continue; // the historical request is not made yet. } List <OHLCBar> historicalData; if (!_historicalData.TryGetValue(historicalRequestId, out historicalData)) { continue; // the historical data did not arrived yet. } List <int> requestsToDelete = new List <int>(); foreach (var pair2 in pair.Value) { // get the current position int indexPosition = 0; if (_requestPosition.TryGetValue(pair2.Key, out indexPosition)) { indexPosition++; } if (historicalData.Count <= indexPosition) { // end of historical data _logger.Log(LogLevel.Info, $"End of historical data for real time simulation - request ID: {pair2.Key}"); requestsToDelete.Add(pair2.Key); } else { var currentBar = historicalData[indexPosition]; RaiseEvent(DataReceived, this, new RealTimeDataEventArgs( pair2.Value.Instrument.ID.Value, MyUtils.ConvertToTimestamp(currentBar.DT), currentBar.Open, currentBar.High, currentBar.Low, currentBar.Close, currentBar.Volume ?? 0, 0, 0, pair2.Value.AssignedID )); if (indexPosition == 0) { _requestPosition.TryAdd(pair2.Key, indexPosition); } else { _requestPosition[pair2.Key] = indexPosition; } } } RealTimeDataRequest dummy; foreach (var i in requestsToDelete) { pair.Value.TryRemove(i, out dummy); } } }
public static void AddLineBillboard(string material, Vector4 color, Vector3D origin, int renderObjectID, ref MatrixD worldToLocal, Vector3 directionNormalized, float length, float thickness, int priority = 0, bool near = false, int customViewProjection = -1) { Debug.Assert(material != null); if (!IsEnabled) { return; } MyDebug.AssertIsValid(origin); MyDebug.AssertIsValid(length); MyDebug.AssertDebug(length > 0); MyDebug.AssertDebug(thickness > 0); //VRageRender.MyBillboard billboard = m_preallocatedBillboards.Allocate(); //VRageRender.MyBillboard billboard = new VRageRender.MyBillboard(); VRageRender.MyBillboard billboard = VRageRender.MyRenderProxy.BillboardsPoolWrite.Allocate(); if (billboard == null) { return; } billboard.Priority = priority; billboard.UVOffset = Vector2.Zero; billboard.UVSize = Vector2.One; MyPolyLineD polyLine; polyLine.LineDirectionNormalized = directionNormalized; polyLine.Point0 = origin; polyLine.Point1 = origin + directionNormalized * length; polyLine.Thickness = thickness; MyQuadD quad; Vector3D cameraPosition = customViewProjection == -1 ? MyTransparentGeometry.Camera.Translation : VRageRender.MyRenderProxy.BillboardsViewProjectionWrite[customViewProjection].CameraPosition; Vector3D cameraToPoly = cameraPosition - polyLine.Point0; if (Vector3D.IsZero(cameraToPoly, 1e-6)) { return; } MyUtils.GetPolyLineQuad(out quad, ref polyLine, cameraPosition); CreateBillboard(billboard, ref quad, material, ref color, ref origin, false, near, false, customViewProjection); if (renderObjectID != -1) { Vector3D.Transform(ref billboard.Position0, ref worldToLocal, out billboard.Position0); Vector3D.Transform(ref billboard.Position1, ref worldToLocal, out billboard.Position1); Vector3D.Transform(ref billboard.Position2, ref worldToLocal, out billboard.Position2); Vector3D.Transform(ref billboard.Position3, ref worldToLocal, out billboard.Position3); billboard.ParentID = renderObjectID; } billboard.Position0.AssertIsValid(); billboard.Position1.AssertIsValid(); billboard.Position2.AssertIsValid(); billboard.Position3.AssertIsValid(); VRageRender.MyRenderProxy.AddBillboard(billboard); }
public MyLargeGatlingBarrel() { m_rotationTimeout = (float)MyGatlingConstants.ROTATION_TIMEOUT + MyUtils.GetRandomFloat(-500, +500); }
/// <summary> /// 发送通知邮件 /// </summary> /// <param name="billId"></param> /// <param name="opType"></param> private void SendNotifyEmail(int billId, string opType) { var dr = new DRSv().GetDRBill(billId); if (dr == null) { return; } string subject, content, emailAddr, accountName; var currentCompany = MyUtils.GetCurrentCompany(dr.account); accountName = currentCompany == null ? "" : currentCompany.accountName; switch (opType) { case "提交": emailAddr = GetMatOrderEmail(dr); subject = "你有一张待审核的供应商送货申请单"; content = "<div style='font-family:Microsoft YaHei'><div>你好:</div>"; content += "<div style='margin-left:30px;'>"; content += string.Format("你有一张待处理的单号为【{0}】的送货申请单,来自【{3}】,供应商【{1}({2})】。请尽快登录平台处理。", dr.bill_no, dr.supplier_name, dr.supplier_number, accountName); content += "</div>"; content += "<div style='clear:both'><br />单击以下链接可进入平台处理这张申请单:</div>"; content += string.Format("<div><a href='{0}{1}{2}' style='color:#337ab7;text-decoration:none;'>内网用户请点击此链接</a></div>", innerWebSite, "Delivery/ConfirmApply?billId=", billId); content += string.Format("<div><a href='{0}{1}{2}' style='color:#337ab7;text-decoration:none;'>外网用户请点击此链接</a></div>", outerWebSite, "Delivery/ConfirmApply?billId=", billId); content += "</div>"; break; case "确认": case "拒绝": case "反审核": emailAddr = getSupplierEmail(dr); subject = "你有一张送货申请单已被订料员" + opType; content = "<div style='font-family:Microsoft YaHei'><div>你好:</div>"; content += "<div style='margin-left:30px;'>"; content += string.Format("你有一张单号为【{0}】的送货申请单已被{1}{2},来自【{3}】", dr.bill_no, dr.mat_order_name, opType, accountName); content += "</div>"; content += "<div style='clear:both'><br />单击以下链接可进入平台查看申请单详情:</div>"; content += string.Format("<div><a href='{0}{1}{2}' style='color:#337ab7;text-decoration:none;'>请点击此链接查看详情</a></div>", outerWebSite, "Delivery/CheckDRApply?id=", billId); content += "</div>"; break; case "撤销": emailAddr = GetMatOrderEmail(dr); subject = "供应商撤销了一张送货申请单"; content = "<div style='font-family:Microsoft YaHei'><div>你好:</div>"; content += "<div style='margin-left:30px;'>"; content += string.Format("单号为【{0}】的送货申请单已被供应商撤销,来自【{3}】,供应商【{1}({2})】。", dr.bill_no, dr.supplier_name, dr.supplier_number, accountName); content += "</div>"; content += "<div style='clear:both'><br />单击以下链接可进入平台查看申请单详情:</div>"; content += string.Format("<div><a href='{0}{1}{2}' style='color:#337ab7;text-decoration:none;'>内网用户请点击此链接</a></div>", innerWebSite, "Delivery/CheckDRApply?id=", billId); content += string.Format("<div><a href='{0}{1}{2}' style='color:#337ab7;text-decoration:none;'>外网用户请点击此链接</a></div>", outerWebSite, "Delivery/CheckDRApply?id=", billId); content += "</div>"; break; default: return; } WLog("发送通知邮件", opType, dr.bill_no); MyEmail.SendEmail(subject, emailAddr, content); }
//todo move it to session repostitory? private void Modify() { //ensure sessions don't overlap if (!MyUtils.ValidateSessions(TheSessionTemplate.Sessions.ToList(), out List <string> error)) { MessageBox.Show(error.First()); return; } //save to db var nameExists = DbContext.SessionTemplates.Any(x => x.Name == TheSessionTemplate.Name); var addingNew = TheSessionTemplate.ID == -1; if (nameExists && (addingNew || originalTemplate.Name != TheSessionTemplate.Name)) { MessageBox.Show("Name already exists, please change it."); return; } if (addingNew) { DbContext.SessionTemplates.Add(TheSessionTemplate); } else { DbContext.SessionTemplates.Attach(originalTemplate); DbContext.Entry(originalTemplate).CurrentValues.SetValues(TheSessionTemplate); } DbContext.SaveChanges(); //find removed sessions and mark them as deleted if (originalTemplate != null) { var removedSessions = originalTemplate.Sessions.Where(x => TheSessionTemplate.Sessions.All(y => y.ID != x.ID)) .ToList(); foreach (var t in removedSessions) { DbContext.Entry(t).State = EntityState.Deleted; } //find the ones that overlap and modify them, if not add them foreach (var s in TheSessionTemplate.Sessions) { if (s.ID != 0) //this means it's not newly added { var session = originalTemplate.Sessions.First(x => x.ID == s.ID); DbContext.TemplateSessions.Attach(session); DbContext.Entry(session).CurrentValues.SetValues(s); } } } DbContext.SaveChanges(); //find instruments using this exchange as session source, and update their sessions if (TheSessionTemplate.ID != -1) { var instruments = DbContext.Instruments.Where( x => x.SessionsSource == SessionsSource.Template && x.ExchangeID == TheSessionTemplate.ID) .ToList(); foreach (var i in instruments) { DbContext.InstrumentSessions.RemoveRange(i.Sessions); i.Sessions.Clear(); foreach (var s in TheSessionTemplate.Sessions) { i.Sessions.Add(s.ToInstrumentSession()); } } } DbContext.SaveChanges(); SessionAddedRemovedOrChanged = true; }
public MyTomasInputComponent() { AddShortcut(MyKeys.Delete, true, true, false, false, () => "Delete all characters", delegate { foreach (var obj in MyEntities.GetEntities().OfType <MyCharacter>()) { if (obj == MySession.Static.ControlledEntity) { MySession.Static.SetCameraController(MyCameraControllerEnum.Spectator); } obj.Close(); } foreach (var obj in MyEntities.GetEntities().OfType <MyCubeGrid>()) { foreach (var obj2 in obj.GetBlocks()) { if (obj2.FatBlock is MyCockpit) { var cockpit = obj2.FatBlock as MyCockpit; if (cockpit.Pilot != null) { cockpit.Pilot.Close(); } } } } return(true); }); AddShortcut(MyKeys.NumPad4, true, false, false, false, () => "Spawn cargo ship or barbarians", delegate { var theEvent = MyGlobalEvents.GetEventById(new MyDefinitionId(typeof(MyObjectBuilder_GlobalEventBase), "SpawnCargoShip")); if (theEvent == null) { theEvent = MyGlobalEvents.GetEventById(new MyDefinitionId(typeof(MyObjectBuilder_GlobalEventBase), "SpawnBarbarians")); } if (theEvent != null) { MyGlobalEvents.RemoveGlobalEvent(theEvent); theEvent.SetActivationTime(TimeSpan.FromSeconds(1)); MyGlobalEvents.AddGlobalEvent(theEvent); } return(true); }); AddShortcut(MyKeys.NumPad5, true, false, false, false, () => "Spawn random meteor", delegate { var camera = MySector.MainCamera; var target = camera.Position + MySector.MainCamera.ForwardVector * 20.0f; var spawnPosition = target + MySector.DirectionToSunNormalized * 1000.0f; if (MyUtils.GetRandomFloat(0.0f, 1.0f) < 0.2f) { MyMeteor.SpawnRandomLarge(spawnPosition, -MySector.DirectionToSunNormalized); } else { MyMeteor.SpawnRandomSmall(spawnPosition, -MySector.DirectionToSunNormalized); } return(true); }); AddShortcut(MyKeys.NumPad8, true, false, false, false, () => "Switch control to next entity", delegate { if (MySession.Static.ControlledEntity != null) { //we already are controlling this object var cameraController = MySession.Static.GetCameraControllerEnum(); if (cameraController != MyCameraControllerEnum.Entity && cameraController != MyCameraControllerEnum.ThirdPersonSpectator) { MySession.Static.SetCameraController(MyCameraControllerEnum.Entity, MySession.Static.ControlledEntity.Entity); } else { var entities = MyEntities.GetEntities().ToList(); int lastKnownIndex = entities.IndexOf(MySession.Static.ControlledEntity.Entity); var entitiesList = new List <MyEntity>(); if (lastKnownIndex + 1 < entities.Count) { entitiesList.AddRange(entities.GetRange(lastKnownIndex + 1, entities.Count - lastKnownIndex - 1)); } if (lastKnownIndex != -1) { entitiesList.AddRange(entities.GetRange(0, lastKnownIndex + 1)); } MyCharacter newControlledObject = null; for (int i = 0; i < entitiesList.Count; i++) { var character = entitiesList[i] as MyCharacter; if (character != null) { newControlledObject = character; break; } } if (newControlledObject != null) { MySession.Static.LocalHumanPlayer.Controller.TakeControl(newControlledObject); } } } return(true); }); AddShortcut(MyKeys.NumPad7, true, false, false, false, () => "Use next ship", delegate { MyCharacterInputComponent.UseNextShip(); return(true); }); AddShortcut(MyKeys.NumPad9, true, false, false, false, () => "Debug new grid screen", delegate { MyGuiSandbox.AddScreen(new DebugNewGridScreen()); return(true); }); AddShortcut(MyKeys.N, true, false, false, false, () => "Refill all batteries", delegate { foreach (var entity in MyEntities.GetEntities()) { MyCubeGrid grid = entity as MyCubeGrid; if (grid != null) { foreach (var block in grid.GetBlocks()) { MyBatteryBlock battery = block.FatBlock as MyBatteryBlock; if (battery != null) { battery.CurrentStoredPower = battery.MaxStoredPower; } } } } return(true); }); AddShortcut(MyKeys.U, true, false, false, false, () => "Spawn new character", delegate { var character = MyCharacterInputComponent.SpawnCharacter(); return(true); }); AddShortcut(MyKeys.NumPad2, true, false, false, false, () => "Merge static grids", delegate { // Try to merge all static large grids HashSet <MyCubeGrid> ignoredGrids = new HashSet <MyCubeGrid>(); while (true) { // Flag that we need new entities enumeration bool needNewEntitites = false; foreach (var entity in MyEntities.GetEntities()) { MyCubeGrid grid = entity as MyCubeGrid; if (grid != null && grid.IsStatic && grid.GridSizeEnum == MyCubeSize.Large) { if (ignoredGrids.Contains(grid)) { continue; } List <MySlimBlock> blocks = grid.GetBlocks().ToList(); foreach (var block in blocks) { var mergedGrid = grid.DetectMerge(block); if (mergedGrid == null) { continue; } needNewEntitites = true; // Grid merged to other grid? Then break and loop all entities again. if (mergedGrid != grid) { break; } } if (!needNewEntitites) { ignoredGrids.Add(grid); } } if (needNewEntitites) { break; } } if (!needNewEntitites) { break; } } return(true); }); AddShortcut(MyKeys.Add, true, false, false, false, () => "Increase wheel animation speed", delegate { USE_WHEEL_ANIMATION_SPEED += 0.05f; return(true); }); AddShortcut(MyKeys.Subtract, true, false, false, false, () => "Decrease wheel animation speed", delegate { USE_WHEEL_ANIMATION_SPEED -= 0.05f; return(true); }); AddShortcut(MyKeys.Divide, true, false, false, false, () => "Show model texture names", delegate { MyFakes.ENABLE_DEBUG_DRAW_TEXTURE_NAMES = !MyFakes.ENABLE_DEBUG_DRAW_TEXTURE_NAMES; return(true); }); AddShortcut(MyKeys.NumPad1, true, false, false, false, () => "Throw from spectator: " + Sandbox.Game.Components.MySessionComponentThrower.USE_SPECTATOR_FOR_THROW, delegate { Sandbox.Game.Components.MySessionComponentThrower.USE_SPECTATOR_FOR_THROW = !Sandbox.Game.Components.MySessionComponentThrower.USE_SPECTATOR_FOR_THROW; return(true); }); AddShortcut(MyKeys.F2, true, false, false, false, () => "Spectator to next small grid", () => SpectatorToNextGrid(MyCubeSize.Small)); AddShortcut(MyKeys.F3, true, false, false, false, () => "Spectator to next large grid", () => SpectatorToNextGrid(MyCubeSize.Large)); AddShortcut(MyKeys.Multiply, true, false, false, false, () => "Show model texture names", CopyAssetToClipboard ); }
private void DrawJetpackThrusts(bool updateCalled) { MyCharacter character = m_skinnedEntity as MyCharacter; if (character == null || character.GetCurrentMovementState() == MyCharacterMovementEnum.Died) { return; } var jetpack = character.JetpackComp; if (jetpack == null || !jetpack.CanDrawThrusts) { return; } var thrustComponent = Container.Get <MyEntityThrustComponent>(); if (thrustComponent == null) { return; } //VRageRender.MyRenderProxy.DebugDrawLine3D(WorldMatrix.Translation, WorldMatrix.Translation + Physics.LinearAcceleration, Color.White, Color.Green, false); var worldToLocal = MatrixD.Invert(Container.Entity.PositionComp.WorldMatrix); foreach (MyJetpackThrust thrust in m_jetpackThrusts) { Vector3D position = Vector3D.Zero; if ((jetpack.TurnedOn && jetpack.IsPowered) && (!character.IsInFirstPersonView || character != MySession.Static.LocalCharacter)) { var thrustMatrix = (MatrixD)thrust.ThrustMatrix * Container.Entity.PositionComp.WorldMatrix; Vector3D forward = Vector3D.TransformNormal(thrust.Forward, thrustMatrix); position = thrustMatrix.Translation; position += forward * thrust.Offset; float flameScale = 0.05f; if (updateCalled) { thrust.ThrustRadius = MyUtils.GetRandomFloat(0.9f, 1.1f) * flameScale; } float strength = Vector3.Dot(forward, -Vector3.Transform(thrustComponent.FinalThrust, Entity.WorldMatrix.GetOrientation()) / Entity.Physics.Mass); strength = MathHelper.Clamp(strength * 0.09f, 0.1f, 1f); if (strength > 0 && thrust.ThrustRadius > 0) { float angle = 1 - Math.Abs(Vector3.Dot(MyUtils.Normalize(MySector.MainCamera.Position - position), forward)); float alphaCone = (1 - (float)Math.Pow(1 - angle, 30)) * 0.5f; if (updateCalled) { thrust.ThrustLength = strength * 10 * MyUtils.GetRandomFloat(0.6f, 1.0f) * flameScale; thrust.ThrustThickness = MyUtils.GetRandomFloat(thrust.ThrustRadius * 0.90f, thrust.ThrustRadius); } // We move polyline particle backward, because we are stretching ball texture and it doesn't look good if stretched. This will hide it. MyTransparentGeometry.AddLineBillboard(thrust.ThrustMaterial, thrust.Light.Color * alphaCone * strength, position, GetRenderObjectID(), ref worldToLocal, forward, thrust.ThrustLength, thrust.ThrustThickness, MyBillboard.BlenType.AdditiveBottom); } if (thrust.ThrustRadius > 0) { MyTransparentGeometry.AddPointBillboard(thrust.ThrustMaterial, thrust.Light.Color, position, GetRenderObjectID(), ref worldToLocal, thrust.ThrustRadius, 0, -1, MyBillboard.BlenType.AdditiveBottom); } } else { if (updateCalled || (character.IsUsing != null)) { thrust.ThrustRadius = 0; } } if (thrust.Light != null) { if (thrust.ThrustRadius > 0) { thrust.Light.LightOn = true; thrust.Light.Intensity = JETPACK_LIGHT_INTENSITY_BASE + thrust.ThrustLength * JETPACK_LIGHT_INTENSITY_LENGTH; thrust.Light.Range = thrust.ThrustRadius * JETPACK_LIGHT_RANGE_RADIUS + thrust.ThrustLength * JETPACK_LIGHT_RANGE_LENGTH; thrust.Light.Position = Vector3D.Transform(position, MatrixD.Invert(Container.Entity.PositionComp.WorldMatrix)); thrust.Light.ParentID = GetRenderObjectID(); thrust.Light.GlareOn = true; thrust.Light.GlareIntensity = JETPACK_GLARE_INTENSITY_BASE + thrust.ThrustLength * JETPACK_GLARE_INTENSITY_LENGTH; thrust.Light.GlareMaterial = "GlareJetpack"; thrust.Light.GlareType = VRageRender.Lights.MyGlareTypeEnum.Normal; thrust.Light.GlareSize = (thrust.ThrustRadius * JETPACK_GLARE_SIZE_RADIUS + thrust.ThrustLength * JETPACK_GLARE_SIZE_LENGTH) * thrust.ThrustGlareSize; thrust.Light.GlareQuerySize = 0.1f; thrust.Light.UpdateLight(); } else { thrust.Light.GlareOn = false; thrust.Light.LightOn = false; thrust.Light.UpdateLight(); } } } }
public override void Draw() { base.Draw(); var worldToLocal = MatrixD.Invert(Container.Entity.PositionComp.WorldMatrix); if (m_thrust.CanDraw()) { m_thrust.UpdateThrustFlame(); m_thrust.UpdateThrustColor(); foreach (var flame in m_thrust.Flames) { if (m_thrust.CubeGrid.Physics == null) { continue; } var flameDirection = Vector3D.TransformNormal(flame.Direction, Container.Entity.PositionComp.WorldMatrix); var flamePosition = Vector3D.Transform(flame.Position, Container.Entity.PositionComp.WorldMatrix); float radius = m_thrust.ThrustRadiusRand * flame.Radius; float length = m_thrust.ThrustLengthRand * flame.Radius; float thickness = m_thrust.ThrustThicknessRand * flame.Radius; Vector3D velocityAtNewCOM = Vector3D.Cross(m_thrust.CubeGrid.Physics.AngularVelocity, flamePosition - m_thrust.CubeGrid.Physics.CenterOfMassWorld); var velocity = m_thrust.CubeGrid.Physics.LinearVelocity + velocityAtNewCOM; if (m_thrust.CurrentStrength > 0 && length > 0) { float angle = 1 - Math.Abs(Vector3.Dot(MyUtils.Normalize(MySector.MainCamera.Position - flamePosition), flameDirection)); float alphaCone = (1 - (float)Math.Pow(1 - angle, 30)) * 0.5f; // We move polyline particle backward, because we are stretching ball texture and it doesn't look good if stretched. This will hide it. MyTransparentGeometry.AddLineBillboard(m_thrust.FlameLengthMaterial, m_thrust.ThrustColor * alphaCone, flamePosition - flameDirection * length * 0.25f, GetRenderObjectID(), ref worldToLocal, flameDirection, length, thickness); } if (radius > 0) { MyTransparentGeometry.AddPointBillboard(m_thrust.FlamePointMaterial, m_thrust.ThrustColor, flamePosition, GetRenderObjectID(), ref worldToLocal, radius, 0); } if (m_thrust.ThrustLengthRand > MyMathConstants.EPSILON && m_landingEffectUpdateCounter-- <= 0) { m_landingEffectUpdateCounter = (int)Math.Round(m_landingEffectUpdateInterval * (0.8f + MyRandom.Instance.NextFloat() * 0.4f)); m_lastHitInfo = MyPhysics.CastRay(flamePosition, flamePosition + flameDirection * m_thrust.ThrustLengthRand * (m_thrust.CubeGrid.GridSizeEnum == MyCubeSize.Large ? 5.0f : 3.0f) * flame.Radius, MyPhysics.CollisionLayers.DefaultCollisionLayer); } var voxelBase = m_lastHitInfo.HasValue ? m_lastHitInfo.Value.HkHitInfo.GetHitEntity() as MyVoxelPhysics : null; if (voxelBase == null) { if (m_landingEffect != null) { m_landingEffect.Stop(true); m_landingEffect = null; --m_landingEffectCount; } continue; } if (m_landingEffect == null && m_landingEffectCount < m_maxNumberLandingEffects && MyParticlesManager.TryCreateParticleEffect(54, out m_landingEffect)) { ++m_landingEffectCount; } if (m_landingEffect == null) { continue; } m_landingEffect.UserScale = m_thrust.CubeGrid.GridSize; m_landingEffect.WorldMatrix = MatrixD.CreateFromTransformScale(Quaternion.CreateFromForwardUp(-m_lastHitInfo.Value.HkHitInfo.Normal, Vector3.CalculatePerpendicularVector(m_lastHitInfo.Value.HkHitInfo.Normal)), m_lastHitInfo.Value.Position, Vector3D.One); } } else if (m_landingEffect != null) { m_landingEffect.Stop(true); m_landingEffect = null; --m_landingEffectCount; } if (m_thrust.Light != null) { m_thrust.UpdateLight(); } }
protected MyBehaviorTreeState RunAway([BTParam] float distance) { if (!runAwayPos.HasValue) { Vector3D currentPosition = Bot.Player.Character.PositionComp.GetPosition(); Vector3D planetGravityVec = MyGravityProviderSystem.CalculateNaturalGravityInPoint(currentPosition); var planet = MyGamePruningStructure.GetClosestPlanet(currentPosition); if (planet == null) { return(MyBehaviorTreeState.FAILURE); } if (lastTargetedEntityPosition.HasValue) { Vector3D lastTargetedEntityPositionProjected = lastTargetedEntityPosition.Value; lastTargetedEntityPositionProjected = planet.GetClosestSurfacePointGlobal(ref lastTargetedEntityPositionProjected); Vector3D direction = currentPosition - lastTargetedEntityPositionProjected; Vector3D runAwayPosCandidate = currentPosition + Vector3D.Normalize(direction) * distance; runAwayPos = planet.GetClosestSurfacePointGlobal(ref runAwayPosCandidate); } else { planetGravityVec.Normalize(); Vector3D planetTangent = Vector3D.CalculatePerpendicularVector(planetGravityVec); Vector3D planetBitangent = Vector3D.Cross(planetGravityVec, planetTangent); planetTangent.Normalize(); planetBitangent.Normalize(); Vector3D runAwayPosCandidate = MyUtils.GetRandomDiscPosition(ref currentPosition, distance, distance, ref planetTangent, ref planetBitangent); if (planet != null) { runAwayPos = planet.GetClosestSurfacePointGlobal(ref runAwayPosCandidate); } else { runAwayPos = runAwayPosCandidate; } } AiTargetBase.SetTargetPosition(runAwayPos.Value); AimWithMovement(); } else { if (Bot.Navigation.Stuck) { return(MyBehaviorTreeState.FAILURE); } } AiTargetBase.GotoTargetNoPath(1.0f, false); if (Vector3D.DistanceSquared(runAwayPos.Value, Bot.Player.Character.PositionComp.GetPosition()) < 10.0f * 10.0f) { CyberhoundLogic.Remove(); return(MyBehaviorTreeState.SUCCESS); } else { return(MyBehaviorTreeState.RUNNING); } }
private DataSet GetUsers(string sql,MyUtils.ImageSize sz=MyUtils.ImageSize.SMALL,bool deleterows=true) { DataSet d = db.GetDataSet(sql); MixInFeatured(d, deleterows); d.Tables[0].Columns.Add("mainphoto_"); d.Tables[0].Columns.Add("online"); foreach (DataRow r in d.Tables[0].Rows) { r["mainphoto_"] = MyUtils.GetImageUrl(r, sz); r["online"] = MyUtils.IsOnline((int)r["id_user"]) ? "1" : "0";// ..GetImageUrl(r, MyUtils.ImageSize.MEDIUM); } d.Tables[0].Columns.Remove("mainphoto"); d.Tables[0].Columns["mainphoto_"].ColumnName = "MainPhoto"; d.Tables[0].TableName = "U"; //DataTable t = new DataTable(); //t.TableName = "filter"; //t.Columns.Add("json"); //t.Rows.Add(t.NewRow()); //t.Rows[0]["json"] = f.ToString(); //d.Tables.Add(t); return d; }
private void RefreshGameList() { m_gamesTable.Clear(); AddHeaders(); m_textCache.Clear(); m_gameTypeText.Clear(); m_gameTypeToolTip.Clear(); m_lobbyPage.Text = MyTexts.Get(MySpaceTexts.JoinGame_TabTitle_Lobbies); if (m_lobbies != null) { int shownGames = 0; for (int i = 0; i < m_lobbies.Count; ++i) { var lobby = m_lobbies[i]; var row = new MyGuiControlTable.Row(lobby); string sessionName = MyMultiplayerLobby.GetLobbyWorldName(lobby); ulong sessionSize = MyMultiplayerLobby.GetLobbyWorldSize(lobby); int appVersion = MyMultiplayerLobby.GetLobbyAppVersion(lobby); int modCount = MyMultiplayerLobby.GetLobbyModCount(lobby); var searchName = m_blockSearch.Text.Trim(); if (!string.IsNullOrWhiteSpace(searchName) && !sessionName.ToLower().Contains(searchName.ToLower())) { continue; } m_gameTypeText.Clear(); m_gameTypeToolTip.Clear(); if (appVersion > 01022000) { var inventory = MyMultiplayerLobby.GetLobbyFloat(MyMultiplayer.InventoryMultiplierTag, lobby, 1); var refinery = MyMultiplayerLobby.GetLobbyFloat(MyMultiplayer.RefineryMultiplierTag, lobby, 1); var assembler = MyMultiplayerLobby.GetLobbyFloat(MyMultiplayer.AssemblerMultiplierTag, lobby, 1); MyGameModeEnum gameMode = MyMultiplayerLobby.GetLobbyGameMode(lobby); bool isBattle = MyMultiplayerLobby.GetLobbyBattle(lobby); switch (gameMode) { case MyGameModeEnum.Creative: m_gameTypeText.AppendStringBuilder(MyTexts.Get(MySpaceTexts.WorldSettings_GameModeCreative)); break; case MyGameModeEnum.Survival: if (MyFakes.ENABLE_BATTLE_SYSTEM && isBattle) { m_gameTypeText.AppendStringBuilder(MyTexts.Get(MySpaceTexts.WorldSettings_Battle)); } else { m_gameTypeText.AppendStringBuilder(MyTexts.Get(MySpaceTexts.WorldSettings_GameModeSurvival)); m_gameTypeText.Append(String.Format(" {0}-{1}-{2}", inventory, assembler, refinery)); } break; default: Debug.Fail("Unknown game type"); break; } m_gameTypeToolTip.AppendFormat(MyTexts.Get(MySpaceTexts.JoinGame_GameTypeToolTip_MultipliersFormat).ToString(), inventory, assembler, refinery); var viewDistance = MyMultiplayerLobby.GetLobbyViewDistance(lobby); m_gameTypeToolTip.AppendLine(); m_gameTypeToolTip.AppendFormat(MyTexts.Get(MySpaceTexts.JoinGame_GameTypeToolTip_ViewDistance).ToString(), viewDistance); } // Skip world without name (not fully initialized) if (string.IsNullOrEmpty(sessionName)) { continue; } // Show only same app versions if (m_showOnlyCompatibleGames.IsChecked && appVersion != MyFinalBuildConstants.APP_VERSION) { continue; } // Show only if the game data match if (m_showOnlyWithSameMods.IsChecked && MyFakes.ENABLE_MP_DATA_HASHES && !MyMultiplayerLobby.HasSameData(lobby)) { continue; } float sessionFormattedSize = (float)sessionSize; string owner = MyMultiplayerLobby.GetLobbyHostName(lobby); string limit = lobby.MemberLimit.ToString(); string userCount = lobby.MemberCount + "/" + limit; var prefixSize = MyUtils.FormatByteSizePrefix(ref sessionFormattedSize); var modListToolTip = new StringBuilder(); int displayedModsMax = 15; int lastMod = Math.Min(displayedModsMax, modCount - 1); foreach (var mod in MyMultiplayerLobby.GetLobbyMods(lobby)) { if (displayedModsMax-- <= 0) { modListToolTip.Append("..."); break; } if (lastMod-- <= 0) { modListToolTip.Append(mod.FriendlyName); } else { modListToolTip.AppendLine(mod.FriendlyName); } } //row.AddCell(new MyGuiControlTable.Cell(text: m_textCache.Clear().Append(MyMultiplayerLobby.HasSameData(lobby) ? "" : "*"))); row.AddCell(new MyGuiControlTable.Cell(text: m_textCache.Clear().Append(sessionName), userData: lobby.LobbyId, toolTip: m_textCache.ToString())); row.AddCell(new MyGuiControlTable.Cell(text: m_gameTypeText, toolTip: (m_gameTypeToolTip.Length > 0) ? m_gameTypeToolTip.ToString() : null)); row.AddCell(new MyGuiControlTable.Cell(text: new StringBuilder(sessionFormattedSize.ToString("0.") + prefixSize + "B "))); row.AddCell(new MyGuiControlTable.Cell(text: m_textCache.Clear().Append(owner), toolTip: m_textCache.ToString())); row.AddCell(new MyGuiControlTable.Cell(text: new StringBuilder(userCount))); row.AddCell(new MyGuiControlTable.Cell(text: m_textCache.Clear().Append(modCount == 0 ? "---" : modCount.ToString()), toolTip: modListToolTip.ToString())); m_gamesTable.Add(row); shownGames++; } m_lobbyPage.Text = new StringBuilder().Append(MyTexts.Get(MySpaceTexts.JoinGame_TabTitle_Lobbies).ToString()).Append(" (").Append(shownGames).Append(")"); } //m_gameDataLabel.Visible = m_incompatibleGameData; m_gamesTable.SelectedRowIndex = null; }