Exemple #1
0
        private TextureFlags GetFlags(GenericStructure vmt)
        {
            var flags = TextureFlags.None;
            var tp    = vmt.PropertyInteger("$translucent") + vmt.PropertyInteger("$alphatest");

            if (tp > 0)
            {
                flags |= TextureFlags.Transparent;
            }
            return(flags);
        }
Exemple #2
0
        private static Visgroup ReadVisgroup(GenericStructure visgroup)
        {
            var v = new Visgroup {
                Name    = visgroup["name"],
                ID      = visgroup.PropertyInteger("visgroupid"),
                Colour  = visgroup.PropertyColour("color", Colour.GetRandomBrushColour()),
                Visible = true
            };

            return(v);
        }
Exemple #3
0
        public void Write(GenericStructure gs)
        {
            gs["ID"]                                 = ID.ToString(CultureInfo.InvariantCulture);
            gs["Name"]                               = Name;
            gs["EngineID"]                           = Engine.ToString();
            gs["BuildID"]                            = BuildID.ToString(CultureInfo.InvariantCulture);
            gs["SteamInstall"]                       = SteamInstall.ToString(CultureInfo.InvariantCulture);
            gs["WonGameDir"]                         = WonGameDir;
            gs["SteamGameDir"]                       = SteamGameDir;
            gs["ModDir"]                             = ModDir;
            gs["UseHDModels"]                        = UseHDModels.ToString(CultureInfo.InvariantCulture);
            gs["BaseDir"]                            = BaseDir;
            gs["Executable"]                         = Executable;
            gs["ExecutableParameters"]               = ExecutableParameters;
            gs["MapDir"]                             = MapDir;
            gs["Autosave"]                           = Autosave.ToString(CultureInfo.InvariantCulture);
            gs["UseCustomAutosaveDir"]               = UseCustomAutosaveDir.ToString(CultureInfo.InvariantCulture);
            gs["AutosaveDir"]                        = AutosaveDir;
            gs["AutosaveTime"]                       = AutosaveTime.ToString(CultureInfo.InvariantCulture);
            gs["AutosaveLimit"]                      = AutosaveLimit.ToString(CultureInfo.InvariantCulture);
            gs["AutosaveOnlyOnChanged"]              = AutosaveOnlyOnChanged.ToString(CultureInfo.InvariantCulture);
            gs["AutosaveTriggerFileChange"]          = AutosaveTriggerFileSave.ToString(CultureInfo.InvariantCulture);
            gs["DefaultPointEntity"]                 = DefaultPointEntity;
            gs["DefaultBrushEntity"]                 = DefaultBrushEntity;
            gs["DefaultTextureScale"]                = DefaultTextureScale.ToString(CultureInfo.InvariantCulture);
            gs["DefaultLightmapScale"]               = DefaultLightmapScale.ToString(CultureInfo.InvariantCulture);
            gs["IncludeFgdDirectoriesInEnvironment"] = IncludeFgdDirectoriesInEnvironment.ToString(CultureInfo.InvariantCulture);
            gs["OverrideMapSize"]                    = OverrideMapSize.ToString(CultureInfo.InvariantCulture);
            gs["OverrideMapSizeLow"]                 = OverrideMapSizeLow.ToString(CultureInfo.InvariantCulture);
            gs["OverrideMapSizeHigh"]                = OverrideMapSizeHigh.ToString(CultureInfo.InvariantCulture);

            var additional = new GenericStructure("AdditionalPackages");
            var i          = 1;

            foreach (var add in AdditionalPackages)
            {
                additional.AddProperty(i.ToString(CultureInfo.InvariantCulture), add);
                i++;
            }
            gs.Children.Add(additional);

            gs["PackageBlacklist"] = (PackageBlacklist ?? "").Replace("\r", "").Replace('\n', ';');
            gs["PackageWhitelist"] = (PackageWhitelist ?? "").Replace("\r", "").Replace('\n', ';');

            var fgds = new GenericStructure("Fgds");

            i = 1;
            foreach (var fgd in Fgds)
            {
                fgds.AddProperty(i.ToString(CultureInfo.InvariantCulture), fgd.Path);
                i++;
            }
            gs.Children.Add(fgds);
        }
Exemple #4
0
        public static GenericStructure CreateCopyStream(List<MapObject> objects)
        {
            var stream = new GenericStructure("clipboard");

            var entitySolids = objects.OfType<Entity>().SelectMany(x => x.Find(y => y is Solid)).ToList();
            stream.Children.AddRange(objects.OfType<Solid>().Where(x => !x.IsCodeHidden && !x.IsVisgroupHidden && !entitySolids.Contains(x)).Select(WriteSolid));
            stream.Children.AddRange(objects.OfType<Group>().Select(WriteGroup));
            stream.Children.AddRange(objects.OfType<Entity>().Select(WriteEntity));

            return stream;
        }
Exemple #5
0
        public static GenericStructure CreateCopyStream(List <MapObject> objects)
        {
            var stream = new GenericStructure("clipboard");

            var entitySolids = objects.OfType <Entity>().SelectMany(x => x.Find(y => y is Solid)).ToList();

            stream.Children.AddRange(objects.OfType <Solid>().Where(x => !x.IsCodeHidden && !x.IsVisgroupHidden && !entitySolids.Contains(x)).Select(WriteSolid));
            stream.Children.AddRange(objects.OfType <Group>().Select(WriteGroup));
            stream.Children.AddRange(objects.OfType <Entity>().Select(WriteEntity));

            return(stream);
        }
Exemple #6
0
        private static GenericStructure WriteGroup(Group group)
        {
            var ret = new GenericStructure("group");

            ret["id"] = group.ID.ToString(CultureInfo.InvariantCulture);

            var editor = WriteEditor(group);

            ret.Children.Add(editor);

            return(ret);
        }
Exemple #7
0
        public static CompileSpecification Parse(GenericStructure gs)
        {
            var spec = new CompileSpecification {
                ID = gs["ID"] ?? "", Name = gs["Name"] ?? ""
            };
            var tools = gs.GetChildren("Tool");

            spec.Tools.AddRange(tools.Select(CompileTool.Parse));
            var presets = gs.GetChildren("Preset");

            spec.Presets.AddRange(presets.Select(CompilePreset.Parse));
            return(spec);
        }
Exemple #8
0
        public static T GetAdditionalData <T>(string key)
        {
            if (!AdditionalSettings.ContainsKey(key))
            {
                return(default(T));
            }
            var additional = AdditionalSettings[key];

            try {
                return(GenericStructure.Deserialise <T>(additional));
            } catch {
                return(default(T)); // Deserialisation failure
            }
        }
Exemple #9
0
        public static CompileTool Parse(GenericStructure gs)
        {
            var tool = new CompileTool
            {
                Name        = gs["Name"] ?? "",
                Description = gs["Description"] ?? "",
                Order       = gs.PropertyInteger("Order"),
                Enabled     = gs.PropertyBoolean("Enabled", true)
            };
            var parameters = gs.GetChildren("Parameter");

            tool.Parameters.AddRange(parameters.Select(CompileParameter.Parse));
            return(tool);
        }
Exemple #10
0
 private static IEnumerable <MapObject> ExtractCopyStream(Document document, string str)
 {
     using (var tr = new StringReader(str))
     {
         try
         {
             var gs = GenericStructure.Parse(tr);
             return(VmfProvider.ExtractCopyStream(gs.FirstOrDefault(), document.Map.IDGenerator));
         }
         catch
         {
             return(null);
         }
     }
 }
Exemple #11
0
        public void TestMapObjectSerialisation()
        {
            // compare the *'s:
            // brush -> GS -> string* -> GS -> brush -> GS -> string*

            var brush        = new BlockBrush();
            var b            = brush.Create(new IDGenerator(), new Box(Coordinate.Zero, Coordinate.One * 100), null, 0);
            var serialised   = GenericStructure.Serialise(b);
            var toString     = serialised.ToString();
            var parsed       = GenericStructure.Parse(new StringReader(toString));
            var deserialised = GenericStructure.Deserialise <List <MapObject> >(parsed.First());
            var reserialised = GenericStructure.Serialise(deserialised);

            Assert.AreEqual(serialised.ToString(), reserialised.ToString());
        }
        public void TestParseBasic()
        {
            var input =
                @"Test
                {
                    key value
                }";
            var parsed = GenericStructure.Parse(new StringReader(input)).First();

            Assert.AreEqual("Test", parsed.Name);
            CollectionAssert.AreEquivalent(new List <string> {
                "key"
            }, parsed.GetPropertyKeys().ToList());
            Assert.AreEqual("value", parsed["key"]);
        }
Exemple #13
0
 private static IEnumerable <MapObject> ExtractCopyStream(Document document, string str)
 {
     using (var tr = new StringReader(str))
     {
         try
         {
             var gs = GenericStructure.Parse(tr);
             return(VmfProvider.ExtractCopyStream(gs.FirstOrDefault(), document.Map.IDGenerator, document.Map.WorldSpawn.MetaData.Get <Dictionary <string, UInt32> >("EntityCounts")));
         }
         catch
         {
             return(null);
         }
     }
 }
Exemple #14
0
        private static EntityData ReadEntityData(GenericStructure structure)
        {
            var ret = new EntityData();

            foreach (var key in structure.GetPropertyKeys())
            {
                if (ExcludedKeys.Contains(key.ToLower()))
                {
                    continue;
                }
                ret.SetPropertyValue(key, structure[key]);
            }
            ret.Name  = structure["classname"];
            ret.Flags = structure.PropertyInteger("spawnflags");
            return(ret);
        }
Exemple #15
0
        public void TestPrimitiveSerialisation()
        {
            Assert.AreEqual(null, GenericStructure.Deserialise <object>(GenericStructure.Serialise(null)));
            Assert.AreEqual(new DateTime(2014, 01, 01), GenericStructure.Deserialise <DateTime>(GenericStructure.Serialise(new DateTime(2014, 01, 01))));
            Assert.AreEqual(10, GenericStructure.Deserialise <int>(GenericStructure.Serialise(10)));
            Assert.AreEqual(10m, GenericStructure.Deserialise <decimal>(GenericStructure.Serialise(10m)));
            Assert.AreEqual(false, GenericStructure.Deserialise <bool>(GenericStructure.Serialise(false)));
            Assert.AreEqual("12345", GenericStructure.Deserialise <string>(GenericStructure.Serialise("12345")));
            Assert.AreEqual(new Coordinate(123, 456, 789.0005m), GenericStructure.Deserialise <Coordinate>(GenericStructure.Serialise(new Coordinate(123, 456, 789.0005m))));
            var dsBox = GenericStructure.Deserialise <Box>(GenericStructure.Serialise(new Box(Coordinate.Zero, Coordinate.One)));

            Assert.AreEqual(Coordinate.Zero, dsBox.Start);
            Assert.AreEqual(Coordinate.One, dsBox.End);
            Assert.AreEqual(Color.FromArgb(255, 255, 0, 0), GenericStructure.Deserialise <Color>(GenericStructure.Serialise(Color.FromArgb(255, 255, 0, 0))));
            Assert.AreEqual(new Plane(Coordinate.UnitZ, 1), GenericStructure.Deserialise <Plane>(GenericStructure.Serialise(new Plane(Coordinate.UnitZ, 1))));
        }
Exemple #16
0
 public static CompilePreset Parse(GenericStructure gs)
 {
     return(new CompilePreset
     {
         Name = gs["Name"] ?? "",
         Description = gs["Description"] ?? "",
         Csg = gs["Csg"] ?? "",
         Bsp = gs["Bsp"] ?? "",
         Vis = gs["Vis"] ?? "",
         Rad = gs["Rad"] ?? "",
         RunCsg = gs.PropertyBoolean("RunCsg", true),
         RunBsp = gs.PropertyBoolean("RunBsp", true),
         RunVis = gs.PropertyBoolean("RunVis", true),
         RunRad = gs.PropertyBoolean("RunRad", true)
     });
 }
        public void TestParseQuotes()
        {
            var input =
                @"""Test Name""
                {
                    ""key"" ""value""
                    ""key with spaces"" ""value with spaces""
                }";
            var parsed = GenericStructure.Parse(new StringReader(input)).First();

            Assert.AreEqual("Test Name", parsed.Name);
            CollectionAssert.AreEquivalent(new List <string> {
                "key", "key with spaces"
            }, parsed.GetPropertyKeys().ToList());
            Assert.AreEqual("value", parsed["key"]);
            Assert.AreEqual("value with spaces", parsed["key with spaces"]);
        }
Exemple #18
0
 public static IEnumerable<MapObject> ExtractCopyStream(GenericStructure gs, IDGenerator generator)
 {
     if (gs == null || gs.Name != "clipboard") return null;
     var dummyGen = new IDGenerator();
     var list = new List<MapObject>();
     var world = ReadWorld(gs, dummyGen);
     foreach (var entity in gs.GetChildren("entity"))
     {
         var ent = ReadEntity(entity, dummyGen);
         var groupid = entity.Children.Where(x => x.Name == "editor").Select(x => x.PropertyInteger("groupid")).FirstOrDefault();
         var entParent = groupid > 0 ? world.Find(x => x.ID == groupid && x is Group).FirstOrDefault() ?? world : world;
         ent.SetParent(entParent);
     }
     list.AddRange(world.GetChildren());
     Reindex(list, generator);
     return list;
 }
Exemple #19
0
        private static GenericStructure ReadSettingsFile()
        {
            if (File.Exists(SettingsFile))
            {
                return(GenericStructure.Parse(SettingsFile).FirstOrDefault());
            }

            var exec = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var path = Path.Combine(exec, "Settings.vdf");

            if (File.Exists(path))
            {
                return(GenericStructure.Parse(path).FirstOrDefault());
            }

            return(null);
        }
Exemple #20
0
        private static Face ReadFace(GenericStructure side, IDGenerator generator)
        {
            var id = side.PropertyLong("id");

            if (id == 0)
            {
                id = generator.GetNextFaceID();
            }
            var dispinfo = side.GetChildren("dispinfo").FirstOrDefault();
            var ret      = dispinfo != null?ReadDisplacement(id, dispinfo) : new Face(id);

            // id, plane, material, uaxis, vaxis, rotation, lightmapscale, smoothing_groups
            var uaxis = side.PropertyTextureAxis("uaxis");
            var vaxis = side.PropertyTextureAxis("vaxis");

            ret.Texture.Name     = side["material"];
            ret.Texture.UAxis    = uaxis.Item1;
            ret.Texture.XShift   = uaxis.Item2;
            ret.Texture.XScale   = uaxis.Item3;
            ret.Texture.VAxis    = vaxis.Item1;
            ret.Texture.YShift   = vaxis.Item2;
            ret.Texture.YScale   = vaxis.Item3;
            ret.Texture.Rotation = side.PropertyDecimal("rotation");
            ret.Plane            = side.PropertyPlane("plane");
            //NOTE(SVK) Paste RF data
            ret.Texture.Flags            = (FaceFlags)side.PropertyInteger("flags");
            ret.Texture.Translucency     = (int)side.PropertyDecimal("translucency");
            ret.Texture.Opacity          = side.PropertyDecimal("opacity");
            ret.Texture.PositionRF       = side.PropertyCoordinate("positionrf");
            ret.Texture.TransformAngleRF = side.PropertyMatrix("transformanglerf");

            var verts = side.Children.FirstOrDefault(x => x.Name == "vertex");

            if (verts != null)
            {
                var count = verts.PropertyInteger("count");
                for (var i = 0; i < count; i++)
                {
                    ret.Vertices.Add(new Vertex(verts.PropertyCoordinate("vertex" + i), ret));
                }
            }

            return(ret);
        }
Exemple #21
0
        private static Entity ReadEntity(GenericStructure entity, IDGenerator generator)
        {
            var ret = new Entity(GetObjectID(entity, generator))
            {
                ClassName  = entity["classname"],
                EntityData = ReadEntityData(entity),
                Origin     = entity.PropertyCoordinate("origin")
            };
            var editor = entity.GetChildren("editor").FirstOrDefault() ?? new GenericStructure("editor");

            ret.Colour = editor.PropertyColour("color", Colour.GetRandomBrushColour());
            ret.Visgroups.AddRange(editor.GetAllPropertyValues("visgroupid").Select(int.Parse).Where(x => x > 0));
            foreach (var child in entity.GetChildren("solid").Select(solid => ReadSolid(solid, generator)).Where(s => s != null))
            {
                child.SetParent(ret, false);
            }
            ret.UpdateBoundingBox(false);
            return(ret);
        }
Exemple #22
0
        private static GenericStructure WriteFace(Face face)
        {
            var ret = new GenericStructure("side");

            ret["id"]    = face.ID.ToString(CultureInfo.InvariantCulture);
            ret["plane"] = String.Format("({0}) ({1}) ({2})",
                                         FormatCoordinate(face.Vertices[0].Location),
                                         FormatCoordinate(face.Vertices[1].Location),
                                         FormatCoordinate(face.Vertices[2].Location));
            ret["material"] = face.Texture.Name;
            ret["uaxis"]    = String.Format(CultureInfo.InvariantCulture, "[{0} {1}] {2}", FormatCoordinate(face.Texture.UAxis), face.Texture.XShift, face.Texture.XScale);
            ret["vaxis"]    = String.Format(CultureInfo.InvariantCulture, "[{0} {1}] {2}", FormatCoordinate(face.Texture.VAxis), face.Texture.YShift, face.Texture.YScale);
            ret["rotation"] = face.Texture.Rotation.ToString(CultureInfo.InvariantCulture);

            //NOTE(SVK) Copy RF data
            ret["flags"]            = ((int)face.Texture.Flags).ToString(CultureInfo.InvariantCulture);
            ret["translucency"]     = face.Texture.Translucency.ToString(CultureInfo.InvariantCulture);
            ret["opacity"]          = face.Texture.Opacity.ToString(CultureInfo.InvariantCulture);
            ret["positionrf"]       = FormatCoordinate(face.Texture.PositionRF);
            ret["transformanglerf"] = FormatMatrix(face.Texture.TransformAngleRF);

            // ret["lightmapscale"]
            // ret["smoothing_groups"]

            var verts = new GenericStructure("vertex");

            verts["count"] = face.Vertices.Count.ToString(CultureInfo.InvariantCulture);
            for (var i = 0; i < face.Vertices.Count; i++)
            {
                verts["vertex" + i] = FormatCoordinate(face.Vertices[i].Location);
            }
            ret.Children.Add(verts);

            var disp = face as Displacement;

            if (disp != null)
            {
                ret.Children.Add(WriteDisplacement(disp));
            }

            return(ret);
        }
Exemple #23
0
        public static CompileParameter Parse(GenericStructure gs)
        {
            var param = new CompileParameter
            {
                Name         = gs["Name"] ?? "",
                Flag         = gs["Flag"] ?? "",
                Description  = gs["Description"] ?? "",
                Enabled      = gs.PropertyBoolean("Enabled"),
                Value        = gs["Value"] ?? "",
                Type         = gs.PropertyEnum("Type", CompileParameterType.Checkbox),
                Min          = gs.PropertyDecimal("Min", Decimal.MinValue),
                Max          = gs.PropertyDecimal("Max", Decimal.MaxValue),
                Precision    = gs.PropertyInteger("Precision", 1),
                Options      = (gs["Options"] ?? "").Split(',').ToList(),
                OptionValues = (gs["OptionValues"] ?? "").Split(',').ToList(),
                Filter       = gs["Filter"] ?? ""
            };

            return(param);
        }
Exemple #24
0
        private static Displacement ReadDisplacement(long id, GenericStructure dispinfo)
        {
            var disp = new Displacement(id);

            // power, startposition, flags, elevation, subdiv, normals{}, distances{},
            // offsets{}, offset_normals{}, alphas{}, triangle_tags{}, allowed_verts{}
            disp.SetPower(dispinfo.PropertyInteger("power", 3));
            disp.StartPosition = dispinfo.PropertyCoordinate("startposition");
            disp.Elevation     = dispinfo.PropertyDecimal("elevation");
            disp.SubDiv        = dispinfo.PropertyInteger("subdiv") > 0;
            var size          = disp.Resolution + 1;
            var normals       = dispinfo.GetChildren("normals").FirstOrDefault();
            var distances     = dispinfo.GetChildren("distances").FirstOrDefault();
            var offsets       = dispinfo.GetChildren("offsets").FirstOrDefault();
            var offsetNormals = dispinfo.GetChildren("offset_normals").FirstOrDefault();
            var alphas        = dispinfo.GetChildren("alphas").FirstOrDefault();

            //var triangleTags = dispinfo.GetChildren("triangle_tags").First();
            //var allowedVerts = dispinfo.GetChildren("allowed_verts").First();
            for (var i = 0; i < size; i++)
            {
                var row  = "row" + i;
                var norm = normals != null?normals.PropertyCoordinateArray(row, size) : Enumerable.Range(0, size).Select(x => Coordinate.Zero).ToArray();

                var dist = distances != null?distances.PropertyDecimalArray(row, size) : Enumerable.Range(0, size).Select(x => 0m).ToArray();

                var offn = offsetNormals != null?offsetNormals.PropertyCoordinateArray(row, size) : Enumerable.Range(0, size).Select(x => Coordinate.Zero).ToArray();

                var offs = offsets != null?offsets.PropertyDecimalArray(row, size) : Enumerable.Range(0, size).Select(x => 0m).ToArray();

                var alph = alphas != null?alphas.PropertyDecimalArray(row, size) : Enumerable.Range(0, size).Select(x => 0m).ToArray();

                for (var j = 0; j < size; j++)
                {
                    disp.Points[i, j].Displacement       = new Vector(norm[j], dist[j]);
                    disp.Points[i, j].OffsetDisplacement = new Vector(offn[j], offs[j]);
                    disp.Points[i, j].Alpha = alph[j];
                }
            }
            return(disp);
        }
Exemple #25
0
        private static GenericStructure WriteEditor(MapObject obj)
        {
            var editor = new GenericStructure("editor");

            editor["color"] = FormatColor(obj.Colour);
            foreach (var visgroup in obj.Visgroups.Except(obj.AutoVisgroups).OrderBy(x => x))
            {
                editor.AddProperty("visgroupid", visgroup.ToString(CultureInfo.InvariantCulture));
            }
            editor["visgroupshown"]     = "1";
            editor["visgroupautoshown"] = "1";
            if (obj.Parent is Group)
            {
                editor["groupid"] = obj.Parent.ID.ToString(CultureInfo.InvariantCulture);
            }
            if (obj.Parent != null)
            {
                editor["parentid"] = obj.Parent.ID.ToString(CultureInfo.InvariantCulture);
            }
            return(editor);
        }
Exemple #26
0
        public static IEnumerable <MapObject> ExtractCopyStream(GenericStructure gs, IDGenerator generator)
        {
            if (gs == null || gs.Name != "clipboard")
            {
                return(null);
            }
            var dummyGen = new IDGenerator();
            var list     = new List <MapObject>();
            var world    = ReadWorld(gs, dummyGen);

            foreach (var entity in gs.GetChildren("entity"))
            {
                var ent       = ReadEntity(entity, dummyGen);
                var groupid   = entity.Children.Where(x => x.Name == "editor").Select(x => x.PropertyInteger("groupid")).FirstOrDefault();
                var entParent = groupid > 0 ? world.Find(x => x.ID == groupid && x is Group).FirstOrDefault() ?? world : world;
                ent.SetParent(entParent);
            }
            list.AddRange(world.GetChildren());
            Reindex(list, generator);
            return(list);
        }
        public void TestParseChildren()
        {
            var input =
                @"Test
                {
                    key value
                    Child
                    {
                        key2 value2
                        Child2
                        {
                            key3 value3
                        }
                    }
                }";
            var parsed = GenericStructure.Parse(new StringReader(input)).First();

            Assert.AreEqual("Test", parsed.Name);
            CollectionAssert.AreEquivalent(new List <string> {
                "key"
            }, parsed.GetPropertyKeys().ToList());
            Assert.AreEqual("value", parsed["key"]);
            Assert.AreEqual(1, parsed.Children.Count);

            var child = parsed.Children.First();

            Assert.AreEqual("Child", child.Name);
            CollectionAssert.AreEquivalent(new List <string> {
                "key2"
            }, child.GetPropertyKeys().ToList());
            Assert.AreEqual("value2", child["key2"]);
            Assert.AreEqual(1, child.Children.Count);

            child = child.Children.First();
            Assert.AreEqual("Child2", child.Name);
            CollectionAssert.AreEquivalent(new List <string> {
                "key3"
            }, child.GetPropertyKeys().ToList());
            Assert.AreEqual("value3", child["key3"]);
        }
Exemple #28
0
        private static GenericStructure WriteWorld(DataStructures.MapObjects.Map map, IEnumerable <Solid> solids, IEnumerable <Group> groups)
        {
            var world = map.WorldSpawn;
            var ret   = new GenericStructure("world");

            ret["id"]         = world.ID.ToString(CultureInfo.InvariantCulture);
            ret["classname"]  = "worldspawn";
            ret["mapversion"] = map.Version.ToString(CultureInfo.InvariantCulture);
            WriteEntityData(ret, world.EntityData);

            foreach (var solid in solids.OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteSolid(solid));
            }

            foreach (var group in groups.OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteGroup(group));
            }

            return(ret);
        }
Exemple #29
0
        private static GenericStructure WriteEntity(Entity ent)
        {
            var ret = new GenericStructure("entity");

            ret["id"]        = ent.ID.ToString(CultureInfo.InvariantCulture);
            ret["classname"] = ent.EntityData.Name;
            WriteEntityData(ret, ent.EntityData);
            if (!ent.HasChildren)
            {
                ret["origin"] = FormatCoordinate(ent.Origin);
            }

            var editor = WriteEditor(ent);

            ret.Children.Add(editor);

            foreach (var solid in ent.GetChildren().SelectMany(x => x.FindAll()).OfType <Solid>().OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteSolid(solid));
            }

            return(ret);
        }
Exemple #30
0
        private static GenericStructure WriteSolid(Solid solid)
        {
            var ret = new GenericStructure("solid");

            ret["id"] = solid.ID.ToString(CultureInfo.InvariantCulture);

            foreach (var face in solid.Faces.OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteFace(face));
            }

            var editor = WriteEditor(solid);

            ret.Children.Add(editor);

            if (solid.IsVisgroupHidden)
            {
                var hidden = new GenericStructure("hidden");
                hidden.Children.Add(ret);
                ret = hidden;
            }

            return(ret);
        }
Exemple #31
0
        public void VmtStatsCollectorTest()
        {
            var exclude = new[]
            {
                "ambulance",
                "backpack",
                "cable",
                "console",
                "cp_bloodstained",
                "customcubemaps",
                "detail",
                "debug",
                "effects",
                "engine",
                "environment maps",
                "halflife",
                "matsys_regressiontest",
                "hlmv",
                "hud",
                "logo",
                "maps",
                "models",
                "overviews",
                "particle",
                "particles",
                "perftest",
                "pl_halfacre",
                "pl_hoodoo",
                "scripted",
                "shadertest",
                "sprites",
                "sun",
                "vgui",
                "voice",
            };

            var stats = new Dictionary <string, int>();

            using (var fs = new VpkDirectory(new FileInfo(@"F:\Steam\SteamApps\common\Team Fortress 2\tf\tf2_misc_dir.vpk")))
            {
                using (var ss = fs.GetStreamSource())
                {
                    //var vmts = fs.SearchFiles("materials", ".vmt$", true);
                    var subs = fs.GetDirectories("materials").Where(x => !exclude.Contains(x.Split('/')[1]));
                    var vmts = subs.SelectMany(x => fs.SearchFiles(x, ".vmt$", true));
                    foreach (var vmt in vmts)
                    {
                        using (var sr = new StreamReader(ss.OpenFile(vmt)))
                        {
                            var parsed = GenericStructure.Parse(sr).First();
                            var type   = parsed.Name.ToLowerInvariant();
                            if (!stats.ContainsKey(type))
                            {
                                stats.Add(type, 0);
                            }
                            stats[type]++;
                            if (type == "refract" || type == "replacements" || type == "modulate")
                            {
                                Console.WriteLine(type + " " + vmt);
                            }
                        }
                    }
                }
            }
            foreach (var kv in stats.OrderByDescending(x => x.Value))
            {
                Console.WriteLine(kv.Key + " - " + kv.Value);
            }
        }
Exemple #32
0
 private static Entity ReadEntity(GenericStructure entity, IDGenerator generator)
 {
     var ret = new Entity(GetObjectID(entity, generator))
                   {
                       ClassName = entity["classname"],
                       EntityData = ReadEntityData(entity),
                       Origin = entity.PropertyCoordinate("origin")
                   };
     var editor = entity.GetChildren("editor").FirstOrDefault() ?? new GenericStructure("editor");
     ret.Colour = editor.PropertyColour("color", Colour.GetRandomBrushColour());
     ret.Visgroups.AddRange(editor.GetAllPropertyValues("visgroupid").Select(int.Parse));
     foreach (var child in entity.GetChildren("solid").Select(solid => ReadSolid(solid, generator)).Where(s => s != null))
     {
         child.SetParent(ret);
     }
     ret.UpdateBoundingBox(false);
     return ret;
 }
Exemple #33
0
 private static EntityData ReadEntityData(GenericStructure structure)
 {
     var ret = new EntityData();
     foreach (var key in structure.GetPropertyKeys())
     {
         if (ExcludedKeys.Contains(key.ToLower())) continue;
         ret.SetPropertyValue(key, structure[key]);
     }
     ret.Name = structure["classname"];
     ret.Flags = structure.PropertyInteger("spawnflags");
     return ret;
 }
Exemple #34
0
        private static Face ReadFace(GenericStructure side, IDGenerator generator)
        {
            var id = side.PropertyLong("id");
            if (id == 0) id = generator.GetNextFaceID();
            var dispinfo = side.GetChildren("dispinfo").FirstOrDefault();
            var ret = dispinfo != null ? ReadDisplacement(id, dispinfo) : new Face(id);
            // id, plane, material, uaxis, vaxis, rotation, lightmapscale, smoothing_groups
            var uaxis = side.PropertyTextureAxis("uaxis");
            var vaxis = side.PropertyTextureAxis("vaxis");
            ret.Texture.Name = side["material"];
            ret.Texture.UAxis = uaxis.Item1;
            ret.Texture.XShift = uaxis.Item2;
            ret.Texture.XScale = uaxis.Item3;
            ret.Texture.VAxis = vaxis.Item1;
            ret.Texture.YShift = vaxis.Item2;
            ret.Texture.YScale = vaxis.Item3;
            ret.Texture.Rotation = side.PropertyDecimal("rotation");
            ret.Plane = side.PropertyPlane("plane");

            var verts = side.Children.FirstOrDefault(x => x.Name == "vertex");
            if (verts != null)
            {
                var count = verts.PropertyInteger("count");
                for (var i = 0; i < count; i++)
                {
                    ret.Vertices.Add(new Vertex(verts.PropertyCoordinate("vertex"+i), ret));
                }
            }

            return ret;
        }
Exemple #35
0
 private static Group ReadGroup(GenericStructure group, IDGenerator generator)
 {
     var g = new Group(GetObjectID(group, generator));
     var editor = group.GetChildren("editor").FirstOrDefault() ?? new GenericStructure("editor");
     g.Colour = editor.PropertyColour("color", Colour.GetRandomBrushColour());
     g.Visgroups.AddRange(editor.GetAllPropertyValues("visgroupid").Select(int.Parse));
     return g;
 }
Exemple #36
0
 private static void WriteEntityData(GenericStructure obj, EntityData data)
 {
     foreach (var property in data.Properties.OrderBy(x => x.Key))
     {
         obj[property.Key] = property.Value;
     }
     obj["spawnflags"] = data.Flags.ToString(CultureInfo.InvariantCulture);
 }
Exemple #37
0
 private static GenericStructure WriteVisgroup(Visgroup visgroup)
 {
     var ret = new GenericStructure("visgroup");
     ret["name"] = visgroup.Name;
     ret["visgroupid"] = visgroup.ID.ToString(CultureInfo.InvariantCulture);
     ret["color"] = FormatColor(visgroup.Colour);
     return ret;
 }
Exemple #38
0
 private static long GetObjectID(GenericStructure gs, IDGenerator generator)
 {
     var id = gs.PropertyLong("id");
     if (id == 0) id = generator.GetNextObjectID();
     return id;
 }
Exemple #39
0
 private TextureFlags GetFlags(GenericStructure vmt)
 {
     var flags = TextureFlags.None;
     var tp = vmt.PropertyInteger("$translucent") + vmt.PropertyInteger("$alphatest");
     if (tp > 0) flags |= TextureFlags.Transparent;
     return flags;
 }
Exemple #40
0
        protected override DataStructures.MapObjects.Map GetFromStream(Stream stream)
        {
            using (var reader = new StreamReader(stream))
            {
                var parent = new GenericStructure("Root");
                parent.Children.AddRange(GenericStructure.Parse(reader));
                // Sections from a Hammer map:
                // - world
                // - entity
                // - visgroups
                // - cordon
                // Not done yet
                // - versioninfo
                // - viewsettings
                // - cameras

                var map = new DataStructures.MapObjects.Map();

                var world = parent.GetChildren("world").FirstOrDefault();
                var entities = parent.GetChildren("entity");
                var visgroups = parent.GetChildren("visgroups").SelectMany(x => x.GetChildren("visgroup"));
                var cameras = parent.GetChildren("cameras").FirstOrDefault();
                var cordon = parent.GetChildren("cordon").FirstOrDefault();
                var viewsettings = parent.GetChildren("viewsettings").FirstOrDefault();

                foreach (var visgroup in visgroups)
                {
                    var vg = ReadVisgroup(visgroup);
                    if (vg.ID < 0 && vg.Name == "Auto") continue;
                    map.Visgroups.Add(vg);
                }

                if (world != null) map.WorldSpawn = ReadWorld(world, map.IDGenerator);
                foreach (var entity in entities)
                {
                    var ent = ReadEntity(entity, map.IDGenerator);
                    var groupid = entity.Children.Where(x => x.Name == "editor").Select(x => x.PropertyInteger("groupid")).FirstOrDefault();
                    var entParent = groupid > 0 ? map.WorldSpawn.Find(x => x.ID == groupid && x is Group).FirstOrDefault() ?? map.WorldSpawn : map.WorldSpawn;
                    ent.SetParent(entParent);
                }

                var activeCamera = 0;
                if (cameras != null)
                {
                    activeCamera = cameras.PropertyInteger("activecamera");
                    foreach (var cam in cameras.GetChildren("camera"))
                    {
                        var pos = cam.PropertyCoordinate("position");
                        var look = cam.PropertyCoordinate("look");
                        if (pos != null && look != null)
                        {
                            map.Cameras.Add(new Camera {EyePosition = pos, LookPosition = look});
                        }
                    }
                }
                if (!map.Cameras.Any())
                {
                    map.Cameras.Add(new Camera { EyePosition = Coordinate.Zero, LookPosition = Coordinate.UnitY });
                }
                if (activeCamera < 0 || activeCamera >= map.Cameras.Count)
                {
                    activeCamera = 0;
                }
                map.ActiveCamera = map.Cameras[activeCamera];

                if (cordon != null)
                {
                    var start = cordon.PropertyCoordinate("mins", map.CordonBounds.Start);
                    var end = cordon.PropertyCoordinate("maxs", map.CordonBounds.End);
                    map.CordonBounds = new Box(start, end);
                    map.Cordon = cordon.PropertyBoolean("active", map.Cordon);
                }

                if (viewsettings != null)
                {
                    map.SnapToGrid = viewsettings.PropertyBoolean("bSnapToGrid", map.SnapToGrid);
                    map.Show2DGrid = viewsettings.PropertyBoolean("bShowGrid", map.Show2DGrid);
                    map.Show3DGrid = viewsettings.PropertyBoolean("bShow3DGrid", map.Show3DGrid);
                    map.GridSpacing = viewsettings.PropertyDecimal("nGridSpacing", map.GridSpacing);
                    map.IgnoreGrouping = viewsettings.PropertyBoolean("bIgnoreGrouping", map.IgnoreGrouping);
                    map.HideFaceMask = viewsettings.PropertyBoolean("bHideFaceMask", map.HideFaceMask);
                    map.HideNullTextures = viewsettings.PropertyBoolean("bHideNullTextures", map.HideNullTextures);
                    map.TextureLock = viewsettings.PropertyBoolean("bTextureLock", map.TextureLock);
                    map.TextureScalingLock = viewsettings.PropertyBoolean("bTextureScalingLock", map.TextureScalingLock);
                }

                return map;
            }
        }
Exemple #41
0
        private static GenericStructure WriteWorld(DataStructures.MapObjects.Map map, IEnumerable<Solid> solids, IEnumerable<Group> groups)
        {
            var world = map.WorldSpawn;
            var ret = new GenericStructure("world");
            ret["id"] = world.ID.ToString(CultureInfo.InvariantCulture);
            ret["classname"] = "worldspawn";
            WriteEntityData(ret, world.EntityData);

            //TODO these properties
            ret["mapversion"] = map.Version.ToString(CultureInfo.InvariantCulture);
            ret["detailmaterial"] = "detail/detailsprites";
            ret["detailvbsp"] = "detail.vbsp";
            ret["maxpropscreenwidth"] = "-1";
            ret["skyname"] = "sky_day01_01";

            foreach (var solid in solids.OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteSolid(solid));
            }

            foreach (var group in groups.OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteGroup(group));
            }

            return ret;
        }
Exemple #42
0
 private static GenericStructure WriteEditor(MapObject obj)
 {
     var editor = new GenericStructure("editor");
     editor["color"] = FormatColor(obj.Colour);
     foreach (var visgroup in obj.Visgroups.OrderBy(x => x))
     {
         editor.AddProperty("visgroupid", visgroup.ToString(CultureInfo.InvariantCulture));
     }
     editor["visgroupshown"] = "1";
     editor["visgroupautoshown"] = "1";
     if (obj.Parent is Group) editor["groupid"] = obj.Parent.ID.ToString(CultureInfo.InvariantCulture);
     if (obj.Parent != null) editor["parentid"] = obj.Parent.ID.ToString(CultureInfo.InvariantCulture);
     return editor;
 }
Exemple #43
0
 private static Displacement ReadDisplacement(long id, GenericStructure dispinfo)
 {
     var disp = new Displacement(id);
     // power, startposition, flags, elevation, subdiv, normals{}, distances{},
     // offsets{}, offset_normals{}, alphas{}, triangle_tags{}, allowed_verts{}
     disp.SetPower(dispinfo.PropertyInteger("power", 3));
     disp.StartPosition = dispinfo.PropertyCoordinate("startposition");
     disp.Elevation = dispinfo.PropertyDecimal("elevation");
     disp.SubDiv = dispinfo.PropertyInteger("subdiv") > 0;
     var size = disp.Resolution + 1;
     var normals = dispinfo.GetChildren("normals").FirstOrDefault();
     var distances = dispinfo.GetChildren("distances").FirstOrDefault();
     var offsets = dispinfo.GetChildren("offsets").FirstOrDefault();
     var offsetNormals = dispinfo.GetChildren("offset_normals").FirstOrDefault();
     var alphas = dispinfo.GetChildren("alphas").FirstOrDefault();
     //var triangleTags = dispinfo.GetChildren("triangle_tags").First();
     //var allowedVerts = dispinfo.GetChildren("allowed_verts").First();
     for (var i = 0; i < size; i++)
     {
         var row = "row" + i;
         var norm = normals != null ? normals.PropertyCoordinateArray(row, size) : Enumerable.Range(0, size).Select(x => Coordinate.Zero).ToArray();
         var dist = distances != null ? distances.PropertyDecimalArray(row, size) : Enumerable.Range(0, size).Select(x => 0m).ToArray();
         var offn = offsetNormals != null ? offsetNormals.PropertyCoordinateArray(row, size) : Enumerable.Range(0, size).Select(x => Coordinate.Zero).ToArray();
         var offs = offsets != null ? offsets.PropertyDecimalArray(row, size) : Enumerable.Range(0, size).Select(x => 0m).ToArray();
         var alph = alphas != null ? alphas.PropertyDecimalArray(row, size) : Enumerable.Range(0, size).Select(x => 0m).ToArray();
         for (var j = 0; j < size; j++)
         {
             disp.Points[i, j].Displacement = new Vector(norm[j], dist[j]);
             disp.Points[i, j].OffsetDisplacement = new Vector(offn[j], offs[j]);
             disp.Points[i, j].Alpha = alph[j];
         }
     }
     return disp;
 }
Exemple #44
0
        static void Main(string[] args)
        {
            Program p1 = new Program();
            Int32 intBoxed = 10, unboxed;
            //boxing
            Object obj = (Object)intBoxed;
            //unboxing
            try
            {
                Int16 newint = (Int16)obj;
            }
            catch (InvalidCastException ice)
            {
                Console.WriteLine(ice.Message);
            }
            finally
            {
                Int32 newint = (Int32)obj;
                unboxed = newint;
            }
            //Int32 newint = (Int32)obj;
            Console.WriteLine(unboxed);
            p1.WorkingWithArrayList();
            p1.WorkingWithQueue();
            p1.WorkingWithSortedList();
            p1.WorkingWithStack();
            p1.WorkingWithGenerics();
            p1.GenericListDemo();
            p1.GenericStack();
            Demo d1 = new Demo();
            int x = 10, y = 20;
            d1.Swap<Int32>(ref x, ref y);
            Product product1 = new Product(0001, "book", 3.45);
            Product product2 = new Product(0002, "file", 2.13);
            d1.Swap<Product>(ref product1, ref product2);
            //d1.Swap(ref product1, ref product2); //not a standard approach, always specify Type Parameters

            GenericStructure<Int32> myStruct = new GenericStructure<int>(10, 25);
            //myStruct.Reset();
            Console.WriteLine(myStruct);

            TypeParameterConstraints<SatisfyingConstraints> scObj = new TypeParameterConstraints<SatisfyingConstraints>();
            scObj.Show(new SatisfyingConstraints(34.678));

            FinalGenericDerivedClass<Product, Employee> objFGDC = new FinalGenericDerivedClass<Product, Employee>();
            objFGDC.Show();
            Console.WriteLine(objFGDC);
            Console.ReadLine();
        }
Exemple #45
0
        protected override void SaveToStream(Stream stream, DataStructures.MapObjects.Map map)
        {
            var groups = new List<Group>();
            var solids = new List<Solid>();
            var ents = new List<Entity>();
            FlattenTree(map.WorldSpawn, solids, ents, groups);

            var fvi = FileVersionInfo.GetVersionInfo(typeof (VmfProvider).Assembly.Location);
            var versioninfo = new GenericStructure("versioninfo");
            versioninfo.AddProperty("editorname", "Sledge");
            versioninfo.AddProperty("editorversion", fvi.ProductMajorPart.ToString(CultureInfo.InvariantCulture) + "." + fvi.ProductMinorPart.ToString(CultureInfo.InvariantCulture));
            versioninfo.AddProperty("editorbuild", fvi.ProductBuildPart.ToString(CultureInfo.InvariantCulture));
            versioninfo.AddProperty("mapversion", map.Version.ToString(CultureInfo.InvariantCulture));
            versioninfo.AddProperty("formatversion", "100");
            versioninfo.AddProperty("prefab", "0");

            var visgroups = new GenericStructure("visgroups");
            foreach (var visgroup in map.Visgroups.OrderBy(x => x.ID).Where(x => !x.IsAutomatic))
            {
                visgroups.Children.Add(WriteVisgroup(visgroup));
            }

            var viewsettings = new GenericStructure("viewsettings");

            viewsettings.AddProperty("bSnapToGrid", map.SnapToGrid ? "1" : "0");
            viewsettings.AddProperty("bShowGrid", map.Show2DGrid ? "1" : "0");
            viewsettings.AddProperty("bShow3DGrid", map.Show3DGrid ? "1" : "0");
            viewsettings.AddProperty("nGridSpacing", map.GridSpacing.ToString(CultureInfo.InvariantCulture));
            viewsettings.AddProperty("bIgnoreGrouping", map.IgnoreGrouping ? "1" : "0");
            viewsettings.AddProperty("bHideFaceMask", map.HideFaceMask ? "1" : "0");
            viewsettings.AddProperty("bHideNullTextures", map.HideNullTextures ? "1" : "0");
            viewsettings.AddProperty("bTextureLock", map.TextureLock ? "1" : "0");
            viewsettings.AddProperty("bTextureScalingLock", map.TextureScalingLock ? "1" : "0");

            var world = WriteWorld(map, solids, groups);

            var entities = ents.OrderBy(x => x.ID).Select(WriteEntity).ToList();

            var cameras = new GenericStructure("cameras");
            cameras.AddProperty("activecamera", map.Cameras.IndexOf(map.ActiveCamera).ToString(CultureInfo.InvariantCulture));
            foreach (var cam in map.Cameras)
            {
                var camera = new GenericStructure("camera");
                camera.AddProperty("position", "[" + FormatCoordinate(cam.EyePosition) + "]");
                camera.AddProperty("look", "[" + FormatCoordinate(cam.LookPosition) + "]");
                cameras.Children.Add(camera);
            }

            var cordon = new GenericStructure("cordon");
            cordon.AddProperty("mins", map.CordonBounds.Start.ToString());
            cordon.AddProperty("maxs", map.CordonBounds.End.ToString());
            cordon.AddProperty("active", map.Cordon ? "1" : "0");

            using (var sw = new StreamWriter(stream))
            {
                versioninfo.PrintToStream(sw);
                visgroups.PrintToStream(sw);
                viewsettings.PrintToStream(sw);
                world.PrintToStream(sw);
                entities.ForEach(e => e.PrintToStream(sw));
                cameras.PrintToStream(sw);
                cordon.PrintToStream(sw);
            }
        }
Exemple #46
0
        private static World ReadWorld(GenericStructure world, IDGenerator generator)
        {
            var ret = new World(GetObjectID(world, generator))
                          {
                              ClassName = "worldspawn",
                              EntityData = ReadEntityData(world)
                          };

            // Load groups
            var groups = new Dictionary<Group, long>();
            foreach (var group in world.GetChildren("group"))
            {
                var g = ReadGroup(group, generator);
                var editor = group.GetChildren("editor").FirstOrDefault() ?? new GenericStructure("editor");
                var gid = editor.PropertyLong("groupid");
                groups.Add(g, gid);
            }

            // Build group tree
            var assignedGroups = groups.Where(x => x.Value == 0).Select(x => x.Key).ToList();
            foreach (var ag in assignedGroups)
            {
                // Add the groups with no parent
                ag.SetParent(ret);
                groups.Remove(ag);
            }
            while (groups.Any())
            {
                var canAssign = groups.Where(x => assignedGroups.Any(y => y.ID == x.Value)).ToList();
                if (!canAssign.Any())
                {
                    break;
                }
                foreach (var kv in canAssign)
                {
                    // Add the group to the tree and the assigned list, remove it from the groups list
                    var parent = assignedGroups.First(y => y.ID == kv.Value);
                    kv.Key.SetParent(parent);
                    assignedGroups.Add(kv.Key);
                    groups.Remove(kv.Key);
                }
            }

            // Load visible solids
            foreach (var solid in world.GetChildren("solid"))
            {
                var s = ReadSolid(solid, generator);
                if (s == null) continue;

                var editor = solid.GetChildren("editor").FirstOrDefault() ?? new GenericStructure("editor");
                var gid = editor.PropertyLong("groupid");
                var parent = gid > 0 ? assignedGroups.FirstOrDefault(x => x.ID == gid) ?? (MapObject) ret : ret;
                s.SetParent(parent);
                parent.UpdateBoundingBox();
            }

            // Load hidden solids
            foreach (var hidden in world.GetChildren("hidden"))
            {
                foreach (var solid in hidden.GetChildren("solid"))
                {
                    var s = ReadSolid(solid, generator);
                    if (s == null) continue;

                    s.IsVisgroupHidden = true;

                    var editor = solid.GetChildren("editor").FirstOrDefault() ?? new GenericStructure("editor");
                    var gid = editor.PropertyLong("groupid");
                    var parent = gid > 0 ? assignedGroups.FirstOrDefault(x => x.ID == gid) ?? (MapObject)ret : ret;
                    s.SetParent(parent);
                    parent.UpdateBoundingBox();
                }
            }

            assignedGroups.ForEach(x => x.UpdateBoundingBox(false));

            return ret;
        }
Exemple #47
0
 private static Visgroup ReadVisgroup(GenericStructure visgroup)
 {
     var v = new Visgroup
                 {
                     Name = visgroup["name"],
                     ID = visgroup.PropertyInteger("visgroupid"),
                     Colour = visgroup.PropertyColour("color", Colour.GetRandomBrushColour()),
                     Visible = true
                 };
     return v;
 }
Exemple #48
0
        private static Solid ReadSolid(GenericStructure solid, IDGenerator generator)
        {
            var editor = solid.GetChildren("editor").FirstOrDefault() ?? new GenericStructure("editor");
            var faces = solid.GetChildren("side").Select(x => ReadFace(x, generator)).ToList();

            Solid ret;

            if (faces.All(x => x.Vertices.Count >= 3))
            {
                // Vertices were stored in the VMF
                ret = new Solid(GetObjectID(solid, generator));
                ret.Faces.AddRange(faces);
            }
            else
            {
                // Need to grab the vertices using plane intersections
                var idg = new IDGenerator(); // No need to increment the id generator if it doesn't have to be
                ret = Solid.CreateFromIntersectingPlanes(faces.Select(x => x.Plane), idg);
                ret.ID = GetObjectID(solid, generator);

                for (var i = 0; i < ret.Faces.Count; i++)
                {
                    var face = ret.Faces[i];
                    var f = faces.FirstOrDefault(x => x.Plane.Normal.EquivalentTo(ret.Faces[i].Plane.Normal));
                    if (f == null)
                    {
                        // TODO: Report invalid solids
                        Debug.WriteLine("Invalid solid! ID: " + solid["id"]);
                        return null;
                    }
                    face.Texture = f.Texture;

                    var disp = f as Displacement;
                    if (disp == null) continue;

                    disp.Plane = face.Plane;
                    disp.Vertices = face.Vertices;
                    disp.Texture = f.Texture;
                    disp.AlignTextureToWorld();
                    disp.CalculatePoints();
                    ret.Faces[i] = disp;
                }
            }

            ret.Colour = editor.PropertyColour("color", Colour.GetRandomBrushColour());
            ret.Visgroups.AddRange(editor.GetAllPropertyValues("visgroupid").Select(int.Parse));
            foreach (var face in ret.Faces)
            {
                face.Parent = ret;
                face.Colour = ret.Colour;
                face.UpdateBoundingBox();
            }

            if (ret.Faces.Any(x => x is Displacement))
            {
                ret.Faces.ForEach(x => x.IsHidden = !(x is Displacement));
            }

            ret.UpdateBoundingBox(false);

            return ret;
        }
Exemple #49
0
        private static GenericStructure WriteFace(Face face)
        {
            var ret = new GenericStructure("side");
            ret["id"] = face.ID.ToString(CultureInfo.InvariantCulture);
            ret["plane"] = String.Format("({0}) ({1}) ({2})",
                                         FormatCoordinate(face.Vertices[0].Location),
                                         FormatCoordinate(face.Vertices[1].Location),
                                         FormatCoordinate(face.Vertices[2].Location));
            ret["material"] = face.Texture.Name;
            ret["uaxis"] = String.Format(CultureInfo.InvariantCulture, "[{0} {1}] {2}", FormatCoordinate(face.Texture.UAxis), face.Texture.XShift, face.Texture.XScale);
            ret["vaxis"] = String.Format(CultureInfo.InvariantCulture, "[{0} {1}] {2}", FormatCoordinate(face.Texture.VAxis), face.Texture.YShift, face.Texture.YScale);
            ret["rotation"] = face.Texture.Rotation.ToString(CultureInfo.InvariantCulture);
            // ret["lightmapscale"]
            // ret["smoothing_groups"]

            var verts = new GenericStructure("vertex");
            verts["count"] = face.Vertices.Count.ToString(CultureInfo.InvariantCulture);
            for (var i = 0; i < face.Vertices.Count; i++)
            {
                verts["vertex" + i] = FormatCoordinate(face.Vertices[i].Location);
            }
            ret.Children.Add(verts);

            var disp = face as Displacement;
            if (disp != null)
            {
                ret.Children.Add(WriteDisplacement(disp));
            }

            return ret;
        }
Exemple #50
0
        private static GenericStructure WriteEntity(Entity ent)
        {
            var ret = new GenericStructure("entity");
            ret["id"] = ent.ID.ToString(CultureInfo.InvariantCulture);
            ret["classname"] = ent.EntityData.Name;
            WriteEntityData(ret, ent.EntityData);
            if (!ent.HasChildren) ret["origin"] = FormatCoordinate(ent.Origin);

            var editor = WriteEditor(ent);
            ret.Children.Add(editor);

            foreach (var solid in ent.GetChildren().SelectMany(x => x.FindAll()).OfType<Solid>().OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteSolid(solid));
            }

            return ret;
        }
Exemple #51
0
        public static void Write()
        {
            var newSettings = Serialise.SerialiseSettings().Select(s => new Setting {
                Key = s.Key, Value = s.Value
            });

            Settings.Clear();
            Settings.AddRange(newSettings);

            var root = new GenericStructure("Sledge");

            // Settings
            var settings = new GenericStructure("Settings");

            foreach (var setting in Settings)
            {
                settings.AddProperty(setting.Key, setting.Value);
            }
            root.Children.Add(settings);

            // Recent Files
            var recents = new GenericStructure("RecentFiles");
            var i       = 1;

            foreach (var file in RecentFiles.OrderBy(x => x.Order).Select(x => x.Location).Where(File.Exists))
            {
                recents.AddProperty(i.ToString(CultureInfo.InvariantCulture), file);
                i++;
            }
            root.Children.Add(recents);

            // Games > Fgds/Wads
            foreach (var game in Games)
            {
                var g = new GenericStructure("Game");
                game.Write(g);
                root.Children.Add(g);
            }

            // Builds
            foreach (var build in Builds)
            {
                var b = new GenericStructure("Build");
                build.Write(b);
                root.Children.Add(b);
            }

            // Hotkeys
            Hotkeys = Sledge.Settings.Hotkeys.GetHotkeys().ToList();
            var hotkeys = new GenericStructure("Hotkeys");

            foreach (var g in Hotkeys.GroupBy(x => x.ID))
            {
                var count = 0;
                foreach (var hotkey in g)
                {
                    hotkeys.AddProperty(hotkey.ID + ":" + count, hotkey.HotkeyString);
                    count++;
                }
            }
            root.Children.Add(hotkeys);

            // Additional
            var additional = new GenericStructure("AdditionalSettings");

            foreach (var kv in AdditionalSettings)
            {
                var child = new GenericStructure(kv.Key);
                child.Children.Add(kv.Value);
                additional.Children.Add(child);
            }
            root.Children.Add(additional);

            // Favourite textures
            var favTextures = new GenericStructure("FavouriteTextures");

            favTextures.Children.Add(GenericStructure.Serialise(FavouriteTextureFolders));
            root.Children.Add(favTextures);

            File.WriteAllText(SettingsFile, root.ToString());
        }
Exemple #52
0
        private static GenericStructure WriteGroup(Group group)
        {
            var ret = new GenericStructure("group");
            ret["id"] = group.ID.ToString(CultureInfo.InvariantCulture);

            var editor = WriteEditor(group);
            ret.Children.Add(editor);

            return ret;
        }
Exemple #53
0
        private static GenericStructure WriteSolid(Solid solid)
        {
            var ret = new GenericStructure("solid");
            ret["id"] = solid.ID.ToString(CultureInfo.InvariantCulture);

            foreach (var face in solid.Faces.OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteFace(face));
            }

            var editor = WriteEditor(solid);
            ret.Children.Add(editor);

            if (solid.IsVisgroupHidden)
            {
                var hidden = new GenericStructure("hidden");
                hidden.Children.Add(ret);
                ret = hidden;
            }

            return ret;
        }
Exemple #54
0
        private static GenericStructure WriteWorld(DataStructures.MapObjects.Map map, IEnumerable<Solid> solids, IEnumerable<Group> groups)
        {
            var world = map.WorldSpawn;
            var ret = new GenericStructure("world");
            ret["id"] = world.ID.ToString(CultureInfo.InvariantCulture);
            ret["classname"] = "worldspawn";
            ret["mapversion"] = map.Version.ToString(CultureInfo.InvariantCulture);
            WriteEntityData(ret, world.EntityData);

            foreach (var solid in solids.OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteSolid(solid));
            }

            foreach (var group in groups.OrderBy(x => x.ID))
            {
                ret.Children.Add(WriteGroup(group));
            }

            return ret;
        }