├── plugin ├── KIPCPlugin │ ├── KOS │ │ ├── Extensions.cs │ │ ├── KRPCClient.cs │ │ ├── KRPCConnection.cs │ │ └── Addon.cs │ ├── FodyWeavers.xml │ ├── Serialization │ │ ├── Exceptions.cs │ │ ├── CollectionHandler.cs │ │ ├── BodyHandler.cs │ │ ├── SerializesAttribute.cs │ │ ├── VesselHandler.cs │ │ ├── ListHandlers.cs │ │ ├── LexiconHandler.cs │ │ ├── GeometryHandlers.cs │ │ ├── TypeRegistry.cs │ │ ├── TypeSerializer.cs │ │ ├── TypeHandler.cs │ │ └── Serializer.cs │ ├── packages.config │ ├── Extensions.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Addon.cs │ ├── KRPC │ │ ├── Processor.cs │ │ └── Service.cs │ ├── Util │ │ ├── CountingIterator.cs │ │ ├── Validation.cs │ │ └── CacheDictionary.cs │ ├── KIPCPlugin.csproj │ ├── KOSAddon.cs │ └── KIPC.csproj ├── KIPC.version ├── KIPC.version.template ├── KIPC.sln └── Postbuild.ps1 ├── .vscode └── settings.json ├── python ├── requirements.txt └── cli.py ├── doc ├── CHANGELOG.md ├── kos.md ├── index.md ├── krpc.md └── LICENSE.md ├── .gitattributes ├── KIPC.netkan ├── README.md └── .gitignore /plugin/KIPCPlugin/KOS/Extensions.cs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "editor.rulers": [120], 4 | } -------------------------------------------------------------------------------- /plugin/KIPCPlugin/FodyWeavers.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /python/requirements.txt: -------------------------------------------------------------------------------- 1 | Jinja2==2.8 2 | krpc==0.3.5 3 | krpc.clientgen==0.2.2 4 | krpctools==0.3.5 5 | MarkupSafe==0.23 6 | protobuf==3.0.0b3 7 | six==1.10.0 8 | -------------------------------------------------------------------------------- /plugin/KIPC.version: -------------------------------------------------------------------------------- 1 | {"NAME":"kIPC","VERSION":{"MAJOR":0,"MINOR":2,"PATCH":0,"BUILD":0},"KSP_VERSION":{"MAJOR":1,"MINOR":1,"PATCH":3},"KSP_VERSION_MIN":{"MAJOR":1,"MINOR":1,"PATCH":3},"KSP_VERSION_MAX":{"MAJOR":1,"MINOR":1,"PATCH":99},"GITHUB":{"USERNAME":"dewiniaid","REPOSITORY":"ksp-kipc","ALLOW_PRE_RELEASE":false},"URL":"https://raw.githubusercontent.com/dewiniaid/ksp-kipc/master/plugin/KIPC.version"} 2 | -------------------------------------------------------------------------------- /python/cli.py: -------------------------------------------------------------------------------- 1 | import krpc 2 | import code 3 | 4 | conn = krpc.connect(name="KIPC Test Script") 5 | print(conn.krpc.get_status()) 6 | 7 | processors = conn.kipc.get_processors(conn.space_center.active_vessel) 8 | print(repr(processors)) 9 | part = processors[0].part 10 | print(repr(part)) 11 | processor = conn.kipc.get_processor(part) 12 | print(repr(processor)) 13 | 14 | code.interact(local=globals()) 15 | 16 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/Exceptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace KIPC.Serialization 4 | { 5 | public class SerializationException : Exception 6 | { 7 | public SerializationException() { } 8 | public SerializationException(string message) : base(message) { } 9 | public SerializationException(string message, Exception inner) : base(message, inner) { } 10 | } 11 | } -------------------------------------------------------------------------------- /plugin/KIPCPlugin/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /plugin/KIPC.version.template: -------------------------------------------------------------------------------- 1 | { 2 | "NAME":"kIPC", 3 | 4 | "VERSION": { "MAJOR": 0, "MINOR": 2, "PATCH": 0, "BUILD" :0 }, 5 | "KSP_VERSION": { "MAJOR": 1, "MINOR": 1, "PATCH": 3 }, 6 | "KSP_VERSION_MIN": { "MAJOR": 1, "MINOR": 1, "PATCH": 3 }, 7 | "KSP_VERSION_MAX": { "MAJOR": 1, "MINOR": 1, "PATCH": 99 }, 8 | 9 | "GITHUB": { 10 | "USERNAME": "dewiniaid", 11 | "REPOSITORY": "ksp-kipc", 12 | "ALLOW_PRE_RELEASE": false 13 | }, 14 | "URL": "https://raw.githubusercontent.com/dewiniaid/ksp-kipc/master/plugin/KIPC.version" 15 | } 16 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/KOS/KRPCClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | using kOS.Safe.Encapsulation; 7 | 8 | namespace KIPC.KOS 9 | { 10 | /// 11 | /// Represents a KRPC client. Placeholder. 12 | /// 13 | [kOS.Safe.Utilities.KOSNomenclature("KRPCClient")] 14 | class KRPCClient : Structure 15 | { 16 | public KRPCClient(kOS.SharedObjects shared) { } 17 | 18 | public override string ToString() 19 | { 20 | return "KRPCClient(PLACEHOLDER)"; 21 | } 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /doc/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | **[ [KIPC Overview](index.md) ] [ [kOS API](kos.md) ] [ [kRPC API](krpc.md) ] [ [Changelog](CHANGELOG.md) ] [ [License](LICENSE.md) ]** 4 | 5 | ## 0.2.0-beta (2016-07-16) 6 | 7 | - Added client libraries for C#, C++ and Java. 8 | - Added preliminary support for CKAN and KSP-AVC. This release *does not* include MiniAVC and *does not* use the internet to check for version updates, but other providers of MiniAVC/KSP-AVC might. 9 | 10 | ## 0.1.1-dev2 (2016-07-12) 11 | 12 | - Added `KIPC.GetMessages` and `KIPC.CountMessages` for better control and information about the message queue. 13 | - Added `KIPC.ResolveBodies` and `KIPC.ResolveVessels` to handle multiple bodies/vessels at once. 14 | - Added `KIPC.GetProcessor` to retrieve the kOSProcessor of a single part (compare to `KIPC.GetProcessors` which receives all processors on a given vesse) 15 | - Added `KIPC.GetPartsTagged` to find parts with a given `kOSNameTag`. 16 | 17 | ## 0.1.0-dev1 (2016-07-10) 18 | 19 | - First development release. 20 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | # http://davidlaing.com/2012/09/19/customise-your-gitattributes-to-become-a-git-ninja/ 3 | * text=auto 4 | 5 | *.cs text eol=crlf diff=csharp 6 | 7 | # Custom for Visual Studio 8 | *.sln text eol=crlf 9 | *.csproj text eol=crlf 10 | *.vbproj text eol=crlf 11 | *.fsproj text eol=crlf 12 | *.dbproj text eol=crlf 13 | 14 | *.vcxproj text eol=crlf 15 | *.vcxitems text eol=crlf 16 | *.props text eol=crlf 17 | *.filters text eol=crlf 18 | 19 | # Basic .gitattributes for a python repo. 20 | 21 | # Source files 22 | # ============ 23 | *.pxd text 24 | *.py text 25 | *.py3 text 26 | *.pyw text 27 | *.pyx text 28 | 29 | # Binary files 30 | # ============ 31 | *.db binary 32 | *.p binary 33 | *.pkl binary 34 | *.pyc binary 35 | *.pyd binary 36 | *.pyo binary 37 | 38 | # Note: .db, .p, and .pkl files are associated 39 | # with the python modules ``pickle``, ``dbm.*``, 40 | # ``shelve``, ``marshal``, ``anydbm``, & ``bsddb`` 41 | # (among others). 42 | -------------------------------------------------------------------------------- /KIPC.netkan: -------------------------------------------------------------------------------- 1 | { 2 | "spec_version" : 1, 3 | "identifier" : "KIPC", 4 | "author" : "dewin", 5 | "$kref" : "#/ckan/github/dewiniaid/ksp-kipc", 6 | "$vref" : "#/ckan/ksp-avc", 7 | "name" : "kIPC: Kerbal Interprocess Communication", 8 | "abstract" : "Provides a communication bridge between kOS and kRPC.", 9 | "description" : "kIPC adds a bridge between kOS and kRPC. It allows kOS processors to send messages to kRPC clients and allows kRPC clients to send messages directly to kOS procesors.", 10 | "license" : "GPL-3.0", 11 | "release_status" : "testing", 12 | "resources" : { 13 | "homepage" : "http://forum.kerbalspaceprogram.com/index.php?/topic/142979-113", 14 | "repository" : "https://github.com/dewiniaid/ksp-kipc", 15 | "manual" : "https://github.com/dewiniaid/ksp-kipc/blob/master/doc/index.md" 16 | }, 17 | "install" : [ 18 | { 19 | "file": "GameData/KIPC", 20 | "install_to": "GameData" 21 | } 22 | ], 23 | "x_last_revision_by": "dewin", 24 | "depends": [ 25 | { "name": "kOS", "min_version" : "1.0.0" }, 26 | { "name": "kRPC" } 27 | ], 28 | "x_netkan_override": [ 29 | { 30 | "version": "v0.2.0-beta", 31 | "override": { "ksp_version_max": "1.1.99" } 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/KOS/KRPCConnection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | using kOS.Safe.Encapsulation; 7 | 8 | using KIPC.Serialization; 9 | 10 | namespace KIPC.KOS 11 | { 12 | /// 13 | /// Represents a KRPC connection. Placeholder. 14 | /// 15 | [kOS.Safe.Utilities.KOSNomenclature("KRPCConnection")] 16 | class KRPCConnection : kOS.Safe.Communication.Connection 17 | { 18 | public KRPCClient Client { get; private set; } 19 | private kOS.SharedObjects shared; 20 | public KRPCConnection(kOS.SharedObjects shared, KRPCClient client) 21 | { 22 | Client = client; 23 | this.shared = shared; 24 | } 25 | 26 | public override bool Connected { get; } = true; 27 | public override double Delay { get; } = 0; 28 | 29 | protected override Structure Destination() 30 | { 31 | return Client; 32 | } 33 | 34 | protected override BooleanValue SendMessage(Structure content) 35 | { 36 | KIPC.Addon.krpcMessageQueue.Enqueue(Serializer.WriteJson(shared, content)); 37 | return true; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /doc/kos.md: -------------------------------------------------------------------------------- 1 | # Using KIPC within kOS 2 | 3 | **[ [KIPC Overview](index.md) ] [ [kOS API](kos.md) ] [ [kRPC API](krpc.md) ] [ [Changelog](CHANGELOG.md) ] [ [License](LICENSE.md) ]** 4 | 5 | ## Supported data types 6 | All currently serializable data types should be supported; these are the same restrictions as what you can use when 7 | sending messages between processors or vessels. 8 | 9 | These types include simple types like `ScalarValue`, `Boolean` and `String`, most of the collection types 10 | (`Lexicon`, `List`, `Queue`, `Stack`), and some object references (`Vessel` and `Body`). `Vector` is currently 11 | supported, but `Direction` is not available in this build due to limitations within kOS. 12 | 13 | ## Sending Messages 14 | 15 | **ADDON:KIPC:CONNECTION** 16 | Returns a `KRPCConnection` that can be used to send messages to kRPC. This functions like a normal `Connection` 17 | within processors on the same vessel. 18 | 19 | ## Unstable/Developer API 20 | These are all mostly intended for the developer build; they may change or be removed at any time. 21 | 22 | **ADDON:KIPC:SERIALIZE(_content_)** 23 | 24 | Serializes _content_ and returns the result. 25 | 26 | **ADDON:KIPC:DESERIALIZE(_json_)** 27 | 28 | Deserializes _json_ and returns the result. 29 | 30 | **ADDON:KIPC:SEND(_vessel_, _content_)** 31 | Immediately sends a message to the target vessel, ignoring RemoteTech restrictions (if any). 32 | -------------------------------------------------------------------------------- /plugin/KIPC.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio 14 3 | VisualStudioVersion = 14.0.25123.0 4 | MinimumVisualStudioVersion = 10.0.40219.1 5 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{AC48674B-DA82-45FA-AEFF-96AD040C3974}" 6 | ProjectSection(SolutionItems) = preProject 7 | KIPC.version = KIPC.version 8 | KIPC.version.template = KIPC.version.template 9 | Postbuild.ps1 = Postbuild.ps1 10 | EndProjectSection 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KIPC", "KIPCPlugin\KIPC.csproj", "{FEBE111A-D442-48BF-90B3-9135B577A4F6}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {FEBE111A-D442-48BF-90B3-9135B577A4F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {FEBE111A-D442-48BF-90B3-9135B577A4F6}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {FEBE111A-D442-48BF-90B3-9135B577A4F6}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {FEBE111A-D442-48BF-90B3-9135B577A4F6}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/CollectionHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections; 3 | using KIPC.Extensions; 4 | 5 | namespace KIPC.Serialization 6 | { 7 | using JsonList = List; 8 | using JsonDict = Dictionary; 9 | using JsonKey = KeyValuePair; 10 | using IJsonList = IList; 11 | using IJsonDict = IDictionary; 12 | 13 | public interface ICollectionHandler 14 | { 15 | object ObjectId { get; set; } 16 | IEnumerable GetContainers(); 17 | IEnumerable GetContainers(IJsonDict source); 18 | } 19 | 20 | public abstract class CollectionHandler : TypeHandler, ICollectionHandler 21 | { 22 | 23 | public object ObjectId 24 | { 25 | get { return this.GetValueOrDefault("ref"); } 26 | set { this["ref"] = value; } 27 | } 28 | 29 | protected CollectionHandler(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 30 | 31 | /// 32 | /// Returns any lists that may contain nested objects in the serialized data. 33 | /// 34 | public virtual IEnumerable GetContainers() 35 | { 36 | return GetContainers(this); 37 | } 38 | 39 | public abstract IEnumerable GetContainers(IJsonDict source); 40 | } 41 | } -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/BodyHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using kOS.Suffixed; 3 | using KIPC.Util; 4 | using KIPC.Extensions; 5 | using System.Linq; 6 | using System.Collections; 7 | using System.Collections.Generic; 8 | namespace KIPC.Serialization 9 | { 10 | using JsonList = List; 11 | using JsonDict = Dictionary; 12 | using JsonKey = KeyValuePair; 13 | using IJsonList = IList; 14 | using IJsonDict = IDictionary; 15 | 16 | [Serializes(typeof(BodyTarget), "body")] 17 | public class BodyHandler : TypeHandler 18 | { 19 | public BodyHandler(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 20 | 21 | public static CelestialBody GetBodyById(int bodyId) 22 | { 23 | try 24 | { 25 | return FlightGlobals.Bodies[bodyId]; 26 | } 27 | catch (IndexOutOfRangeException) 28 | { 29 | throw new SerializationException("Provided body ID is invalid."); 30 | } 31 | } 32 | 33 | public override BodyTarget Deserialize(IJsonDict source) 34 | { 35 | EnsureValueIsType(source); 36 | int bodyId = (int)source["data"]; 37 | return new BodyTarget(GetBodyById(bodyId), serializer.SharedObjects); 38 | } 39 | 40 | public override TypeHandler Serialize(BodyTarget input) 41 | { 42 | this["data"] = input.Body.flightGlobalsIndex; 43 | return this; 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | namespace KIPC.Extensions { 4 | public static class DictionaryExtensions { 5 | /// 6 | /// Get a the value for a key. If the key does not exist, return null; 7 | /// 8 | /// The type of the keys in the dictionary. 9 | /// The type of the values in the dictionary. 10 | /// The dictionary to call this method on. 11 | /// The key to look up. 12 | /// The key value. null if this key is not in the dictionary. 13 | public static TValue GetValueOrDefault(this IDictionary dic, TKey key, TValue defaultValue = default(TValue)) 14 | { 15 | TValue result; 16 | return dic.TryGetValue(key, out result) ? result : defaultValue; 17 | } 18 | } 19 | 20 | public static class TypeExtensions 21 | { 22 | /// 23 | /// Counterpart to IsSubclassOf. Also returns true if the two types are the same type. This differs from IsAssignableFrom in that it compares actual types and ignores cases 24 | /// where a type supports assignment from another type that's not one of its subclasses. 25 | /// 26 | /// Parent type 27 | /// Possible child type 28 | /// True if the child and parent represent the same type or the child is a subclass of the parent. 29 | public static bool IsParentClassOf(this Type parent, Type child) 30 | { 31 | return child == parent || child.IsSubclassOf(parent); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ksp-kipc 2 | kIPC - Inter-Process(or) Communication for kOS and kRPC in KSP 3 | 4 | ## About 5 | 6 | KIPC (Kerbal Inter-Process Communication) provides a bridge between kOS and KRPC. Specifically, it adds a primitive 7 | messaging system that allows Kerboscript code (running in kOS) to communicate with outside programs using kRPC. 8 | 9 | ## Why not just use kOS? 10 | 11 | kOS is poorly suited to certain tasks, including complex calculations. The particular incentive to write this mod came 12 | about after attempting to make a kOS version of [AlexMoon's Launch Window Planner](http://alexmoon.github.io/ksp/) and 13 | 14 | Additionally, someone may already have a large kRPC-using project -- or sufficient experience with mainstream 15 | programming languages -- to prefer kRPC. 16 | 17 | ## Why not just use kRPC? 18 | 19 | kRPC introduces a small amount of latency in fine control of a craft, since messages go over a TCP/IP communication 20 | channel and KSP may have additional physics frames before a message to cut throttle is received. 21 | 22 | Additionally, someone whose first experience in programming comes from kOS may not want to have to start completely 23 | from scratch if they're inspired to start learning a mainstream programming language. 24 | 25 | ## Use Cases 26 | 27 | There's two main scenarios where I can see the bridge being useful, though others likely exist. 28 | 29 | * **kOS As Mission Control**: kOS handles the overall control of a particular vessel, with requests sent to kRPC for 30 | complex tasks like maneuver planning. 31 | * **kRPC as Mission Control**: kRPC handles the overall control of a particular vessel, with requests sent to kOS for 32 | real-time tasks like executing a planned maneuver. 33 | 34 | ## Documentation 35 | 36 | * [Overview and architecture](/doc/index.md) 37 | * [kOS API](/doc/kos.md) 38 | * [KRPC API](/doc/krpc.md) 39 | * [License](/doc/LICENSE.md) 40 | * [All documentation](/doc/) 41 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/SerializesAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace KIPC.Serialization 4 | { 5 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 6 | public class SerializesAttribute : Attribute 7 | { 8 | /// 9 | /// The Structure subclass that this serializer handles. 10 | /// 11 | public Type NativeType { get; private set; } 12 | 13 | /// 14 | /// The structure's identifier in data files. Must be unique. 15 | /// 16 | public object Identifier { get; private set; } 17 | 18 | /// 19 | /// The structure's friendly name. 20 | /// 21 | public string Name { get; private set; } 22 | 23 | /// 24 | /// In the event of multiple types matching a particular input, the lowest priority will take precedence. 25 | /// 26 | public int Priority { get; private set; } = 0; 27 | 28 | /// 29 | /// Create a new SimpleTypeSerializerAttribute 30 | /// 31 | /// Native type that this serialized from/deserializes to 32 | /// Friendly type name 33 | /// Priority in case multiple serializers match a given input. 34 | public SerializesAttribute(Type nativeType, string name, int priority = 0) : this(nativeType, name, name, priority) { } 35 | public SerializesAttribute(Type nativeType, object identifier, string name, int priority = 0) : base() 36 | { 37 | this.NativeType = nativeType; 38 | this.Identifier = identifier; 39 | this.Name = name; 40 | this.Priority = priority; 41 | } 42 | public SerializesAttribute() : base() { } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("KIPC")] 9 | [assembly: AssemblyDescription("KSP IPC plugin - bridge between kOS and kRPC")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Next Phase Technologies")] 12 | [assembly: AssemblyProduct("KIPC")] 13 | [assembly: AssemblyCopyright("Copyright © 2016 Daniel J Grace a.k.a. dewin - Licensed GPLv3")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("febe111a-d442-48bf-90b3-9135b577a4f6")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("0.2.0.0")] 36 | [assembly: AssemblyFileVersion("0.2.0.1")] 37 | 38 | [assembly: KSPAssembly("KIPC", 0, 2)] 39 | [assembly: KSPAssemblyDependency("kOS", 0, 0)] 40 | [assembly: KSPAssemblyDependency("KRPC", 0, 0)] 41 | [assembly: KSPAssemblyDependency("KRPC.SpaceCenter", 0, 0)] 42 | 43 | // This is the default value for ck.stamp.fody, but explicitly defining it means that our own code won't break if 44 | // ck.stamp.fody isn't present. 45 | [assembly: AssemblyInformationalVersion("%ck-standard%")] 46 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Addon.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Reflection; 6 | using KSP; 7 | using UnityEngine; 8 | 9 | using System.IO; 10 | using JsonFx; 11 | 12 | 13 | namespace KIPC 14 | { 15 | [KSPAddon(KSPAddon.Startup.Instantly, true)] 16 | public class Addon : MonoBehaviour 17 | { 18 | public static Queue krpcMessageQueue = new Queue(); 19 | void Start() 20 | { 21 | DontDestroyOnLoad(this); 22 | Debug.Log("[KIPCPlugin] Hello, Solar System!"); 23 | 24 | GameEvents.onLevelWasLoaded.Add(this.OnLevelWasLoaded); 25 | } 26 | 27 | void OnLevelWasLoaded(GameScenes scene) 28 | { 29 | if(scene == GameScenes.MAINMENU) 30 | { 31 | krpcMessageQueue.Clear(); 32 | // Handle the queue? 33 | } 34 | 35 | } 36 | 37 | 38 | } 39 | 40 | [KSPScenario(ScenarioCreationOptions.AddToAllGames, new GameScenes[] { GameScenes.FLIGHT })] 41 | public class KIPCPluginData : ScenarioModule 42 | { 43 | public static System.Runtime.Serialization.ObjectIDGenerator idgen = new System.Runtime.Serialization.ObjectIDGenerator(); 44 | public override void OnAwake() 45 | { 46 | bool dummy; 47 | base.OnAwake(); 48 | Debug.Log(string.Format("[KIPCPlugin] {0} PersistentState OnAwake()", idgen.GetId(this, out dummy))); 49 | } 50 | public override void OnSave(ConfigNode node) 51 | { 52 | bool dummy; 53 | node.ClearNodes(); 54 | ConfigNode child = node.AddNode("MESSAGEQUEUE"); 55 | foreach(string message in Addon.krpcMessageQueue) 56 | { 57 | child.AddValue("message", message); 58 | Debug.Log("Saved message " + message); 59 | } 60 | base.OnSave(node); 61 | Debug.Log(string.Format("[KIPCPlugin] {0} PersistentState OnSave()", idgen.GetId(this, out dummy))); 62 | } 63 | public override void OnLoad(ConfigNode node) 64 | { 65 | Addon.krpcMessageQueue.Clear(); 66 | bool dummy; 67 | ConfigNode child = node.GetNode("MESSAGEQUEUE"); 68 | if(child != null) { 69 | foreach(string message in child.GetValues("message")) 70 | { 71 | Addon.krpcMessageQueue.Enqueue(message); 72 | Debug.Log("Queued message " + message); 73 | } 74 | } 75 | 76 | base.OnLoad(node); 77 | Debug.Log(string.Format("[KIPCPlugin] {0} PersistentState OnLoad()", idgen.GetId(this, out dummy))); 78 | } 79 | 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/KOS/Addon.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.Serialization; 5 | 6 | using UnityEngine; 7 | 8 | using kOS; 9 | using kOS.AddOns; 10 | using kOS.Safe.Encapsulation; 11 | using kOS.Safe.Encapsulation.Suffixes; 12 | using kOS.Suffixed; 13 | using kOS.Suffixed.PartModuleField; 14 | using kOS.Communication; 15 | 16 | using KIPC.Serialization; 17 | 18 | 19 | 20 | namespace KIPC.KOS 21 | { 22 | /// 23 | /// Implements the kOS-level addon. 24 | /// 25 | [kOSAddon("KIPC")] 26 | [kOS.Safe.Utilities.KOSNomenclature("KIPC")] 27 | public class Addon : kOS.Suffixed.Addon 28 | { 29 | private SharedObjects sharedObjects; 30 | private KRPCClient client; 31 | private KRPCConnection connection; 32 | 33 | public Addon(SharedObjects shared) : base(shared) 34 | { 35 | sharedObjects = shared; 36 | client = new KRPCClient(shared); 37 | connection = new KRPCConnection(shared, client); 38 | 39 | InitializeSuffixes(); 40 | } 41 | 42 | private void InitializeSuffixes() 43 | { 44 | AddSuffix("SERIALIZE", new OneArgsSuffix(Serialize, "Encodes a value for messaging. Unstable API.")); 45 | AddSuffix("DESERIALIZE", new OneArgsSuffix(Deserialize, "Deserializes an encoded message. Unstable API.")); 46 | AddSuffix("CONNECTION", new StaticSuffix(() => this.connection, "Returns the Connection representing all connected KRPC Clients.")); 47 | AddSuffix("SEND", new TwoArgsSuffix(SendImmediate, "Immediately send a message to the specified target. Developer API.")); 48 | } 49 | 50 | private BooleanValue SendImmediate(VesselTarget target, Structure content) 51 | { 52 | double sentAt = Planetarium.GetUniversalTime(); 53 | double receivedAt = sentAt; 54 | Message message = Message.Create(content, sentAt, receivedAt, new VesselTarget(shared), shared.Processor.Tag); 55 | MessageQueueStructure queue = InterVesselManager.Instance.GetQueue(target.Vessel, shared); 56 | queue.Push(message); 57 | return true; 58 | } 59 | 60 | private StringValue Serialize(Structure input) 61 | { 62 | return new StringValue(Serializer.WriteJson(sharedObjects, input)); 63 | } 64 | 65 | private Structure Deserialize(StringValue input) 66 | { 67 | return (Structure)Serializer.ReadJson(sharedObjects, input); 68 | } 69 | 70 | public override BooleanValue Available() 71 | { 72 | return true; 73 | } 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/VesselHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using kOS.Suffixed; 3 | using KIPC.Util; 4 | using KIPC.Extensions; 5 | using System.Linq; 6 | using System.Collections; 7 | using System.Collections.Generic; 8 | 9 | 10 | namespace KIPC.Serialization 11 | { 12 | using JsonList = List; 13 | using JsonDict = Dictionary; 14 | using JsonKey = KeyValuePair; 15 | using IJsonList = IList; 16 | using IJsonDict = IDictionary; 17 | 18 | [Serializes(typeof(VesselTarget), "vessel")] 19 | public class VesselHandler : TypeHandler 20 | { 21 | // Remember the last ~10 or so vessels we've looked up. 22 | protected static CacheDictionary vesselCache = new CacheDictionary(10); 23 | 24 | public VesselHandler(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 25 | 26 | public static Vessel GetVesselById(Guid id, bool useCache = true) 27 | { 28 | // Fast resolve if it's the active vessel, which is probably the most likely case. 29 | if (FlightGlobals.ActiveVessel != null && FlightGlobals.ActiveVessel.id == id) 30 | { 31 | return FlightGlobals.ActiveVessel; 32 | } 33 | 34 | // Check cache. 35 | if (useCache) 36 | { 37 | var item = vesselCache.GetValueOrDefault(id, null); 38 | if (item != null) 39 | { 40 | if (item.IsAlive) return (Vessel)item.Target; 41 | vesselCache.Remove(id); 42 | } 43 | } 44 | 45 | Vessel vessel = FlightGlobals.Vessels.Find(v => v.id == id); 46 | if (vessel != null && useCache) 47 | { 48 | vesselCache[id] = new WeakReference(vessel); 49 | } 50 | return vessel; 51 | } 52 | 53 | public override VesselTarget Deserialize(IJsonDict source) 54 | { 55 | EnsureValueIsType(source); 56 | Guid vesselId; 57 | try 58 | { 59 | vesselId = new Guid((string)source["data"]); 60 | } 61 | catch (Exception ex) 62 | { 63 | throw new SerializationException("Provided vessel GUID is invalid.", ex); 64 | } 65 | Vessel vessel = GetVesselById(vesselId); 66 | if (vessel == null) return null; // kOS won't really like this, but meh. 67 | return new VesselTarget(vessel, serializer.SharedObjects); 68 | } 69 | 70 | public override TypeHandler Serialize(VesselTarget input) 71 | { 72 | this["data"] = input.Vessel.id.ToString(); 73 | return this; 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /doc/index.md: -------------------------------------------------------------------------------- 1 | # KIPC Overview 2 | 3 | **[ [KIPC Overview](index.md) ] [ [kOS API](kos.md) ] [ [kRPC API](krpc.md) ] [ [Changelog](CHANGELOG.md) ] [ [License](LICENSE.md) ]** 4 | 5 | ## About 6 | 7 | KIPC (Kerbal Inter-Process Communication) provides a bridge between kOS and KRPC. Specifically, it adds the ability 8 | to send messages from kOS to KIPC using a mechanism simpilar to the communications mechanisms added in kOS 1.0.0 9 | 10 | ## Why not just use kOS? 11 | 12 | kOS is poorly suited to certain tasks, including complex calculations. It also lacks certain visualization 13 | capabilities that can be tapped into using kIPC. The particular incentive to write this mod came about after 14 | attempting to make a kOS version of [AlexMoon's Launch Window Planner](http://alexmoon.github.io/ksp/) and 15 | encountering unreasonably long delays while attempting to compute something similar to a porkchop plot. 16 | 17 | Additionally, someone may already have a large kRPC-using project -- or sufficient experience with mainstream 18 | programming languages -- to prefer kRPC. 19 | 20 | ## Why not just use kRPC? 21 | 22 | kRPC introduces a small amount of latency in fine control of a craft, since messages go over a TCP/IP communication 23 | channel and KSP may have additional physics frames before a message to cut throttle is received. 24 | 25 | Additionally, someone whose first experience in programming comes from kOS may not want to have to start completely 26 | from scratch if they're inspired to start learning a mainstream programming language. 27 | 28 | ## Use Cases 29 | 30 | Here's a few scenarios where the combination of kRPC and kOS can be useful. You can probably think of some more. 31 | 32 | * **kOS As Mission Control**: kOS handles the overall control of a particular vessel, with requests sent to kRPC for 33 | complex tasks like maneuver planning. 34 | * **kRPC as Mission Control**: kRPC handles the overall control of a particular vessel, with requests sent to kOS for 35 | real-time tasks like executing a planned maneuver. 36 | * **kRPC for user input**: Display a rudimentary user interface in a kRPC client which then relays interface 37 | selections back to kOS. 38 | * **kRPC for data visualization**: Let kOS fly while kRPC renders pretty graphs in realtime. 39 | 40 | ## Architecture 41 | 42 | From kOS's perspective, `addons:kipc:connection` functions similar to a connection another `kOSProcessor` on the 43 | same vessel. Messages can be sent to that connection. 44 | 45 | On the kRPC side, KIPC adds a `KIPC` service which provides mechanisms to get information about `kOSProcessors` 46 | and send messages to them. The KIPC service also provides procedures for retrieving the next message in the message 47 | queue and some limited kOS control (like toggling power or visibility of the terminal) 48 | 49 | Messages are represented as JSON in KRPC. Complex types all have a simple format that describes what the type is and 50 | the data it contains -- this includes collections (lists, stacks, queues and lexicons/dicts) as well as references to 51 | vessels, celestial bodies and vectors. 52 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/ListHandlers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using kOS.Safe.Encapsulation; 6 | using System.Reflection; 7 | 8 | namespace KIPC.Serialization 9 | { 10 | using JsonList = List; 11 | using JsonDict = Dictionary; 12 | using JsonKey = KeyValuePair; 13 | using IJsonList = IList; // ; 14 | using IJsonDict = IDictionary; 15 | 16 | 17 | // Lists, stacks, and queues are mostly the same. 18 | public abstract class BaseListHandler : CollectionHandler 19 | where TCollection : IEnumerable 20 | { 21 | static ConstructorInfo factory = typeof(TCollection).GetConstructor(new Type[0]); 22 | ConstructorInfo Factory { get { return BaseListHandler.factory; } } 23 | 24 | public BaseListHandler(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 25 | 26 | public override IEnumerable GetContainers(IJsonDict source) 27 | { 28 | EnsureValueIsType(source); 29 | return new List{ (IJsonList)source["data"] }; 30 | } 31 | 32 | public override TypeHandler Serialize(TCollection input) 33 | { 34 | this["data"] = input.Select(v => serializer.Serialize(v)).ToList(); 35 | return this; 36 | } 37 | 38 | protected abstract void AddItems(TCollection result, IEnumerable items); 39 | 40 | public override TCollection Deserialize(IJsonDict source) 41 | { 42 | EnsureValueIsType(source); 43 | TCollection result = (TCollection) Factory.Invoke(new object[0]); 44 | serializer.deserializerState.results[source] = result; 45 | 46 | AddItems( 47 | result, 48 | ((IJsonList)source["data"]).Cast().Select(element => (TItem)(serializer.Deserialize(element))) 49 | ); 50 | return result; 51 | } 52 | } 53 | 54 | [Serializes(typeof(ListValue), "list")] 55 | public class SerializedList : BaseListHandler 56 | { 57 | public SerializedList(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 58 | 59 | protected override void AddItems(ListValue result, IEnumerable items) 60 | { 61 | foreach(var item in items) { result.Add(item); } 62 | } 63 | } 64 | 65 | [Serializes(typeof(QueueValue), "queue")] 66 | public class SerializedQueue : BaseListHandler 67 | { 68 | public SerializedQueue(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 69 | 70 | protected override void AddItems(QueueValue result, IEnumerable items) 71 | { 72 | foreach(var item in items) { result.Push(item); } 73 | } 74 | } 75 | 76 | [Serializes(typeof(StackValue), "stack")] 77 | public class SerializedStack : BaseListHandler 78 | { 79 | public SerializedStack(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 80 | 81 | protected override void AddItems(StackValue result, IEnumerable items) 82 | { 83 | foreach (var item in items) { result.Push(item); } 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/LexiconHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Runtime.Serialization; 6 | 7 | using UnityEngine; 8 | 9 | using kOS.Safe.Encapsulation; 10 | using kOS.Suffixed; 11 | 12 | using JsonFx.Json; 13 | using JsonFx.Bson; 14 | 15 | using KIPC.Extensions; 16 | 17 | namespace KIPC.Serialization 18 | { 19 | using JsonList = List; 20 | using JsonDict = Dictionary; 21 | using JsonKey = KeyValuePair; 22 | using IJsonList = IList; 23 | using IJsonDict = IDictionary; 24 | using System.Collections; 25 | 26 | [Serializes(typeof(Lexicon), "dict")] 27 | public class LexiconHandler : CollectionHandler 28 | { 29 | public LexiconHandler(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 30 | 31 | protected void Validate(IJsonDict source) 32 | { 33 | EnsureValueIsType(source, "data"); 34 | EnsureValueIsType(source, "keys"); 35 | EnsureValueIsType(source, "values"); 36 | EnsureValueIsType(source, "sensitive", mustExist: false); 37 | } 38 | 39 | public override Lexicon Deserialize(IJsonDict source) 40 | { 41 | Validate(source); 42 | bool caseSensitive = (bool)source.GetValueOrDefault("sensitive", false); 43 | var data = (IJsonDict)source["data"]; 44 | var keys = (IJsonList)source["keys"]; 45 | var values = (IJsonList)source["values"]; 46 | if (keys.Count != values.Count) 47 | { 48 | throw new SerializationException("Dict must have the same number of values as it has keys."); 49 | } 50 | var output = new Lexicon(); 51 | output.SetSuffix("CASESENSITIVE", caseSensitive); 52 | serializer.deserializerState.results[source] = output; 53 | data.Select(kvp => output[(Structure)serializer.Deserialize(kvp.Key)] = (Structure)serializer.Deserialize(kvp.Value)); 54 | 55 | foreach (var kvp in data.Select(x => new KeyValuePair((Structure)serializer.Deserialize(x.Key), (Structure)serializer.Deserialize(x.Value)))) 56 | { 57 | output[kvp.Key] = kvp.Value; 58 | } 59 | return output; 60 | } 61 | 62 | public override TypeHandler Serialize(Lexicon input) 63 | { 64 | var data = new JsonDict(); 65 | var keys = new JsonList(); 66 | var values = new JsonList(); 67 | foreach (var kvp in input.Select(x => new KeyValuePair(serializer.Serialize(x.Key), serializer.Serialize(x.Value)))) 68 | { 69 | if (kvp.Key is string) 70 | { 71 | data[(string)kvp.Key] = kvp.Value; 72 | } 73 | else 74 | { 75 | keys.Add(kvp.Key); 76 | values.Add(kvp.Value); 77 | } 78 | } 79 | this["data"] = data; 80 | this["keys"] = keys; 81 | this["values"] = values; 82 | if ((BooleanValue)input.GetSuffix("CASESENSITIVE").Value) 83 | { 84 | this["sensitive"] = true; 85 | } 86 | else 87 | { 88 | this.Remove("sensitive"); 89 | } 90 | return this; 91 | } 92 | 93 | public override IEnumerable GetContainers(IJsonDict source) 94 | { 95 | this.Validate(source); 96 | var result = new List(3); 97 | if (source.ContainsKey("data")) result.Add((IJsonDict)source["data"]); 98 | if (source.ContainsKey("keys")) result.Add((IJsonList)source["keys"]); 99 | if (source.ContainsKey("values")) result.Add((IJsonList)source["values"]); 100 | return result; 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/GeometryHandlers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using kOS.Suffixed; 5 | using KIPC.Extensions; 6 | using System.Linq; 7 | using UnityEngine; 8 | 9 | namespace KIPC.Serialization 10 | { 11 | using JsonList = List; 12 | using JsonDict = Dictionary; 13 | using JsonKey = KeyValuePair; 14 | using IJsonList = IList; 15 | using IJsonDict = IDictionary; 16 | 17 | public abstract class GeometryHandler : TypeHandler 18 | { 19 | public GeometryHandler(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 20 | 21 | protected List GetElements(IJsonDict source, int numElements = 0) 22 | { 23 | EnsureValueIsType(source); 24 | IJsonList value = (IJsonList) source["data"]; 25 | if(numElements != 0 && value.Count != numElements) 26 | { 27 | throw new SerializationException( 28 | string.Format( 29 | "{0} object: Expected data field to contain {1} elements, but it contained {2} instead.", 30 | this.info.Name, numElements, value.Count 31 | ) 32 | ); 33 | } 34 | try 35 | { 36 | return value.Cast().ToList(); 37 | } catch(InvalidCastException) { 38 | throw new SerializationException(string.Format("{0} object: All elements of data must be numeric values.", info.Name)); 39 | } 40 | } 41 | } 42 | 43 | [Serializes(typeof(Vector), "vector")] 44 | public class SerializedVector : GeometryHandler 45 | { 46 | public SerializedVector(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 47 | 48 | public override Vector Deserialize(IJsonDict source) 49 | { 50 | var elements = GetElements(source, 3); 51 | return new Vector(elements[0], elements[1], elements[2]); 52 | } 53 | 54 | public override TypeHandler Serialize(Vector input) 55 | { 56 | this["data"] = new JsonList { input.X, input.Y, input.Z }; 57 | return this; 58 | } 59 | } 60 | 61 | /// 62 | /// TODO: Better Quaternion support. 63 | /// 64 | [Serializes(typeof(Direction), "direction")] 65 | public class SerializedDirection : GeometryHandler 66 | { 67 | public SerializedDirection(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 68 | 69 | public override Direction Deserialize(IJsonDict source) 70 | { 71 | EnsureValueIsType(source, "from", false, true); 72 | string directionType = (string)source.GetValueOrDefault("from", null); 73 | int numElements = 0; 74 | switch (directionType) 75 | { 76 | case null: 77 | break; 78 | case "quaternion": 79 | numElements = 4; 80 | break; 81 | case "euler": 82 | case "vector": 83 | numElements = 3; 84 | break; 85 | default: 86 | throw new SerializationException(string.Format("{0} object: 'from' must be one of (\"quaternioun\", \"euler\", \"vector\", or null).", info.Name)); 87 | } 88 | var elements = GetElements(source, numElements); 89 | switch (elements.Count) 90 | { 91 | case 3: // From Euler angles (default) or vector (explicit) 92 | return new Direction(new Vector3d(elements[0], elements[1], elements[2]), directionType != "vector"); 93 | case 4: // Quaternion 94 | return new Direction(new QuaternionD(elements[0], elements[1], elements[2], elements[3])); 95 | default: 96 | throw new SerializationException(string.Format("{0} object: data field must contain exactly 3 or 4 elements.", info.Name)); 97 | } 98 | } 99 | 100 | public override TypeHandler Serialize(Direction input) 101 | { 102 | this["data"] = new JsonList { input.Euler.x, input.Euler.y, input.Euler.z }; 103 | return this; 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/TypeRegistry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Runtime.Serialization; 4 | using System.Reflection; 5 | using System.Linq; 6 | 7 | using UnityEngine; 8 | 9 | using KIPC.Extensions; 10 | 11 | namespace KIPC.Serialization 12 | { 13 | /// 14 | /// Keeps track of which TypeHandler/TypeSerializerAttributes handle which things. 15 | /// 16 | public class TypeRegistry 17 | { 18 | /// 19 | /// List of all type serializers in priority order. 20 | /// 21 | protected List typeSerializers; 22 | 23 | /// Mapping of type identifiers to serializers. 24 | protected Dictionary serializersByIdentifier = null; 25 | 26 | /// Cache of Types to serializers. 27 | protected Util.CacheDictionary serializerCache = null; 28 | 29 | public TypeRegistry() 30 | { 31 | RefreshTypeData(); 32 | } 33 | 34 | public void RefreshTypeData() 35 | { 36 | var typeSerializers = new List(); 37 | var byIdentifier = new Dictionary(); 38 | var serializerCache = new Util.CacheDictionary(); 39 | TypeSerializer ts; 40 | 41 | foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => typeof(TypeHandler).IsAssignableFrom(t))) 42 | { 43 | foreach (SerializesAttribute attr in type.GetCustomAttributes(typeof(SerializesAttribute), false)) 44 | { 45 | Debug.Log(string.Format("[KIPCPlugin] Registering type serializer '{0}' with identifier {1}, handled by {2} for items of type {3}", attr.Name, attr.Identifier, type.FullName, attr.NativeType.FullName)); 46 | ts = new TypeSerializer(attr, type); 47 | if (byIdentifier.ContainsKey(attr.Identifier)) 48 | { 49 | throw new InvalidOperationException( 50 | string.Format("More than one serializer references the type identifier {0}. This is most certainly not supposed to happen. Please report this bug.", attr.Identifier) 51 | ); 52 | } 53 | if (serializerCache.ContainsKey(ts.NativeType)) 54 | { 55 | throw new InvalidOperationException( 56 | string.Format("More than one serializer references the native type identifier {0}. This is most certainly not supposed to happen. Please report this bug.", ts.NativeType.FullName) 57 | ); 58 | } 59 | typeSerializers.Add(ts); 60 | serializerCache[ts.NativeType] = ts; 61 | byIdentifier[ts.Identifier] = ts; 62 | } 63 | } 64 | serializerCache.MaxSize = 3 * typeSerializers.Count; // Arbitrary multiplier. Should handle various subclasses and such, without growing infinitely if something creates a ton of dynamic types. 65 | typeSerializers.Sort(); // Sort in priority order. 66 | Debug.LogWarning(string.Format("[KIPCPlugin] Registered {0} serializer(s)", typeSerializers.Count)); 67 | 68 | this.typeSerializers = typeSerializers; 69 | this.serializersByIdentifier = byIdentifier; 70 | this.serializerCache = serializerCache; 71 | } 72 | 73 | public TypeSerializer GetDeserializer(object identifier) 74 | { 75 | try 76 | { 77 | return serializersByIdentifier[identifier]; 78 | } 79 | catch (KeyNotFoundException) 80 | { 81 | throw new SerializationException(string.Format("No deserializer is defined for object class {0}", identifier)); 82 | } 83 | } 84 | 85 | public TypeSerializer GetSerializer(object instance) 86 | { 87 | var type = instance.GetType(); 88 | TypeSerializer result; 89 | if (serializerCache.TryGetValue(type, out result)) 90 | { 91 | if (result != null) return result; 92 | } 93 | else 94 | { 95 | result = typeSerializers.Find(x => x.NativeType.IsParentClassOf(type)); 96 | serializerCache[type] = result; 97 | } 98 | if (result == null) 99 | { 100 | throw new SerializationException(string.Format("No serializer is defined for native type {0}", type.FullName)); 101 | } 102 | return result; 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/KRPC/Processor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | using KRPC.Service.Attributes; 7 | using KRPC.Utils; 8 | using kOS.Module; 9 | using kOS.Safe.Encapsulation; 10 | using kOS.Safe.Module; 11 | using global::KRPC.SpaceCenter; 12 | 13 | 14 | namespace KIPC.KRPC 15 | { 16 | using Part = global::KRPC.SpaceCenter.Services.Parts.Part; 17 | 18 | /// 19 | /// Used to properly deserialize messages. 20 | /// 21 | /// To play with kOS's message API, we unfortunately have to deserialize message data, and then send it to Message.Create() which serializes it AGAIN only for kOS to deserialize it. 22 | /// Hopefully we'll be able to fix that at some point. 23 | /// 24 | public class JsonMessageProxy : kOS.Communication.InterProcCommand 25 | { 26 | string json; 27 | public JsonMessageProxy(string json) 28 | { 29 | this.json = json; 30 | } 31 | 32 | public override void Execute(kOS.SharedObjects shared) 33 | { 34 | kOSProcessor processor = shared.Processor as kOSProcessor; 35 | if(processor == null) { throw new ArgumentException("Processor is not a kOSProcessor"); } 36 | processor.Send((Structure) KIPC.Serialization.Serializer.ReadJson(shared, json)); 37 | } 38 | } 39 | 40 | /// 41 | /// A kOSProcessor. 42 | /// 43 | [KRPCClass(Service = Service.SERVICE_NAME)] 44 | public class Processor : Equatable 45 | { 46 | readonly kOSProcessor processor; 47 | 48 | internal static bool Is(Part part) 49 | { 50 | return part.InternalPart.Modules.OfType().Any(); 51 | } 52 | 53 | internal Processor(Part part) 54 | { 55 | Part = part; 56 | processor = part.InternalPart.Modules.OfType().FirstOrDefault(); // We expect this to always 57 | if (processor == null) throw new ArgumentException("Part is not a kOS Processor"); 58 | } 59 | 60 | internal Processor(kOSProcessor processor) 61 | { 62 | this.processor = processor; 63 | Part = new Part(this.processor.part); 64 | } 65 | 66 | public static explicit operator Processor(kOSProcessor processor) 67 | { 68 | return new Processor(processor); 69 | } 70 | 71 | /// 72 | /// Returns true if the objects are equal. 73 | /// 74 | public override bool Equals(Processor other) 75 | { 76 | return !ReferenceEquals(other, null) && Part == other.Part && processor == other.processor; 77 | } 78 | 79 | /// 80 | /// Hash code for the object. 81 | /// 82 | public override int GetHashCode() 83 | { 84 | return Part.GetHashCode() ^ processor.GetHashCode(); 85 | } 86 | 87 | /// 88 | /// The part object for this kOSProcessor 89 | /// 90 | [KRPCProperty] 91 | public Part Part { get; private set; } 92 | 93 | /// 94 | /// Total disk space 95 | /// 96 | [KRPCProperty] 97 | public int DiskSpace { get { return processor.diskSpace; } } 98 | 99 | /// 100 | /// Returns or sets whether the processor is currently turned on. Note that power-starved still counts as turned on. 101 | /// Can be set to change the processor's power state. 102 | /// 103 | [KRPCProperty] 104 | public bool Powered 105 | { 106 | get { return processor.ProcessorMode != ProcessorModes.OFF; } 107 | set { if(value != Powered) { processor.TogglePower(); } } 108 | } 109 | 110 | /// 111 | /// Returns or sets whether the terminal is currently turned visible. 112 | /// 113 | [KRPCProperty] 114 | public bool TerminalVisible 115 | { 116 | get { return processor.WindowIsOpen(); } 117 | set { if (value) processor.OpenWindow(); else processor.CloseWindow(); } 118 | } 119 | 120 | /// 121 | /// Sends a message to the specified kOS Processor which it can receive using kOS's inter-processor communication system. 122 | /// 123 | /// JSON message content formatted according to our allowing format. 124 | /// Whether the message was successfully sent. 125 | [KRPCMethod] 126 | public bool SendMessage(string json) 127 | { 128 | processor.ExecuteInterProcCommand(new JsonMessageProxy(json)); 129 | return true; 130 | } 131 | } 132 | } -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/TypeSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using UnityEngine; 4 | 5 | namespace KIPC.Serialization 6 | { 7 | public class TypeSerializer: IComparable 8 | { 9 | /// 10 | /// Underlying Attribute that we were created off of. 11 | /// 12 | public SerializesAttribute Attribute { get; private set; } 13 | 14 | /// 15 | /// The Structure subclass that this serializer handles. 16 | /// 17 | public Type NativeType { get; private set; } 18 | 19 | /// 20 | /// The structure's identifier in data files. Must be unique. 21 | /// 22 | public object Identifier { get; set; } 23 | 24 | /// 25 | /// The structure's friendly name. 26 | /// 27 | public string Name { get { return Attribute.Name; } } 28 | 29 | /// 30 | /// In the event of multiple types matching a particular input, the lowest priority will take precedence. 31 | /// 32 | public int Priority { get; set; } = 0; 33 | 34 | /// 35 | /// The Type of the class that handles actual serialization. 36 | /// 37 | public Type HandlerType { get; private set; } 38 | 39 | /// 40 | /// Factory method that actually creates an instance of HandlerType. 41 | /// 42 | public System.Reflection.ConstructorInfo Factory { get; private set; } 43 | 44 | public System.Reflection.MethodInfo SerializeMethod { get; private set; } 45 | public System.Reflection.MethodInfo DeserializeMethod { get; private set; } 46 | 47 | /// 48 | /// Signature for factory method (usually a constructor) 49 | /// 50 | static private Type[] factorySignature = { typeof(TypeSerializer), typeof(Serializer) }; 51 | 52 | public TypeSerializer(SerializesAttribute attribute, Type handlerType) 53 | { 54 | if (attribute == null) throw new ArgumentNullException("attribute"); 55 | if (handlerType == null) throw new ArgumentNullException("handler"); 56 | Type[] typeArgs = { attribute.NativeType }; 57 | 58 | // Handle generics 59 | if (handlerType.IsGenericTypeDefinition) 60 | { 61 | handlerType = handlerType.MakeGenericType(typeArgs); 62 | } 63 | 64 | if(!typeof(TypeHandler).IsAssignableFrom(handlerType)) 65 | { 66 | throw new ArgumentException("Specified type is not a TypeHandler", "handler"); 67 | } 68 | var factory = handlerType.GetConstructor(factorySignature); 69 | if(factory == null) { 70 | throw new ArgumentException("Specified handler type lacks a public constructor matching the required signature.", "handler"); 71 | } 72 | var serializeMethod = handlerType.GetMethod("Serialize", typeArgs); 73 | if (serializeMethod == null) 74 | { 75 | throw new ArgumentException("Specified handler type lacks an appropriate serializer method", "handler"); 76 | } 77 | var deserializeMethod = handlerType.GetMethod("Deserialize"); 78 | if (deserializeMethod == null) 79 | { 80 | throw new ArgumentException("Specified handler type lacks an appropriate deserializer method", "handler"); 81 | } 82 | 83 | // It's terribly written code sir, but it checks out. 84 | Attribute = attribute; 85 | NativeType = attribute.NativeType; 86 | Identifier = attribute.Identifier; 87 | Priority = attribute.Priority; 88 | HandlerType = handlerType; 89 | Factory = factory; 90 | SerializeMethod = serializeMethod; 91 | DeserializeMethod = deserializeMethod; 92 | } 93 | 94 | public TypeHandler CreateHandler(Serializer serializer) 95 | { 96 | object[] args = { this, serializer }; 97 | TypeHandler result = (TypeHandler)Factory.Invoke(args); 98 | result.DeserializeMethod = DeserializeMethod; 99 | result.SerializeMethod = SerializeMethod; 100 | return result; 101 | } 102 | public int CompareTo(object obj) 103 | { 104 | var other = obj as TypeSerializer; 105 | if (other == null) 106 | { 107 | //Debug.LogWarning("[KIPCPlugin] TypeSerializer: Attempted comparison against NULL!"); 108 | throw new ArgumentNullException(); 109 | } 110 | //Debug.Log(String.Format("Our priority is: {0}. Other priority is {1}", Priority, other.Priority)) 111 | int result = Priority.CompareTo(other.Priority); 112 | if (result == 0) return Name.CompareTo(other.Name); 113 | return result; 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Util/CountingIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace KIPC.Util 8 | { 9 | /// 10 | /// Handles an Indexing Enumerator, which wraps a regular enumerator as if it was a DictionaryIterator using an autoincrementing count as the index. 11 | /// 12 | public struct CountingIterator : IDictionaryEnumerator 13 | { 14 | /// 15 | /// Stores the actual enumerator we have wrapped. 16 | /// 17 | public IEnumerator wrappedEnumerator; 18 | 19 | /// 20 | /// The start value for this CountingIterator. 21 | /// 22 | public int start; 23 | 24 | /// 25 | /// Whether we've started the count yet. MoveNext() checks this every call; if false it sets it to true and resets index to start. 26 | /// 27 | private bool started; 28 | 29 | /// 30 | /// Current position. 31 | /// 32 | private int index; 33 | 34 | /// 35 | /// Creates a CountingIterator that wraps the specified enumerator with the specified start value. 36 | /// 37 | /// Enumerator to wrap 38 | /// Start index 39 | public CountingIterator(IEnumerator wrappedEnumerator, int start = 0) 40 | { 41 | this.wrappedEnumerator = wrappedEnumerator; 42 | this.start = 0; 43 | this.started = false; 44 | this.index = -1; 45 | } 46 | 47 | /// 48 | /// Returns the current entry. 49 | /// 50 | public object Current { get { return Entry; } } 51 | 52 | /// 53 | /// Returns the current entry. 54 | /// 55 | public DictionaryEntry Entry 56 | { 57 | get { 58 | var value = Value; // Rely on this triggering an exception if one needs to be triggered. 59 | return new DictionaryEntry(index, value); 60 | } 61 | } 62 | 63 | /// 64 | /// Returns the current key (index value). 65 | /// 66 | public object Key 67 | { 68 | get 69 | { 70 | var value = Value; // Rely on this triggering an exception if one needs to be triggered. 71 | return index; 72 | } 73 | } 74 | 75 | /// 76 | /// Returns the wrapped enumerator's current value 77 | /// 78 | public object Value { 79 | get 80 | { 81 | return wrappedEnumerator.Current; 82 | } 83 | } 84 | 85 | /// 86 | /// Advances to the next entry. 87 | /// 88 | public bool MoveNext() 89 | { 90 | bool result = wrappedEnumerator.MoveNext(); 91 | if (!started) 92 | { 93 | started = true; 94 | index = start; 95 | } else 96 | { 97 | ++index; 98 | } 99 | return result; 100 | } 101 | 102 | /// 103 | /// Reset the iterator. 104 | /// 105 | public void Reset() 106 | { 107 | wrappedEnumerator.Reset(); 108 | started = false; 109 | } 110 | 111 | /// 112 | /// Wraps the specified IEnumerable's enumerator. 113 | /// 114 | /// Enumerable to wrap. 115 | /// IEnumerable.GetEnumerator() if it is a IDictionaryEnumerator, otherwise the wrapped iterator. 116 | public static IEnumerator GetKeyedEnumerator(IEnumerable enumerable) { 117 | var e = enumerable.GetEnumerator(); 118 | if (e is IDictionaryEnumerator) return e; 119 | return new CountingIterator(e); 120 | } 121 | 122 | private struct CountingProxy : IEnumerable 123 | { 124 | private IEnumerable e; 125 | internal CountingProxy(IEnumerable e) { this.e = e; } 126 | public IEnumerator GetEnumerator() { return GetKeyedEnumerator(e); } 127 | } 128 | 129 | /// 130 | /// Wraps the specified IEnumerable. Use this method if you want to foreach. 131 | /// 132 | /// Enumerable to wrap. 133 | /// An IEnumerable that returns an appropriate iterator for the wrapped item. 134 | public static IEnumerable GetKeyedEnumerable(IEnumerable enumerable) 135 | { 136 | if (enumerable is IDictionary) return enumerable; 137 | return new CountingProxy(enumerable); 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /doc/krpc.md: -------------------------------------------------------------------------------- 1 | # Using KIPC with KRPC. 2 | 3 | **[ [KIPC Overview](index.md) ] [ [kOS API](kos.md) ] [ [kRPC API](krpc.md) ] [ [Changelog](CHANGELOG.md) ] [ [License](LICENSE.md) ]** 4 | 5 | ## KIPC Service 6 | Handles general functionality. 7 | 8 | **GetProcessors(_vessel_)** 9 | 10 | Returns all `KOSProcessors` on the specified `vessel`. 11 | 12 | **GetProcessor(_part_)** _(Added in 0.1.1)_ 13 | 14 | Returns all `KOSProcessors` on the specified `part`. Generally this will be an empty list or a list with one element. 15 | 16 | **ResolveVessel(_guid_)** 17 | 18 | Given a vessel GUID, returns the vessel. Use this to handle vessel references in JSON results. 19 | 20 | **ResolveVessels(_guids_)** _(Added in 0.1.1)_ 21 | 22 | Given a list of vessel GUIDs, resolves all of them. Results are in the same order as the input. 23 | 24 | **ResolveBody(_id_)** 25 | 26 | Given a body ID, returns the celestial body. Use this to handle body references in JSON results. 27 | 28 | **ResolveBodies(_ids_)** _(Added in 0.1.1)_ 29 | 30 | Given a list of body IDs, returns the corresponding celestial bodies. Results are in the same order as the inputs. 31 | 32 | **PopMessage()** 33 | 34 | Removes and returns the next message in the queue, or an exception if no message exists. 35 | See the JSON Format section for details on how to parse these messages. 36 | 37 | **PeekMessage()** 38 | 39 | Returns the next message in the queue, or an exception if no message exists. The message is not removed. 40 | See the JSON Format section for details on how to parse these messages. 41 | 42 | **GetMessages()** _(Added in 0.1.1)_ 43 | 44 | Returns _all_ messages currently in the queue and empties the queue. Returns an empty list if the queue is empty. 45 | See the JSON Format section for details on how to parse these messages. 46 | 47 | **_property_ CountMessages** (get) _(Added in 0.1.1)_ 48 | 49 | Returns the number of messages in the queue. 50 | 51 | **GetPartsTagged(_vessel_, _tag_)** _(Added in 0.1.1)_ 52 | 53 | Returns a list of all parts tagged with the specified kOS `tag` on the specified `vessel`. 54 | 55 | 56 | ## Processor class 57 | 58 | (May change names in a later build) 59 | 60 | **_property_ Part** (get) 61 | 62 | Returns the parent part of this `kOSProcessor`. 63 | 64 | **_property_ DiskSpace** (get) 65 | 66 | Returns the total disk space of this processor. 67 | 68 | **_property_ Powered** (get, set) 69 | 70 | Returns or sets whether the processor is currently turned on. Note that power-starved still counts as turned on. 71 | 72 | **_property_ TerminalVisible** (get, set) 73 | 74 | Returns or sets whether the terminal is currently visible. 75 | 76 | **SendMessage(_json_)** 77 | 78 | Sends the particular JSON-encoded message to the processor's message queue. 79 | 80 | ## JSON format 81 | 82 | Strings, integers, double/floats, booleans, and `null` are represented using their native JSON representation. 83 | 84 | All other types (including lists and dictionaries) are in an encapsulated format 85 | 86 | ### Dictionary/Lexicon 87 | ``` 88 | { 89 | "type": "dict", 90 | "data": {"string key": 42, ...}, 91 | "keys", [1, 2, 3, 4], 92 | "values", ["One", "Two", "Three", "Four"] 93 | } 94 | ``` 95 | JSON objects cannot have non-string keys, but kOS Lexicons can. All string keys will be contained in `data`. 96 | 97 | Non-string keys will be listed in `keys`, with their corresponding values in `values`. (In Python, you can construct 98 | that portion of the corresponding dictionary using `dict(zip(keys, values))`) 99 | 100 | ### Lists, Stacks, and Queues 101 | ``` 102 | { 103 | "type": "list", // or "stack" or "queue" 104 | "data": [1, 2, 3, 4] 105 | } 106 | ``` 107 | For all three types, data elements are in insertion order: the oldest item on the queue is listed first, and the 108 | bottom-most element of a stack is listed queue. 109 | 110 | ### References 111 | 112 | KIPC can handle recursive data structures: e.g. a list that contains itself, or a dict that is referenced multiple 113 | times within a complicated structure. 114 | 115 | If this occurs, all references to the same object will have a `ref` field with a common value. One of the objects will 116 | be its normal representation, others will look like this: 117 | ``` 118 | { 119 | "type": "ref", 120 | "ref": 4, 121 | } 122 | ``` 123 | 124 | For instance, a list that contains another list that contains the first may look like: 125 | ``` 126 | { 127 | "type": "list", 128 | "ref": 1, 129 | "data": [{ 130 | "type": "list", 131 | "data" [{ 132 | "type": "ref", 133 | "ref", 1 134 | }] 135 | }] 136 | } 137 | ``` 138 | 139 | Only collection types (the four above) support references within the deserializer. 140 | 141 | ### Vectors 142 | ``` 143 | { 144 | "type": "vector", 145 | "data": [x, y, z] 146 | } 147 | ``` 148 | 149 | ### Vessels 150 | ``` 151 | { 152 | "type": "vessel", 153 | "data": "vessel-guid" 154 | } 155 | ``` 156 | Use `KIPC.ResolveVessel` to convert a vessel reference to an actual kRPC-usable `Vessel`. 157 | 158 | ### Celestial Bodies 159 | ``` 160 | { 161 | "type": "body", 162 | "data": 1, // flightGlobals index 163 | } 164 | ``` 165 | Use `KIPC.ResolveBody` to convert a body reference to an actual kRPC-usable `CelestialBody`. 166 | -------------------------------------------------------------------------------- /plugin/Postbuild.ps1: -------------------------------------------------------------------------------- 1 | # powershell $(SolutionDir)\Postbuild.ps1 -BuildDir $(ProjectDir)$(OutDir) -KSPDir $(SolutionDir)..\KSP -OutputDir $(SolutionDir)..\Output -ClientGen $(SolutionDir)..\Python\venv\scripts 2 | Param ( 3 | # Location of build artifacts 4 | [Parameter(Mandatory=$true)] 5 | [ValidateNotNullOrEmpty()] 6 | [string] 7 | $BuildDir, 8 | 9 | # Solution dir. Also used to generate defaults for other arguments. 10 | [Parameter(Mandatory=$true)] 11 | [ValidateNotNullOrEmpty()] 12 | [string] 13 | $SolutionDir, 14 | 15 | # Where to store final output. 16 | [Parameter(Mandatory=$false)] 17 | [ValidateNotNullOrEmpty()] 18 | [string] 19 | $OutputDir, 20 | 21 | # Location of KSP 22 | [Parameter(Mandatory=$false)] 23 | [ValidateNotNullOrEmpty()] 24 | [string] 25 | $KSPDir, 26 | 27 | # Location of build scripts 28 | [Parameter(Mandatory=$false)] 29 | [ValidateNotNullOrEmpty()] 30 | [string] 31 | $ScriptsDir 32 | ) 33 | 34 | $Languages = @( 35 | New-Object -TypeName PSObject -Property @{'Lang'='csharp'; 'File'='KIPC.cs'} 36 | New-Object -TypeName PSObject -Property @{'Lang'='cpp'; 'File'='KIPC.hpp'} 37 | New-Object -TypeName PSObject -Property @{'Lang'='java'; 'File'='KIPC.java'} 38 | ) 39 | 40 | $BuildDir = (Get-Item $BuildDir).FullName 41 | $SolutionDir = (Get-Item $SolutionDir).FullName 42 | 43 | if(-not $OutputDir) { $OutputDir = Join-Path $SolutionDir "..\output" } 44 | if(-not $KSPDir) { $KSPDir = Join-Path $SolutionDir "..\KSP" } 45 | if(-not $ScriptsDir) { $ScriptsDir = Join-Path $SolutionDir "..\python/venv/scripts" } 46 | 47 | $OutputDir = (Get-Item $OutputDir).FullName 48 | $KSPDir = (Get-Item $KSPDir).FullName 49 | $ScriptsDir = (Get-Item $ScriptsDir).FullName 50 | $ClientGen = Join-Path $ScriptsDir "krpc-clientgen" 51 | 52 | echo "BuildDir: $BuildDir" 53 | echo "SolutionDir: $SolutionDir" 54 | echo "KSPDir: $KSPDir" 55 | echo "OutputDir: $OutputDir" 56 | echo "ScriptsDir: $ScriptsDir" 57 | echo "ClientGen: $ClientGen" 58 | 59 | # We're going to need a tempdir. Make one 60 | $TempPath = [System.IO.Path]::GetTempPath() 61 | while($true) { 62 | $TempDir = Join-Path $TempPath ([System.IO.Path]::GetRandomFileName()) 63 | mkdir $TempDir -ErrorVariable DirErr -ErrorAction SilentlyContinue | Out-Null 64 | if($DirErr) { continue } 65 | break 66 | } 67 | Register-EngineEvent -SourceIdentifier Powershell.Exiting -SupportEvent -Action { 68 | rmdir $TempDir -Recurse -Force 69 | echo "Removed $TempDir" 70 | } 71 | echo "TempDir: $TempDir" 72 | 73 | $ErrorActionPreference = "Stop" 74 | $WarningPreference = "Stop" 75 | 76 | # Create folder structure 77 | mkdir $TempDir/Output | Out-Null 78 | mkdir $TempDir/Output/Clients | Out-Null 79 | mkdir $TempDir/Output/GameData/KIPC | Out-Null 80 | mkdir $TempDir/Output/GameData/KIPC/Plugins | Out-Null 81 | mkdir $TempDir/DLLs | Out-Null 82 | 83 | # Copy DLLs. 84 | $BuildDLLs = gci $BuildDir -Filter "*.dll" 85 | $BuildDLLs | %{ Copy-Item $_.FullName $TempDir/Output/GameData/KIPC/Plugins -Force } 86 | $BuildDLLs | %{ Copy-Item $_.FullName $TempDir/DLLs -Force } 87 | 88 | $Dependencies = @(gci $KSPDir/GameData/KOS -Filter "*.dll" -Recurse) + @(gci $KSPDir/GameData/KRPC -Filter "*.dll" -Recurse) 89 | $Dependencies | %{ Copy-Item $_.FullName $TempDir/DLLs -Force } 90 | 91 | # Create AVC version file 92 | $VersionInfo = $BuildDLLs | Where Name -Like "*KIPC*" | Select -First 1 | Select -ExpandProperty VersionInfo 93 | $AVCJson = Get-Content $SolutionDir/KIPC.version.template | ConvertFrom-Json 94 | $AVCJson.VERSION.MAJOR = $VersionInfo.FileMajorPart 95 | $AVCJson.VERSION.MINOR = $VersionInfo.FileMinorPart 96 | $AVCJson.VERSION.PATCH = $VersionInfo.FileBuildPart 97 | $AVCJson.VERSION.BUILD = $VersionInfo.FilePrivatePart 98 | $AVCJson | ConvertTo-Json -Compress | Set-Content $TempDir/Output/GameData/KIPC/KIPC.version 99 | Copy-Item $TempDir/Output/GameData/KIPC/KIPC.version $SolutionDir 100 | 101 | # Build client libraries. 102 | $ClientDefs = "$TempDir/Output/Clients/clientdefs.json" 103 | Push-Location $TempDir/DLLs 104 | $HaveJSON = $false 105 | foreach($Language in $Languages) { 106 | $LangDir = Join-Path $TempDir/Output/Clients $Language.Lang 107 | $OutputFile = Join-Path $LangDir $Language.File 108 | mkdir $LangDir | Out-Null 109 | if($HaveJSON) { 110 | $Args = @($Language.Lang, "KIPC", $ClientDefs) 111 | } else { 112 | $HaveJSON = $true 113 | $Args = @($Language.Lang, "KIPC", "--ksp", $KSPDir, "--output-defs", $ClientDefs) + @($BuildDLLs | %{ $_.Name }) 114 | } 115 | echo ("[clientgen] " + ($Args -Join " ")) 116 | &$ClientGen $args | Out-File $OutputFile 117 | } 118 | Pop-Location 119 | 120 | # Zip the output folder 121 | $ZipName = "KIPC-$($VersionInfo.FileMajorPart).$($VersionInfo.FileMinorPart).$($VersionInfo.FileBuildPart).zip" 122 | Compress-Archive -Path $TempDir/Output/* -DestinationPath "$TempDir/Output/$ZipName" -Force -Verbose 123 | # Move-Item $TempDir/KIPC.zip $TempDir/Output/$ZipName 124 | 125 | # Move the output dir to where it should be. 126 | robocopy /MIR $Tempdir/Output $OutputDir /NJH /NJS /NFL /NDL /NP 127 | 128 | # Mirror to KSP 129 | robocopy /MIR $OutputDir/Gamedata/KIPC $KSPDir/Gamedata/KIPC /NJH /NJS /NFL /NDL /NP 130 | 131 | # Remove temp directories 132 | Remove-Item -Recurse $TempDir 133 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/KRPC/Service.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | using KRPC.Service; 7 | using KRPC.Service.Attributes; 8 | 9 | using KIPC.Serialization; 10 | 11 | namespace KIPC.KRPC 12 | { 13 | using global::KRPC.SpaceCenter.Services; 14 | using global::KRPC.SpaceCenter.Services.Parts; 15 | /// 16 | /// Service for KIPC, a means of communication and interaction between kOS and KRPC. 17 | /// 18 | [KRPCService(GameScene = GameScene.All, Name = "KIPC")] 19 | public static class Service 20 | { 21 | internal const string SERVICE_NAME = "KIPC"; 22 | /// 23 | /// Returns and removes the top message on the message queue. Raises an exception if the queue is empty (since Null isn't a valid return value). 24 | /// 25 | /// The JSON-encoded message. 26 | [KRPCProcedure] 27 | public static string PopMessage() 28 | { 29 | return KIPC.Addon.krpcMessageQueue.Dequeue(); 30 | } 31 | 32 | /// 33 | /// Returns the top message on the message queue. Raises an exception if the queue is empty (since Null isn't a valid return value). 34 | /// 35 | /// The JSON-encoded message. 36 | [KRPCProcedure] 37 | public static string PeekMessage() 38 | { 39 | return KIPC.Addon.krpcMessageQueue.Peek(); 40 | } 41 | 42 | /// 43 | /// Returns all messages on the message queue in order. 44 | /// 45 | [KRPCProcedure] 46 | public static IList GetMessages() 47 | { 48 | var result = KIPC.Addon.krpcMessageQueue.ToList(); 49 | KIPC.Addon.krpcMessageQueue.Clear(); 50 | return result; 51 | } 52 | 53 | /// 54 | /// The number of messages currently waiting in the queue. 55 | /// 56 | [KRPCProperty] 57 | public static int CountMessages { get { return KIPC.Addon.krpcMessageQueue.Count; } } 58 | 59 | /// 60 | /// Returns all kOSProcessors on the specified vessel. 61 | /// 62 | /// Target vessel 63 | /// 64 | [KRPCProcedure] 65 | public static IList GetProcessors(Vessel vessel) 66 | { 67 | return vessel.InternalVessel.parts.SelectMany(x => x.Modules.OfType()).Select(x => new Processor(x)).ToList(); 68 | } 69 | 70 | /// 71 | /// Returns all kOSProcessors on the specified part (usually 0 or 1). 72 | /// 73 | /// Target part 74 | /// 75 | [KRPCProcedure] 76 | public static IList GetProcessor(Part part) 77 | { 78 | return part.InternalPart.Modules.OfType().Select(x => new Processor(x)).ToList(); 79 | } 80 | 81 | /// 82 | /// Resolves a vessel GUID to an actual vessel. 83 | /// 84 | /// Vessel GUID 85 | /// 86 | [KRPCProcedure] 87 | public static Vessel ResolveVessel(string vesselGuid) 88 | { 89 | return new Vessel(VesselHandler.GetVesselById(new Guid(vesselGuid))); 90 | } 91 | 92 | /// 93 | /// Resolves multiple vessel GUIDs to actual vessels. Returned vessels will be in the same order as the inputs. 94 | /// 95 | /// Vessel GUID 96 | /// 97 | [KRPCProcedure] 98 | public static IList ResolveVessels(IList vesselGuids) 99 | { 100 | return vesselGuids.Select(guid => new Vessel(VesselHandler.GetVesselById(new Guid(guid)))).ToList(); 101 | } 102 | 103 | /// 104 | /// Resolves a celestial body ID to an actual celestial body. 105 | /// 106 | /// 107 | /// 108 | [KRPCProcedure] 109 | public static CelestialBody ResolveBody(int bodyId) 110 | { 111 | return new CelestialBody(BodyHandler.GetBodyById(bodyId)); 112 | } 113 | 114 | /// 115 | /// Resolves a celestial body ID to an actual celestial body. 116 | /// 117 | /// 118 | /// 119 | [KRPCProcedure] 120 | public static IList ResolveBodies(IList bodyIds) 121 | { 122 | return bodyIds.Select(bodyId => new CelestialBody(BodyHandler.GetBodyById(bodyId))).ToList(); 123 | } 124 | 125 | /// 126 | /// Returns a list of all parts tagged with the specified kOSNameTag on the specified vessel. 127 | /// 128 | /// Vessel 129 | /// Tag name 130 | /// 131 | [KRPCProcedure] 132 | public static IList GetPartsTagged(Vessel vessel, string tag) 133 | { 134 | return vessel.InternalVessel.parts.FindAll(p => p.Modules.OfType().Any(m => m.nameTag == tag)).Select(p => new Part(p)).ToList(); 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/KIPCPlugin.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {FEBE111A-D442-48BF-90B3-9135B577A4F6} 8 | Library 9 | Properties 10 | KIPCPlugin 11 | KIPCPlugin 12 | v3.5 13 | 512 14 | 15 | 16 | 17 | 18 | 19 | 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | TRACE;DEBUG 25 | prompt 26 | 4 27 | 28 | 29 | none 30 | true 31 | bin\Release\ 32 | 33 | 34 | prompt 35 | 4 36 | false 37 | 38 | 39 | 40 | ..\..\KSP\KSP_x64_Data\Managed\Assembly-CSharp.dll 41 | False 42 | 43 | 44 | ..\..\KSP\KSP_x64_Data\Managed\Assembly-CSharp-firstpass.dll 45 | False 46 | 47 | 48 | ..\..\KSP\KSP_x64_Data\Managed\Assembly-UnityScript.dll 49 | False 50 | 51 | 52 | ..\..\KSP\KSP_x64_Data\Managed\Assembly-UnityScript-firstpass.dll 53 | False 54 | 55 | 56 | ..\packages\JsonFx.2.0.1209.2802\lib\net35\JsonFx.dll 57 | True 58 | 59 | 60 | ..\..\KSP\GameData\kOS\Plugins\kOS.dll 61 | False 62 | 63 | 64 | ..\..\KSP\GameData\kOS\Plugins\kOS.Safe.dll 65 | False 66 | 67 | 68 | ..\..\KSP\GameData\kRPC\KRPC.dll 69 | False 70 | 71 | 72 | ..\..\KSP\GameData\kRPC\KRPC.SpaceCenter.dll 73 | False 74 | 75 | 76 | ..\..\KSP\GameData\kRPC\KRPC.UI.dll 77 | False 78 | 79 | 80 | ..\..\KSP\KSP_x64_Data\Managed\KSPAssets.dll 81 | False 82 | 83 | 84 | ..\..\KSP\KSP_x64_Data\Managed\KSPCore.dll 85 | False 86 | 87 | 88 | ..\..\KSP\KSP_x64_Data\Managed\KSPUtil.dll 89 | False 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | ..\..\KSP\KSP_x64_Data\Managed\UnityEngine.dll 99 | False 100 | 101 | 102 | ..\..\KSP\KSP_x64_Data\Managed\UnityEngine.UI.dll 103 | False 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | Designer 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | powershell $(SolutionDir)\Postbuild.ps1 $(ProjectDir)$(OutDir) $(SolutionDir)..\KSP\GameData\KIPCPlugin\Plugins 122 | 123 | 124 | 125 | 126 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 127 | 128 | 129 | 130 | 137 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Initially created by https://www.gitignore.io/api/csharp 2 | 3 | # No, let's not add KSP to our github repo. Squad wouldn't like that. 4 | KSP/* 5 | # Just say no to binary output 6 | plugin/Output/* 7 | Output/* 8 | 9 | 10 | ### Csharp ### 11 | ## Ignore Visual Studio temporary files, build results, and 12 | ## files generated by popular Visual Studio add-ons. 13 | 14 | # User-specific files 15 | *.suo 16 | *.user 17 | *.userosscache 18 | *.sln.docstates 19 | 20 | # User-specific files (MonoDevelop/Xamarin Studio) 21 | *.userprefs 22 | 23 | # Build results 24 | [Dd]ebug/ 25 | [Dd]ebugPublic/ 26 | [Rr]elease/ 27 | [Rr]eleases/ 28 | x64/ 29 | x86/ 30 | bld/ 31 | [Bb]in/ 32 | [Oo]bj/ 33 | [Ll]og/ 34 | 35 | # Visual Studio 2015 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # MSTest test Results 41 | [Tt]est[Rr]esult*/ 42 | [Bb]uild[Ll]og.* 43 | 44 | # NUNIT 45 | *.VisualState.xml 46 | TestResult.xml 47 | 48 | # Build Results of an ATL Project 49 | [Dd]ebugPS/ 50 | [Rr]eleasePS/ 51 | dlldata.c 52 | 53 | # DNX 54 | project.lock.json 55 | project.fragment.lock.json 56 | artifacts/ 57 | 58 | *_i.c 59 | *_p.c 60 | *_i.h 61 | *.ilk 62 | *.meta 63 | *.obj 64 | *.pch 65 | *.pdb 66 | *.pgc 67 | *.pgd 68 | *.rsp 69 | *.sbr 70 | *.tlb 71 | *.tli 72 | *.tlh 73 | *.tmp 74 | *.tmp_proj 75 | *.log 76 | *.vspscc 77 | *.vssscc 78 | .builds 79 | *.pidb 80 | *.svclog 81 | *.scc 82 | 83 | # Chutzpah Test files 84 | _Chutzpah* 85 | 86 | # Visual C++ cache files 87 | ipch/ 88 | *.aps 89 | *.ncb 90 | *.opendb 91 | *.opensdf 92 | *.sdf 93 | *.cachefile 94 | *.VC.db 95 | *.VC.VC.opendb 96 | 97 | # Visual Studio profiler 98 | *.psess 99 | *.vsp 100 | *.vspx 101 | *.sap 102 | 103 | # TFS 2012 Local Workspace 104 | $tf/ 105 | 106 | # Guidance Automation Toolkit 107 | *.gpState 108 | 109 | # ReSharper is a .NET coding add-in 110 | _ReSharper*/ 111 | *.[Rr]e[Ss]harper 112 | *.DotSettings.user 113 | 114 | # JustCode is a .NET coding add-in 115 | .JustCode 116 | 117 | # TeamCity is a build add-in 118 | _TeamCity* 119 | 120 | # DotCover is a Code Coverage Tool 121 | *.dotCover 122 | 123 | # NCrunch 124 | _NCrunch_* 125 | .*crunch*.local.xml 126 | nCrunchTemp_* 127 | 128 | # MightyMoose 129 | *.mm.* 130 | AutoTest.Net/ 131 | 132 | # Web workbench (sass) 133 | .sass-cache/ 134 | 135 | # Installshield output folder 136 | [Ee]xpress/ 137 | 138 | # DocProject is a documentation generator add-in 139 | DocProject/buildhelp/ 140 | DocProject/Help/*.HxT 141 | DocProject/Help/*.HxC 142 | DocProject/Help/*.hhc 143 | DocProject/Help/*.hhk 144 | DocProject/Help/*.hhp 145 | DocProject/Help/Html2 146 | DocProject/Help/html 147 | 148 | # Click-Once directory 149 | publish/ 150 | 151 | # Publish Web Output 152 | *.[Pp]ublish.xml 153 | *.azurePubxml 154 | # TODO: Comment the next line if you want to checkin your web deploy settings 155 | # but database connection strings (with potential passwords) will be unencrypted 156 | *.pubxml 157 | *.publishproj 158 | 159 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 160 | # checkin your Azure Web App publish settings, but sensitive information contained 161 | # in these scripts will be unencrypted 162 | PublishScripts/ 163 | 164 | # NuGet Packages 165 | *.nupkg 166 | # The packages folder can be ignored because of Package Restore 167 | **/packages/* 168 | # except build/, which is used as an MSBuild target. 169 | !**/packages/build/ 170 | # Uncomment if necessary however generally it will be regenerated when needed 171 | #!**/packages/repositories.config 172 | # NuGet v3's project.json files produces more ignoreable files 173 | *.nuget.props 174 | *.nuget.targets 175 | 176 | # Microsoft Azure Build Output 177 | csx/ 178 | *.build.csdef 179 | 180 | # Microsoft Azure Emulator 181 | ecf/ 182 | rcf/ 183 | 184 | # Windows Store app package directories and files 185 | AppPackages/ 186 | BundleArtifacts/ 187 | Package.StoreAssociation.xml 188 | _pkginfo.txt 189 | 190 | # Visual Studio cache files 191 | # files ending in .cache can be ignored 192 | *.[Cc]ache 193 | # but keep track of directories ending in .cache 194 | !*.[Cc]ache/ 195 | 196 | # Others 197 | ClientBin/ 198 | ~$* 199 | *~ 200 | *.dbmdl 201 | *.dbproj.schemaview 202 | *.pfx 203 | *.publishsettings 204 | node_modules/ 205 | orleans.codegen.cs 206 | 207 | # Since there are multiple workflows, uncomment next line to ignore bower_components 208 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 209 | #bower_components/ 210 | 211 | # RIA/Silverlight projects 212 | Generated_Code/ 213 | 214 | # Backup & report files from converting an old project file 215 | # to a newer Visual Studio version. Backup files are not needed, 216 | # because we have git ;-) 217 | _UpgradeReport_Files/ 218 | Backup*/ 219 | UpgradeLog*.XML 220 | UpgradeLog*.htm 221 | 222 | # SQL Server files 223 | *.mdf 224 | *.ldf 225 | 226 | # Business Intelligence projects 227 | *.rdl.data 228 | *.bim.layout 229 | *.bim_*.settings 230 | 231 | # Microsoft Fakes 232 | FakesAssemblies/ 233 | 234 | # GhostDoc plugin setting file 235 | *.GhostDoc.xml 236 | 237 | # Node.js Tools for Visual Studio 238 | .ntvs_analysis.dat 239 | 240 | # Visual Studio 6 build log 241 | *.plg 242 | 243 | # Visual Studio 6 workspace options file 244 | *.opt 245 | 246 | # Visual Studio LightSwitch build output 247 | **/*.HTMLClient/GeneratedArtifacts 248 | **/*.DesktopClient/GeneratedArtifacts 249 | **/*.DesktopClient/ModelManifest.xml 250 | **/*.Server/GeneratedArtifacts 251 | **/*.Server/ModelManifest.xml 252 | _Pvt_Extensions 253 | 254 | # Paket dependency manager 255 | .paket/paket.exe 256 | paket-files/ 257 | 258 | # FAKE - F# Make 259 | .fake/ 260 | 261 | # JetBrains Rider 262 | .idea/ 263 | *.sln.iml 264 | 265 | 266 | 267 | # Created by https://www.gitignore.io/api/python 268 | 269 | ### Python ### 270 | # Byte-compiled / optimized / DLL files 271 | __pycache__/ 272 | *.py[cod] 273 | *$py.class 274 | 275 | # C extensions 276 | *.so 277 | 278 | # Distribution / packaging 279 | .Python 280 | env/ 281 | build/ 282 | develop-eggs/ 283 | dist/ 284 | downloads/ 285 | eggs/ 286 | .eggs/ 287 | lib/ 288 | lib64/ 289 | parts/ 290 | sdist/ 291 | var/ 292 | *.egg-info/ 293 | .installed.cfg 294 | *.egg 295 | 296 | # PyInstaller 297 | # Usually these files are written by a python script from a template 298 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 299 | *.manifest 300 | *.spec 301 | 302 | # Installer logs 303 | pip-log.txt 304 | pip-delete-this-directory.txt 305 | 306 | # Unit test / coverage reports 307 | htmlcov/ 308 | .tox/ 309 | .coverage 310 | .coverage.* 311 | .cache 312 | nosetests.xml 313 | coverage.xml 314 | *,cover 315 | .hypothesis/ 316 | 317 | # Translations 318 | *.mo 319 | *.pot 320 | 321 | # Django stuff: 322 | *.log 323 | local_settings.py 324 | 325 | # Flask stuff: 326 | instance/ 327 | .webassets-cache 328 | 329 | # Scrapy stuff: 330 | .scrapy 331 | 332 | # Sphinx documentation 333 | docs/_build/ 334 | 335 | # PyBuilder 336 | target/ 337 | 338 | # IPython Notebook 339 | .ipynb_checkpoints 340 | 341 | # pyenv 342 | .python-version 343 | 344 | # celery beat schedule file 345 | celerybeat-schedule 346 | 347 | # dotenv 348 | .env 349 | 350 | # virtualenv 351 | venv/ 352 | ENV/ 353 | 354 | # Spyder project settings 355 | .spyderproject 356 | 357 | # Rope project settings 358 | .ropeproject -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/TypeHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Reflection; 5 | 6 | using KIPC.Util; 7 | 8 | namespace KIPC.Serialization 9 | { 10 | using JsonList = List; 11 | using JsonDict = Dictionary; 12 | using JsonKey = KeyValuePair; 13 | using IJsonList = IList; 14 | using IJsonDict = IDictionary; 15 | 16 | /// 17 | /// Provides the base implementation for TypeHandlers, which handle deserializing JSON Data. 18 | /// 19 | /// Type Handlers turn into JSON Dictionaries (i.e. string: object). They contain -- at minimum -- a 'type' field to identify them 20 | /// and a 'data' field to represent their data. 21 | /// 22 | /// TODO: This really shouldn't be a Dictionary subclass (it should instead contain a dictionary), but I haven't figured out how to really 23 | /// control JsonFx and the documentation, frankly, sucks. 24 | /// 25 | /// TODO: It's entirely possible these could be static or mostly-static classes with some refactoring. This would improve deserialization performance 26 | /// by having fewer objects created and less to garbage collect. Serialization still requires a dictionary output somewhere (unless we learn how to 27 | /// override that in JsonFx), so it'd be only a minor improvement in that department. 28 | /// 29 | public abstract class TypeHandler : JsonDict 30 | { 31 | #region Properties 32 | /// 33 | /// Keep a pointer to our own SerializesAttribute, which will be initialized during a reflection pass. It cannot be changed afterwards. 34 | /// 35 | public readonly TypeSerializer info = null; 36 | 37 | /// 38 | /// Know who our serializer is in case we need to call it for support functions. 39 | /// 40 | public readonly Serializer serializer = null; 41 | #endregion 42 | internal TypeHandler(TypeSerializer info, Serializer serializer) 43 | { 44 | this.info = info; 45 | this.serializer = serializer; 46 | this["type"] = info.Identifier; 47 | this["data"] = null; 48 | } 49 | 50 | internal MethodInfo SerializeMethod, DeserializeMethod; 51 | public TypeHandler ProxySerialize(object input) 52 | { 53 | object[] args = { input }; // Hopefully this is stack allocated 54 | return (TypeHandler) SerializeMethod.Invoke(this, new object[] { input }); 55 | } 56 | 57 | public object ProxyDeserialize(IJsonDict source) 58 | { 59 | return DeserializeMethod.Invoke(this, new object[] { source }); 60 | } 61 | 62 | public void Import(IJsonDict source) 63 | { 64 | foreach(JsonKey kvp in source) 65 | { 66 | this[kvp.Key] = kvp.Value; 67 | } 68 | } 69 | } 70 | /// 71 | /// Type-specific functions for Type Handlers. 72 | /// 73 | public abstract class TypeHandler : TypeHandler 74 | { 75 | /// 76 | /// Construct a new TypeHandler 77 | /// 78 | /// Serializer that will provide services for us. 79 | protected TypeHandler(TypeSerializer info, Serializer serializer) : base(info, serializer) { } 80 | 81 | /// 82 | /// Serialize the specified input, generally by setting appropriate key/value pairs in the dictionary we subclass. 83 | /// Generally returns this, but may return something else in special cases. 84 | /// 85 | /// Input object. 86 | /// 87 | public abstract TypeHandler Serialize(T input); 88 | 89 | /// 90 | /// Deserialize ourselves and recreate the requested original input. 91 | /// 92 | /// Deserialized object 93 | public abstract T Deserialize(IJsonDict source); 94 | 95 | /// 96 | /// Convenience method; raises a SerializationException if the specified key (default 'data') does not exist. 97 | /// 98 | /// Type we expect the value to be. 99 | /// Key in dictionary to look for 100 | /// True if the value must exist. 101 | /// True if value key may be null. 102 | protected void EnsureValueIsType(string key = "data", bool mustExist = true, bool allowNull = false) 103 | { 104 | EnsureValueIsType(this, key, mustExist, allowNull); 105 | } 106 | /// 107 | /// Convenience method; raises a SerializationException if the specified key (default 'data') does not exist. 108 | /// 109 | /// Type we expect the value to be. 110 | /// Source dictionary to look for 111 | /// Key in dictionary to look for 112 | /// True if the value must exist. 113 | /// True if value key may be null. 114 | protected void EnsureValueIsType(IJsonDict source, string key = "data", bool mustExist = true, bool allowNull = false) 115 | { 116 | object value; 117 | try 118 | { 119 | value = source[key]; 120 | } catch (KeyNotFoundException) 121 | { 122 | if (mustExist) 123 | { 124 | throw new SerializationException( 125 | string.Format( 126 | "{0} object: Expected attribute '{1}' of type '{2}' was not found.", 127 | this.info.Name, key, typeof(TType).Name 128 | ) 129 | ); 130 | 131 | } 132 | return; 133 | } 134 | try 135 | { 136 | Validation.AssertType(value, allowNull); 137 | } catch (ArgumentNullException) 138 | { 139 | throw new SerializationException( 140 | string.Format( 141 | "{0} object: Expected attribute '{1}' to be of type '{2}', but it was null instead.", 142 | this.info.Name, key, typeof(TType).Name, value.GetType().Name 143 | ) 144 | ); 145 | } catch (ArgumentException) { 146 | throw new SerializationException( 147 | string.Format( 148 | "{0} object: Expected attribute '{1}' to be of type '{2}', but encountered '{3}' instead.", 149 | this.info.Name, key, typeof(TType).Name, value.GetType().Name 150 | ) 151 | ); 152 | } 153 | } 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/KOSAddon.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.Serialization; 5 | 6 | using UnityEngine; 7 | 8 | using kOS.Safe.Encapsulation; 9 | using kOS.Safe.Encapsulation.Suffixes; 10 | using kOS.Suffixed; 11 | using kOS.AddOns; 12 | 13 | using JsonFx.Json; 14 | 15 | namespace KIPCPlugin.KOS 16 | { 17 | [kOSAddon("KIPC")] 18 | [kOS.Safe.Utilities.KOSNomenclature("KIPC")] 19 | public class Addon : kOS.Suffixed.Addon 20 | { 21 | private static JsonWriter jsonWriter = new JsonWriter(); 22 | 23 | public Addon(kOS.SharedObjects shared) : base(shared) 24 | { 25 | InitializeSuffixes(); 26 | } 27 | 28 | private void InitializeSuffixes() 29 | { 30 | AddSuffix("SERIALIZE", new OneArgsSuffix(Serialize)); 31 | } 32 | 33 | private static StringValue Serialize(Structure input) 34 | { 35 | return jsonWriter.Write(new Serializer().Serialize(input)); 36 | } 37 | 38 | public override BooleanValue Available() 39 | { 40 | return true; 41 | } 42 | } 43 | 44 | /// 45 | /// Exists solely to provide a way for kOS scripts to determine if KRPC is present. 46 | /// 47 | [kOSAddon("KRPC")] 48 | [kOS.Safe.Utilities.KOSNomenclature("KRPC")] 49 | public class KRPCAvailabilityIndicator : Addon 50 | { 51 | public KRPCAvailabilityIndicator(kOS.SharedObjects shared) : base(shared) { } 52 | 53 | public override BooleanValue Available() 54 | { 55 | return KIPC.Addon.hasKRPC; 56 | } 57 | } 58 | 59 | public enum WrappedType 60 | { 61 | List, Queue, Stack, Dict, 62 | Reference, 63 | Vector, Direction, Quaternion, 64 | Vessel, Part, Body, 65 | Invalid = -1 66 | } 67 | 68 | public class Typewrapper : Dictionary 69 | { 70 | public WrappedType type { get; private set; } 71 | public object data { 72 | get { return this["data"]; } 73 | set { this["data"] = value; } 74 | } 75 | public Typewrapper(WrappedType type, object data = null) : base() 76 | { 77 | this["type"] = type.ToString().ToLowerInvariant(); 78 | this["data"] = data; 79 | } 80 | } 81 | 82 | public class SerializationException : Exception 83 | { 84 | public SerializationException() { } 85 | public SerializationException(String message) : base(message) { } 86 | public SerializationException(String message, Exception inner) : base(message, inner) { } 87 | } 88 | 89 | public class Serializer 90 | { 91 | /// 92 | /// Per-instance object ID generator for recursive reference detection. 93 | /// 94 | private ObjectIDGenerator idgenerator = new ObjectIDGenerator(); 95 | /// 96 | /// Current mapping of references so we can detect recursive references. 97 | /// 98 | public Dictionary idMap = new Dictionary(); 99 | 100 | public Serializer() 101 | { 102 | // rrefDict = new Dictionary(); 103 | } 104 | 105 | private Typewrapper RefCapableWrapper(WrappedType type, Structure s, out bool cached) 106 | { 107 | bool firstTime; 108 | long objectId = idgenerator.GetId(s, out firstTime); 109 | Debug.LogFormat( 110 | "Identified object type '{0}' with id {1}, firstTime={2}; in rrefDict={3}", s.KOSName, objectId, firstTime, idMap.ContainsKey(objectId) 111 | ); 112 | if ( (cached = !firstTime) ) // Assignment intentional 113 | { 114 | idMap[objectId]["ref"] = objectId; 115 | return new Typewrapper(WrappedType.Reference, objectId); 116 | } 117 | return idMap[objectId] = new Typewrapper(type); 118 | } 119 | 120 | public object Serialize(Structure s) 121 | { 122 | // If Unity supported a modern C# version with, say, dynamic, we could go back to the overloaded methods approach 123 | // Instead of this giant mess of if-checks 124 | if(s is PrimitiveStructure) 125 | { 126 | return ((PrimitiveStructure)s).ToPrimitive(); 127 | } 128 | if (s is Lexicon) 129 | { 130 | bool cached; 131 | var result = RefCapableWrapper(WrappedType.Dict, s, out cached); 132 | if (cached) return result; 133 | var input = (Lexicon)s; 134 | var data = new Dictionary(); 135 | var keys = new List(); 136 | var values = new List(); 137 | result.data = data; 138 | result["keys"] = keys; 139 | result["values"] = values; 140 | result["sensitive"] = false; // FIXME: but kOS caseSensitive attr is private so we can't currently examine it. 141 | 142 | object key, value; 143 | foreach (var item in input) 144 | { 145 | key = Serialize(item.Key); 146 | value = Serialize(item.Value); 147 | if (key is string) 148 | { 149 | data[(string)key] = value; 150 | } 151 | else 152 | { 153 | keys.Add(key); 154 | values.Add(value); 155 | } 156 | } 157 | return result; 158 | 159 | } 160 | if (s is IEnumerable) 161 | { 162 | var input = (IEnumerable)s; 163 | var t = WrappedType.Invalid; 164 | if (s is ListValue) 165 | { 166 | t = WrappedType.List; 167 | } 168 | else if (s is QueueValue) 169 | { 170 | t = WrappedType.Queue; 171 | } 172 | else if (s is StackValue) 173 | { 174 | t = WrappedType.Stack; 175 | } 176 | if(t != WrappedType.Invalid) { 177 | bool cached; 178 | var result = RefCapableWrapper(t, s, out cached); 179 | if (cached) return result; 180 | result.data = input.Select(x => Serialize(x)).ToArray(); 181 | return result; 182 | } 183 | } 184 | if (s is BodyTarget) 185 | { 186 | return new Typewrapper(WrappedType.Body, ((BodyTarget)s).Body.flightGlobalsIndex); 187 | } 188 | if (s is VesselTarget) 189 | { 190 | return new Typewrapper(WrappedType.Vessel, ((VesselTarget)s).Vessel.id); 191 | } 192 | if (s is kOS.Suffixed.Part.PartValue) { 193 | return new Typewrapper(WrappedType.Part, ((kOS.Suffixed.Part.PartValue)s).Part.flightID); 194 | } 195 | throw new SerializationException("Objects of type " + s.KOSName + " cannot be serialized in this version of KIPC."); 196 | } 197 | } 198 | } 199 | 200 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/KIPC.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {FEBE111A-D442-48BF-90B3-9135B577A4F6} 8 | Library 9 | Properties 10 | KIPC 11 | KIPCPlugin 12 | v3.5 13 | 512 14 | 15 | 16 | 17 | 18 | 19 | 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | TRACE;DEBUG 25 | prompt 26 | 4 27 | 28 | 29 | none 30 | true 31 | bin\Release\ 32 | 33 | 34 | prompt 35 | 4 36 | false 37 | 38 | 39 | 40 | ..\..\KSP\KSP_x64_Data\Managed\Assembly-CSharp.dll 41 | False 42 | global 43 | 44 | 45 | ..\..\KSP\KSP_x64_Data\Managed\Assembly-CSharp-firstpass.dll 46 | False 47 | 48 | 49 | ..\..\KSP\KSP_x64_Data\Managed\Assembly-UnityScript.dll 50 | False 51 | 52 | 53 | ..\..\KSP\KSP_x64_Data\Managed\Assembly-UnityScript-firstpass.dll 54 | False 55 | 56 | 57 | ..\packages\JsonFx.2.0.1209.2802\lib\net35\JsonFx.dll 58 | True 59 | 60 | 61 | ..\..\KSP\GameData\kOS\Plugins\kOS.dll 62 | False 63 | 64 | 65 | ..\..\KSP\GameData\kOS\Plugins\kOS.Safe.dll 66 | False 67 | 68 | 69 | ..\..\KSP\GameData\kRPC\KRPC.dll 70 | False 71 | 72 | 73 | ..\..\KSP\GameData\kRPC\KRPC.SpaceCenter.dll 74 | False 75 | 76 | 77 | ..\..\KSP\GameData\kRPC\KRPC.UI.dll 78 | False 79 | 80 | 81 | ..\..\KSP\KSP_x64_Data\Managed\KSPAssets.dll 82 | False 83 | 84 | 85 | ..\..\KSP\KSP_x64_Data\Managed\KSPCore.dll 86 | False 87 | 88 | 89 | ..\..\KSP\KSP_x64_Data\Managed\KSPUtil.dll 90 | False 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | ..\..\KSP\KSP_x64_Data\Managed\UnityEngine.dll 99 | False 100 | 101 | 102 | ..\..\KSP\KSP_x64_Data\Managed\UnityEngine.UI.dll 103 | False 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | Designer 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | powershell $(SolutionDir)\Postbuild.ps1 -BuildDir $(ProjectDir)$(OutDir) -SolutionDir $(SolutionDir) 144 | 145 | 146 | 147 | 148 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 149 | 150 | 151 | 152 | 159 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Util/Validation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Runtime.Serialization; 6 | using System.Text; 7 | 8 | using KIPC.Extensions; 9 | 10 | namespace KIPC.Util 11 | { 12 | /// 13 | /// Provides a handful of static methods for argument validation. 14 | /// 15 | public class Validation 16 | { 17 | // [Serializable] 18 | public class ElementException : ArgumentException 19 | { 20 | readonly object element; 21 | public ElementException(object element) { 22 | this.element = element; 23 | } 24 | public ElementException(object element, string message) : base(message) 25 | { 26 | this.element = element; 27 | } 28 | public ElementException(object element, string message, Exception inner) : base(message, inner) { 29 | this.element = element; 30 | } 31 | // protected ElementException( 32 | // System.Runtime.Serialization.SerializationInfo info, 33 | // System.Runtime.Serialization.StreamingContext context) : base(info, context) { } 34 | 35 | public static ElementException Wrap(object element, ArgumentException ex) 36 | { 37 | if (ex is ArgumentNullException) 38 | { 39 | return new ElementNullException(element, ex.Message, ex.InnerException); 40 | } else { 41 | return new ElementException(element, ex.Message, ex.InnerException); 42 | } 43 | } 44 | } 45 | 46 | // [Serializable] 47 | public class ElementNullException : ElementException 48 | { 49 | public ElementNullException(object element) : base(element) { } 50 | public ElementNullException(object element, string message, Exception inner) : base(element, message, inner) { } 51 | public ElementNullException(object element, string message) : base(element, message) { } 52 | //protected ElementNullException(SerializationInfo info, StreamingContext context) : base(info, context) { } 53 | } 54 | 55 | /// 56 | /// Raises an exception if the value is not of the specified type, or if it is null and allowNull is false. 57 | /// 58 | /// Required type 59 | /// Value to test. 60 | /// True if the value is allowed to be null. 61 | /// value if no exception is raised. 62 | public static void AssertType(object value, bool allowNull = false) 63 | { 64 | if (value is TType) return; 65 | if (value == null) 66 | { 67 | if (allowNull) return; 68 | throw new ArgumentNullException(); 69 | } 70 | throw new ArgumentException(); 71 | } 72 | 73 | /// 74 | /// Raises an exception if the value is not of the specified type, or if it is null and allowNull is false. 75 | /// 76 | /// Value to test. 77 | /// Required type 78 | /// True if the value is allowed to be null. 79 | public static void AssertType(object value, Type type, bool allowNull) 80 | { 81 | if (value == null) 82 | { 83 | if (allowNull) return; 84 | throw new ArgumentNullException(); 85 | } 86 | if (type.IsParentClassOf(value.GetType())) return; 87 | throw new ArgumentException(); 88 | } 89 | 90 | /// 91 | /// Raises an exception if the value is not of one of the specified types, or if it is null and allowNull is false. 92 | /// 93 | /// Value to test. 94 | /// Allowed types 95 | /// True if the value is allowed to be null. 96 | public static void AssertType(object value, IEnumerable types, bool allowNull) 97 | { 98 | if (value == null) 99 | { 100 | if (allowNull) return; 101 | throw new ArgumentNullException(); 102 | } 103 | var valueType = value.GetType(); 104 | foreach (Type type in types) 105 | { 106 | if (type.IsParentClassOf(valueType)) return; 107 | } 108 | throw new ArgumentException(); 109 | } 110 | 111 | /// 112 | /// Raises an exception if not all of the values in the collection are of the specified type or if any of them are null and allowNull is false. 113 | /// 114 | /// Required type 115 | /// Collection of values to test. 116 | /// True if values are allowed to be null. 117 | /// value if no exception is raised. 118 | public static void AssertAllOfType(IEnumerable collection, bool allowNull = false) 119 | { 120 | foreach(DictionaryEntry kvp in CountingIterator.GetKeyedEnumerable(collection)) 121 | { 122 | try 123 | { 124 | AssertType(kvp.Value, allowNull); 125 | } catch (ArgumentException ex) { 126 | throw ElementException.Wrap(kvp.Key, ex); 127 | } 128 | } 129 | return; 130 | } 131 | 132 | /// 133 | /// Raises an exception if not all of the values in the collection are of the specified type or if any of them are null and allowNull is false. 134 | /// 135 | /// Collection of values to test. 136 | /// Required type 137 | /// True if values are allowed to be null. 138 | public static void AssertAllOfType(IEnumerable collection, Type type, bool allowNull) 139 | { 140 | foreach (DictionaryEntry kvp in CountingIterator.GetKeyedEnumerable(collection)) 141 | { 142 | try 143 | { 144 | AssertType(kvp.Value, type, allowNull); 145 | } 146 | catch (ArgumentException ex) 147 | { 148 | throw ElementException.Wrap(kvp.Key, ex); 149 | } 150 | } 151 | return; 152 | } 153 | 154 | /// 155 | /// Raises an exception if not all of the values in the collection are one of the specified types or if any of them are null and allowNull is false. 156 | /// Raises an exception if the value is not of one of the specified types, or if it is null and allowNull is false. 157 | /// 158 | /// Collection of values to test. 159 | /// Allowed types 160 | /// True if values are allowed to be null. 161 | public static void AssertAllOfType(IEnumerable collection, IEnumerable types, bool allowNull) 162 | { 163 | foreach (DictionaryEntry kvp in CountingIterator.GetKeyedEnumerable(collection)) 164 | { 165 | try 166 | { 167 | AssertType(kvp.Value, types, allowNull); 168 | } 169 | catch (ArgumentException ex) 170 | { 171 | throw ElementException.Wrap(kvp.Key, ex); 172 | } 173 | } 174 | return; 175 | } 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Util/CacheDictionary.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.Serialization; 5 | using System.Text; 6 | 7 | namespace KIPC.Util 8 | { 9 | /// 10 | /// Implements a caching dictionary. 11 | /// 12 | /// A caching dictionary has an optional maximum number of elements. If additional elements are added beyond that maximum, the least recently used members 13 | /// are removed from the dictionary. 14 | /// Key type 15 | /// Value type 16 | public class CacheDictionary : Dictionary 17 | { 18 | #region Node inner class 19 | /// 20 | /// Internal representation of our linked list. We don't use the actual LinkedList since we don't care about the actual list structure, nor the value of the nodes 21 | /// We only care about their order and the ability to quickly change that. 22 | /// 23 | protected class Node 24 | { 25 | public Node prev { get; set; } = null; 26 | public Node next { get; set; } = null; 27 | public TKey value; 28 | 29 | public Node(TKey value) { 30 | this.value = value; 31 | } 32 | 33 | /// 34 | /// Inserts us after the target node, removing us from our current location if we have one. 35 | /// 36 | /// Node to be inserted after 37 | public void InsertAfter(Node node) 38 | { 39 | if (node == null) throw new ArgumentNullException(); 40 | Remove(); 41 | next = node.next; 42 | if (next != null) next.prev = this; 43 | node.next = this; 44 | this.prev = node; 45 | } 46 | 47 | /// 48 | /// Inserts us before the target node, removing us from our current location if we have one. 49 | /// 50 | /// Node to be inserted after 51 | public void InsertBefore(Node node) 52 | { 53 | if (node == null) throw new ArgumentNullException(); 54 | Remove(); 55 | prev = node.prev; 56 | if (prev != null) prev.next = this; 57 | node.prev = this; 58 | this.next = node; 59 | } 60 | 61 | public void Remove() 62 | { 63 | if (prev != null) prev.next = next; 64 | if (next != null) next.prev = prev; 65 | next = prev = null; 66 | } 67 | 68 | static public Node CreateBefore(Node node, TKey value) 69 | { 70 | Node result = new Node(value); 71 | result.InsertBefore(node); 72 | return result; 73 | } 74 | 75 | static public Node CreateAfter(Node node, TKey value) 76 | { 77 | Node result = new Node(value); 78 | result.InsertAfter(node); 79 | return result; 80 | } 81 | } 82 | #endregion 83 | 84 | #region Node properties 85 | private Node firstNode, lastNode; 86 | private void InitializeNodes() 87 | { 88 | firstNode = new Node(default(TKey)); 89 | lastNode = Node.CreateAfter(FirstNode, default(TKey)); 90 | 91 | } 92 | protected Node FirstNode { get { if (firstNode == null) InitializeNodes(); return firstNode; } } 93 | protected Node LastNode { get { if (firstNode == null) InitializeNodes(); return lastNode; } } 94 | #endregion 95 | 96 | protected int maxSize = 0; 97 | 98 | public int MaxSize 99 | { 100 | get { return maxSize; } 101 | set { maxSize = value; if (maxSize > 0) Prune(Count - maxSize); } 102 | } 103 | 104 | private Dictionary recentKeys = new Dictionary(); 105 | 106 | /// 107 | /// Bump a key to the front of the line. 108 | /// 109 | /// 110 | protected void MoveToFront(TKey key) 111 | { 112 | Node node; 113 | try 114 | { 115 | node = recentKeys[key]; 116 | } 117 | catch (KeyNotFoundException) 118 | { 119 | node = new Node(key); 120 | if (MaxSize > 0 && MaxSize < Count) 121 | { 122 | Prune(1); 123 | } 124 | } 125 | node.InsertAfter(FirstNode); 126 | recentKeys[key] = node; 127 | } 128 | 129 | /// 130 | /// Remove up to the specified number of items. Will not remove FirstNode or LastNode. 131 | /// 132 | /// # of items to remove. If zero or negative, this is a noop. 133 | protected void Prune(int count) 134 | { 135 | if (count <= 0) return; // noop 136 | var node = LastNode.prev; 137 | while(count-- > 0 && node.prev != null) 138 | { 139 | recentKeys.Remove(node.value); 140 | base.Remove(node.value); 141 | } 142 | // Now on the last node we want to keep, which might be the first node. 143 | node.next = LastNode; 144 | LastNode.prev = node; 145 | // cut off elements will be gc'd. 146 | } 147 | 148 | public CacheDictionary() : base() { } 149 | 150 | public CacheDictionary(IDictionary dictionary) : base(dictionary) { 151 | foreach(var key in Keys) { this.MoveToFront(key); } 152 | } 153 | 154 | public CacheDictionary(IEqualityComparer comparer) : base(comparer) { } 155 | 156 | public CacheDictionary(int capacity) : base(capacity) { maxSize = capacity; } 157 | 158 | public CacheDictionary(IDictionary dictionary, IEqualityComparer comparer) : base(dictionary, comparer) { 159 | foreach (var key in Keys) { this.MoveToFront(key); } 160 | } 161 | 162 | public CacheDictionary(int capacity, IEqualityComparer comparer) : base(capacity, comparer) { maxSize = capacity; } 163 | 164 | new public TValue this[TKey key] 165 | { 166 | get 167 | { 168 | // Done in this order to avoid mucking up the cache and throw an exception instead if the key doesn't exist. 169 | var result = base[key]; 170 | MoveToFront(key); 171 | return result; 172 | } 173 | set 174 | { 175 | base[key] = value; 176 | MoveToFront(key); 177 | } 178 | } 179 | 180 | new public void Add(TKey key, TValue value) 181 | { 182 | this.MoveToFront(key); 183 | base.Add(key, value); 184 | } 185 | 186 | new public bool Remove(TKey key) 187 | { 188 | if (base.Remove(key)) { 189 | recentKeys[key].Remove(); 190 | recentKeys.Remove(key); 191 | return true; 192 | } 193 | return false; 194 | } 195 | 196 | new public void Clear() 197 | { 198 | base.Clear(); 199 | recentKeys.Clear(); 200 | FirstNode.next = LastNode; 201 | LastNode.prev = FirstNode; 202 | } 203 | 204 | new public bool TryGetValue(TKey key, out TValue value) 205 | { 206 | bool result = base.TryGetValue(key, out value); 207 | if (result) MoveToFront(key); 208 | return result; 209 | } 210 | 211 | /// 212 | /// Retrieves the value of a key from the cache without moving it to the front. 213 | /// 214 | /// Key to retrieve 215 | /// 216 | public TValue Peek(TKey key) 217 | { 218 | return base[key]; 219 | } 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /plugin/KIPCPlugin/Serialization/Serializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Runtime.Serialization; 5 | using System.Reflection; 6 | using System.Linq; 7 | using kOS.Safe.Encapsulation; 8 | using UnityEngine; 9 | using KIPC.Extensions; 10 | using kOS; 11 | using JsonFx.Json; 12 | using JsonFx.Bson; 13 | 14 | namespace KIPC.Serialization 15 | { 16 | using JsonList = List; 17 | using JsonDict = Dictionary; 18 | using JsonKey = KeyValuePair; 19 | using IJsonList = IList; 20 | using IJsonDict = IDictionary; 21 | 22 | /// 23 | /// An instance of Serializer handles a single serialization run, including maintaining internal state. 24 | /// 25 | public class Serializer 26 | { 27 | public SharedObjects SharedObjects { get; private set; } 28 | 29 | public Serializer(SharedObjects sharedObjects) 30 | { 31 | SharedObjects = sharedObjects; 32 | } 33 | 34 | #region Static JSON/BSON I/O 35 | private static JsonReader jsonReader = new JsonReader( 36 | new JsonFx.Serialization.DataReaderSettings(new JsonFx.Serialization.Resolvers.PocoResolverStrategy()) 37 | ); 38 | private static JsonWriter jsonWriter = new JsonWriter( 39 | new JsonFx.Serialization.DataWriterSettings(new JsonFx.Serialization.Resolvers.PocoResolverStrategy()) 40 | ); 41 | 42 | public static string WriteJson(SharedObjects sharedObjects, object input) 43 | { 44 | return jsonWriter.Write(new Serializer(sharedObjects).Serialize(input)); 45 | } 46 | 47 | public static object ReadJson(SharedObjects sharedObjects, string input) 48 | { 49 | return new Serializer(sharedObjects).Deserialize(jsonReader.Read(input)); 50 | } 51 | #endregion 52 | #region Type Registry 53 | public static TypeRegistry registry = new TypeRegistry(); 54 | public static void RefreshTypeRegistry() 55 | { 56 | registry.RefreshTypeData(); 57 | } 58 | #endregion 59 | 60 | #region Serialization 61 | public class SerializerStateInfo 62 | { 63 | public int nextReferenceId = 1; // ID that will be assigned next time we notice a reference. 64 | public Dictionary references = new Dictionary(); // Collections that we've encountered this pass. 65 | } 66 | public SerializerStateInfo serializerState = new SerializerStateInfo(); 67 | protected int nextReferenceId = 1; // ID that will be assigned next time we notice a reference. 68 | protected Dictionary references = new Dictionary(); // Collections that we've encountered this pass. 69 | 70 | protected object MakeReference(ICollectionHandler referenced) 71 | { 72 | if (referenced.ObjectId == null) referenced.ObjectId = serializerState.nextReferenceId++; 73 | return new JsonDict { 74 | {"type", "ref" }, 75 | {"ref", referenced.ObjectId } 76 | }; 77 | } 78 | 79 | public object Serialize(object input) 80 | { 81 | // If Unity supported a modern C# version with, say, dynamic, we could go back to the overloaded methods approach 82 | // Instead of this giant mess of if-checks 83 | if (input is PrimitiveStructure) 84 | { 85 | return ((PrimitiveStructure)input).ToPrimitive(); 86 | } 87 | ICollectionHandler referenced = serializerState.references.GetValueOrDefault(input); 88 | if (referenced != null) return MakeReference(referenced); 89 | TypeHandler handler = registry.GetSerializer(input).CreateHandler(this); // Will throw on unsupported types. 90 | if (handler is ICollectionHandler) 91 | { 92 | // It's important that the reference is set up BEFORE we serialize the handler, otherwise a nested reference to the input may fail to notice 93 | // the existing reference since we haven't created it yet. 94 | serializerState.references[input] = (ICollectionHandler)handler; 95 | } 96 | return handler.ProxySerialize(input); 97 | } 98 | #endregion 99 | 100 | #region Deserialization 101 | public class DeserializerStateInfo 102 | { 103 | public Dictionary references; 104 | public Stack pending; 105 | public Dictionary results; 106 | } 107 | 108 | public DeserializerStateInfo deserializerState = null; 109 | 110 | /// 111 | /// Returns the object type identifier from the specified JSON Dict. Raises an exception if no type identifier is specified. 112 | /// 113 | /// 114 | protected object GetTypeIdentifier(IJsonDict input) 115 | { 116 | try 117 | { 118 | return input["type"]; 119 | } catch (KeyNotFoundException) { 120 | throw new SerializationException("Object type not declared."); 121 | } 122 | } 123 | 124 | /// 125 | /// Helper function for resolving references. Updates the passed list of references. Returns a non-null value if the parent container should replace 126 | /// its current item with the returned item. 127 | /// 128 | /// 129 | /// 130 | /// 131 | internal IJsonDict ResolveItem(IJsonDict item) 132 | { 133 | object typeId = GetTypeIdentifier(item); 134 | object objectId = item.GetValueOrDefault("ref"); 135 | // Debug.Log(string.Format("Identified object of type {0} -- object ID: {1}", typeId, objectId)); 136 | IJsonDict referenced = (objectId == null) ? null : deserializerState.references.GetValueOrDefault(objectId); 137 | if (typeId as string == "ref") { // Found a reference 138 | if (objectId == null) throw new SerializationException("Found a missing or null reference ID."); 139 | // This works because we don't want to replace if the item didn't exist (and thus would return NULL), 140 | // and we do want to replace if it did (and thus would return an actual value) 141 | if (referenced == null) 142 | { 143 | // Debug.Log(string.Format("Adding new pending reference to {0}", objectId)); 144 | deserializerState.references[objectId] = item; 145 | } else 146 | { 147 | // Debug.Log(string.Format("Replacing reference with actual object of type ", referenced["type"])); 148 | } 149 | return referenced; 150 | } 151 | // Still here? Okay. 152 | // Nested container check. 153 | TypeHandler handler = registry.GetDeserializer(typeId).CreateHandler(this); 154 | if (handler is ICollectionHandler) 155 | { 156 | // FIXME: See if this code is actually needed. 157 | if (item.ContainsKey("_visited")) 158 | { 159 | Debug.LogWarning("*** WARNING ***: Container already visited."); 160 | } 161 | else 162 | { 163 | item["_visited"] = true; 164 | foreach (var container in ((ICollectionHandler)handler).GetContainers(item)) 165 | { 166 | deserializerState.pending.Push(container); 167 | } 168 | } 169 | } 170 | 171 | if (objectId == null) return null; // Unreferenced object, nothing to do. 172 | if (referenced == null) 173 | { 174 | deserializerState.references[objectId] = item; 175 | // Debug.Log("Saving reference."); 176 | } 177 | else 178 | { 179 | // Already references something else. Let's hope it's a reference. 180 | if (GetTypeIdentifier(referenced) as string != "ref") 181 | { 182 | // ... nope. Complain loudly. 183 | throw new SerializationException(string.Format("Object reference '{0}' refers to multiple non-reference objects", objectId)); 184 | } 185 | // Everything we've previously seen up until now points to the old object. It's way too much of a hassle to replace it, so... 186 | // instead we clear it and copy all of our data to it. 187 | // Debug.Log(string.Format("Copying over to actual object of type ", referenced["type"])); 188 | referenced.Clear(); 189 | foreach(JsonKey kvp in item) 190 | { 191 | referenced[kvp.Key] = kvp.Value; // Resistance is futile. You will be assimilated. 192 | } 193 | // Debug.Log("Done copying over"); 194 | } 195 | return referenced; 196 | } 197 | public void ResolveReferences(ICollectionHandler handler, IJsonDict item) 198 | { 199 | deserializerState = new DeserializerStateInfo(); 200 | deserializerState.references = new Dictionary(); 201 | deserializerState.pending = new Stack(handler.GetContainers(item)); 202 | deserializerState.results = new Dictionary(); 203 | 204 | object referenceId = item.GetValueOrDefault("ref"); 205 | if (referenceId != null) deserializerState.references[referenceId] = item; 206 | 207 | IEnumerable enumerable; 208 | while (deserializerState.pending.Count > 0) 209 | { 210 | enumerable = deserializerState.pending.Pop(); 211 | // Debug.Log(string.Format("Processing queued item {0}", idgen.GetId(enumerable, out dummy))); 212 | 213 | var list = enumerable as IJsonList; 214 | if (list != null) { 215 | for (int index = 0; index < list.Count; ++index) 216 | { 217 | if ((item = list[index] as IJsonDict) == null) continue; // Not an object 218 | if ((item = ResolveItem(item)) == null) continue; // Replacement not needed 219 | list[index] = item; 220 | } 221 | continue; 222 | } 223 | var dict = enumerable as IJsonDict; 224 | if (dict != null) { 225 | foreach (JsonKey kvp in dict) 226 | { 227 | if ((item = kvp.Value as IJsonDict) == null) continue; // Not an object 228 | if ((item = ResolveItem(item)) == null) continue; // Replacement not needed. 229 | dict[kvp.Key] = item; 230 | } 231 | continue; 232 | } 233 | throw new SerializationException(string.Format("Unexpected enumerable of type {0}", enumerable.GetType().FullName)); 234 | } 235 | } 236 | 237 | public object Deserialize(object input) 238 | { 239 | if (input == null) throw new SerializationException("Encountered NULL while deserializing input."); 240 | // Primitives. 241 | input = Structure.FromPrimitive(input); 242 | if (input is Structure) return (Structure)input; 243 | IJsonDict dict = input as IJsonDict; 244 | if (dict == null) 245 | { 246 | throw new SerializationException("Deserializing from a " + input.GetType().Name + " is unsupported."); 247 | } 248 | // Get the deserializer for this object. 249 | // This will fail and throw an exception(by design) on unsupported types. 250 | // "ref" is also considered an unsupported type. If we see it here, it's either the top-level element 251 | // (in which case there are no other elements it could possibly be referencing), or we somehow failed 252 | // to replace it during the reference replacement run. 253 | TypeHandler handler = registry.GetDeserializer(GetTypeIdentifier(dict)).CreateHandler(this); 254 | ICollectionHandler ich = handler as ICollectionHandler; 255 | object result; 256 | 257 | if (ich != null) { 258 | // If we have a collection handler and haven't scanned for backrefs yet, scan for them. 259 | if (deserializerState == null) ResolveReferences(ich, dict); 260 | // Is this something we've already resolved? If so, return that reference. 261 | result = deserializerState.results.GetValueOrDefault(dict); 262 | if (result != null) 263 | { 264 | return result; 265 | } 266 | } 267 | result = handler.ProxyDeserialize(dict); 268 | if (ich != null) 269 | { 270 | deserializerState.results[dict] = result; 271 | } 272 | return result; 273 | } 274 | #endregion 275 | } 276 | } -------------------------------------------------------------------------------- /doc/LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU General Public License 2 | ========================== 3 | 4 | _Version 3, 29 June 2007_ 5 | _Copyright © 2007 Free Software Foundation, Inc. <>_ 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license 8 | document, but changing it is not allowed. 9 | 10 | ## Preamble 11 | 12 | The GNU General Public License is a free, copyleft license for software and other 13 | kinds of works. 14 | 15 | The licenses for most software and other practical works are designed to take away 16 | your freedom to share and change the works. By contrast, the GNU General Public 17 | License is intended to guarantee your freedom to share and change all versions of a 18 | program--to make sure it remains free software for all its users. We, the Free 19 | Software Foundation, use the GNU General Public License for most of our software; it 20 | applies also to any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not price. Our General 24 | Public Licenses are designed to make sure that you have the freedom to distribute 25 | copies of free software (and charge for them if you wish), that you receive source 26 | code or can get it if you want it, that you can change the software or use pieces of 27 | it in new free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you these rights or 30 | asking you to surrender the rights. Therefore, you have certain responsibilities if 31 | you distribute copies of the software, or if you modify it: responsibilities to 32 | respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether gratis or for a fee, 35 | you must pass on to the recipients the same freedoms that you received. You must make 36 | sure that they, too, receive or can get the source code. And you must show them these 37 | terms so they know their rights. 38 | 39 | Developers that use the GNU GPL protect your rights with two steps: **(1)** assert 40 | copyright on the software, and **(2)** offer you this License giving you legal permission 41 | to copy, distribute and/or modify it. 42 | 43 | For the developers' and authors' protection, the GPL clearly explains that there is 44 | no warranty for this free software. For both users' and authors' sake, the GPL 45 | requires that modified versions be marked as changed, so that their problems will not 46 | be attributed erroneously to authors of previous versions. 47 | 48 | Some devices are designed to deny users access to install or run modified versions of 49 | the software inside them, although the manufacturer can do so. This is fundamentally 50 | incompatible with the aim of protecting users' freedom to change the software. The 51 | systematic pattern of such abuse occurs in the area of products for individuals to 52 | use, which is precisely where it is most unacceptable. Therefore, we have designed 53 | this version of the GPL to prohibit the practice for those products. If such problems 54 | arise substantially in other domains, we stand ready to extend this provision to 55 | those domains in future versions of the GPL, as needed to protect the freedom of 56 | users. 57 | 58 | Finally, every program is threatened constantly by software patents. States should 59 | not allow patents to restrict development and use of software on general-purpose 60 | computers, but in those that do, we wish to avoid the special danger that patents 61 | applied to a free program could make it effectively proprietary. To prevent this, the 62 | GPL assures that patents cannot be used to render the program non-free. 63 | 64 | The precise terms and conditions for copying, distribution and modification follow. 65 | 66 | ## TERMS AND CONDITIONS 67 | 68 | ### 0. Definitions 69 | 70 | “This License” refers to version 3 of the GNU General Public License. 71 | 72 | “Copyright” also means copyright-like laws that apply to other kinds of 73 | works, such as semiconductor masks. 74 | 75 | “The Program” refers to any copyrightable work licensed under this 76 | License. Each licensee is addressed as “you”. “Licensees” and 77 | “recipients” may be individuals or organizations. 78 | 79 | To “modify” a work means to copy from or adapt all or part of the work in 80 | a fashion requiring copyright permission, other than the making of an exact copy. The 81 | resulting work is called a “modified version” of the earlier work or a 82 | work “based on” the earlier work. 83 | 84 | A “covered work” means either the unmodified Program or a work based on 85 | the Program. 86 | 87 | To “propagate” a work means to do anything with it that, without 88 | permission, would make you directly or secondarily liable for infringement under 89 | applicable copyright law, except executing it on a computer or modifying a private 90 | copy. Propagation includes copying, distribution (with or without modification), 91 | making available to the public, and in some countries other activities as well. 92 | 93 | To “convey” a work means any kind of propagation that enables other 94 | parties to make or receive copies. Mere interaction with a user through a computer 95 | network, with no transfer of a copy, is not conveying. 96 | 97 | An interactive user interface displays “Appropriate Legal Notices” to the 98 | extent that it includes a convenient and prominently visible feature that **(1)** 99 | displays an appropriate copyright notice, and **(2)** tells the user that there is no 100 | warranty for the work (except to the extent that warranties are provided), that 101 | licensees may convey the work under this License, and how to view a copy of this 102 | License. If the interface presents a list of user commands or options, such as a 103 | menu, a prominent item in the list meets this criterion. 104 | 105 | ### 1. Source Code 106 | 107 | The “source code” for a work means the preferred form of the work for 108 | making modifications to it. “Object code” means any non-source form of a 109 | work. 110 | 111 | A “Standard Interface” means an interface that either is an official 112 | standard defined by a recognized standards body, or, in the case of interfaces 113 | specified for a particular programming language, one that is widely used among 114 | developers working in that language. 115 | 116 | The “System Libraries” of an executable work include anything, other than 117 | the work as a whole, that **(a)** is included in the normal form of packaging a Major 118 | Component, but which is not part of that Major Component, and **(b)** serves only to 119 | enable use of the work with that Major Component, or to implement a Standard 120 | Interface for which an implementation is available to the public in source code form. 121 | A “Major Component”, in this context, means a major essential component 122 | (kernel, window system, and so on) of the specific operating system (if any) on which 123 | the executable work runs, or a compiler used to produce the work, or an object code 124 | interpreter used to run it. 125 | 126 | The “Corresponding Source” for a work in object code form means all the 127 | source code needed to generate, install, and (for an executable work) run the object 128 | code and to modify the work, including scripts to control those activities. However, 129 | it does not include the work's System Libraries, or general-purpose tools or 130 | generally available free programs which are used unmodified in performing those 131 | activities but which are not part of the work. For example, Corresponding Source 132 | includes interface definition files associated with source files for the work, and 133 | the source code for shared libraries and dynamically linked subprograms that the work 134 | is specifically designed to require, such as by intimate data communication or 135 | control flow between those subprograms and other parts of the work. 136 | 137 | The Corresponding Source need not include anything that users can regenerate 138 | automatically from other parts of the Corresponding Source. 139 | 140 | The Corresponding Source for a work in source code form is that same work. 141 | 142 | ### 2. Basic Permissions 143 | 144 | All rights granted under this License are granted for the term of copyright on the 145 | Program, and are irrevocable provided the stated conditions are met. This License 146 | explicitly affirms your unlimited permission to run the unmodified Program. The 147 | output from running a covered work is covered by this License only if the output, 148 | given its content, constitutes a covered work. This License acknowledges your rights 149 | of fair use or other equivalent, as provided by copyright law. 150 | 151 | You may make, run and propagate covered works that you do not convey, without 152 | conditions so long as your license otherwise remains in force. You may convey covered 153 | works to others for the sole purpose of having them make modifications exclusively 154 | for you, or provide you with facilities for running those works, provided that you 155 | comply with the terms of this License in conveying all material for which you do not 156 | control copyright. Those thus making or running the covered works for you must do so 157 | exclusively on your behalf, under your direction and control, on terms that prohibit 158 | them from making any copies of your copyrighted material outside their relationship 159 | with you. 160 | 161 | Conveying under any other circumstances is permitted solely under the conditions 162 | stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 163 | 164 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law 165 | 166 | No covered work shall be deemed part of an effective technological measure under any 167 | applicable law fulfilling obligations under article 11 of the WIPO copyright treaty 168 | adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention 169 | of such measures. 170 | 171 | When you convey a covered work, you waive any legal power to forbid circumvention of 172 | technological measures to the extent such circumvention is effected by exercising 173 | rights under this License with respect to the covered work, and you disclaim any 174 | intention to limit operation or modification of the work as a means of enforcing, 175 | against the work's users, your or third parties' legal rights to forbid circumvention 176 | of technological measures. 177 | 178 | ### 4. Conveying Verbatim Copies 179 | 180 | You may convey verbatim copies of the Program's source code as you receive it, in any 181 | medium, provided that you conspicuously and appropriately publish on each copy an 182 | appropriate copyright notice; keep intact all notices stating that this License and 183 | any non-permissive terms added in accord with section 7 apply to the code; keep 184 | intact all notices of the absence of any warranty; and give all recipients a copy of 185 | this License along with the Program. 186 | 187 | You may charge any price or no price for each copy that you convey, and you may offer 188 | support or warranty protection for a fee. 189 | 190 | ### 5. Conveying Modified Source Versions 191 | 192 | You may convey a work based on the Program, or the modifications to produce it from 193 | the Program, in the form of source code under the terms of section 4, provided that 194 | you also meet all of these conditions: 195 | 196 | * **a)** The work must carry prominent notices stating that you modified it, and giving a 197 | relevant date. 198 | * **b)** The work must carry prominent notices stating that it is released under this 199 | License and any conditions added under section 7. This requirement modifies the 200 | requirement in section 4 to “keep intact all notices”. 201 | * **c)** You must license the entire work, as a whole, under this License to anyone who 202 | comes into possession of a copy. This License will therefore apply, along with any 203 | applicable section 7 additional terms, to the whole of the work, and all its parts, 204 | regardless of how they are packaged. This License gives no permission to license the 205 | work in any other way, but it does not invalidate such permission if you have 206 | separately received it. 207 | * **d)** If the work has interactive user interfaces, each must display Appropriate Legal 208 | Notices; however, if the Program has interactive interfaces that do not display 209 | Appropriate Legal Notices, your work need not make them do so. 210 | 211 | A compilation of a covered work with other separate and independent works, which are 212 | not by their nature extensions of the covered work, and which are not combined with 213 | it such as to form a larger program, in or on a volume of a storage or distribution 214 | medium, is called an “aggregate” if the compilation and its resulting 215 | copyright are not used to limit the access or legal rights of the compilation's users 216 | beyond what the individual works permit. Inclusion of a covered work in an aggregate 217 | does not cause this License to apply to the other parts of the aggregate. 218 | 219 | ### 6. Conveying Non-Source Forms 220 | 221 | You may convey a covered work in object code form under the terms of sections 4 and 222 | 5, provided that you also convey the machine-readable Corresponding Source under the 223 | terms of this License, in one of these ways: 224 | 225 | * **a)** Convey the object code in, or embodied in, a physical product (including a 226 | physical distribution medium), accompanied by the Corresponding Source fixed on a 227 | durable physical medium customarily used for software interchange. 228 | * **b)** Convey the object code in, or embodied in, a physical product (including a 229 | physical distribution medium), accompanied by a written offer, valid for at least 230 | three years and valid for as long as you offer spare parts or customer support for 231 | that product model, to give anyone who possesses the object code either **(1)** a copy of 232 | the Corresponding Source for all the software in the product that is covered by this 233 | License, on a durable physical medium customarily used for software interchange, for 234 | a price no more than your reasonable cost of physically performing this conveying of 235 | source, or **(2)** access to copy the Corresponding Source from a network server at no 236 | charge. 237 | * **c)** Convey individual copies of the object code with a copy of the written offer to 238 | provide the Corresponding Source. This alternative is allowed only occasionally and 239 | noncommercially, and only if you received the object code with such an offer, in 240 | accord with subsection 6b. 241 | * **d)** Convey the object code by offering access from a designated place (gratis or for 242 | a charge), and offer equivalent access to the Corresponding Source in the same way 243 | through the same place at no further charge. You need not require recipients to copy 244 | the Corresponding Source along with the object code. If the place to copy the object 245 | code is a network server, the Corresponding Source may be on a different server 246 | (operated by you or a third party) that supports equivalent copying facilities, 247 | provided you maintain clear directions next to the object code saying where to find 248 | the Corresponding Source. Regardless of what server hosts the Corresponding Source, 249 | you remain obligated to ensure that it is available for as long as needed to satisfy 250 | these requirements. 251 | * **e)** Convey the object code using peer-to-peer transmission, provided you inform 252 | other peers where the object code and Corresponding Source of the work are being 253 | offered to the general public at no charge under subsection 6d. 254 | 255 | A separable portion of the object code, whose source code is excluded from the 256 | Corresponding Source as a System Library, need not be included in conveying the 257 | object code work. 258 | 259 | A “User Product” is either **(1)** a “consumer product”, which 260 | means any tangible personal property which is normally used for personal, family, or 261 | household purposes, or **(2)** anything designed or sold for incorporation into a 262 | dwelling. In determining whether a product is a consumer product, doubtful cases 263 | shall be resolved in favor of coverage. For a particular product received by a 264 | particular user, “normally used” refers to a typical or common use of 265 | that class of product, regardless of the status of the particular user or of the way 266 | in which the particular user actually uses, or expects or is expected to use, the 267 | product. A product is a consumer product regardless of whether the product has 268 | substantial commercial, industrial or non-consumer uses, unless such uses represent 269 | the only significant mode of use of the product. 270 | 271 | “Installation Information” for a User Product means any methods, 272 | procedures, authorization keys, or other information required to install and execute 273 | modified versions of a covered work in that User Product from a modified version of 274 | its Corresponding Source. The information must suffice to ensure that the continued 275 | functioning of the modified object code is in no case prevented or interfered with 276 | solely because modification has been made. 277 | 278 | If you convey an object code work under this section in, or with, or specifically for 279 | use in, a User Product, and the conveying occurs as part of a transaction in which 280 | the right of possession and use of the User Product is transferred to the recipient 281 | in perpetuity or for a fixed term (regardless of how the transaction is 282 | characterized), the Corresponding Source conveyed under this section must be 283 | accompanied by the Installation Information. But this requirement does not apply if 284 | neither you nor any third party retains the ability to install modified object code 285 | on the User Product (for example, the work has been installed in ROM). 286 | 287 | The requirement to provide Installation Information does not include a requirement to 288 | continue to provide support service, warranty, or updates for a work that has been 289 | modified or installed by the recipient, or for the User Product in which it has been 290 | modified or installed. Access to a network may be denied when the modification itself 291 | materially and adversely affects the operation of the network or violates the rules 292 | and protocols for communication across the network. 293 | 294 | Corresponding Source conveyed, and Installation Information provided, in accord with 295 | this section must be in a format that is publicly documented (and with an 296 | implementation available to the public in source code form), and must require no 297 | special password or key for unpacking, reading or copying. 298 | 299 | ### 7. Additional Terms 300 | 301 | “Additional permissions” are terms that supplement the terms of this 302 | License by making exceptions from one or more of its conditions. Additional 303 | permissions that are applicable to the entire Program shall be treated as though they 304 | were included in this License, to the extent that they are valid under applicable 305 | law. If additional permissions apply only to part of the Program, that part may be 306 | used separately under those permissions, but the entire Program remains governed by 307 | this License without regard to the additional permissions. 308 | 309 | When you convey a copy of a covered work, you may at your option remove any 310 | additional permissions from that copy, or from any part of it. (Additional 311 | permissions may be written to require their own removal in certain cases when you 312 | modify the work.) You may place additional permissions on material, added by you to a 313 | covered work, for which you have or can give appropriate copyright permission. 314 | 315 | Notwithstanding any other provision of this License, for material you add to a 316 | covered work, you may (if authorized by the copyright holders of that material) 317 | supplement the terms of this License with terms: 318 | 319 | * **a)** Disclaiming warranty or limiting liability differently from the terms of 320 | sections 15 and 16 of this License; or 321 | * **b)** Requiring preservation of specified reasonable legal notices or author 322 | attributions in that material or in the Appropriate Legal Notices displayed by works 323 | containing it; or 324 | * **c)** Prohibiting misrepresentation of the origin of that material, or requiring that 325 | modified versions of such material be marked in reasonable ways as different from the 326 | original version; or 327 | * **d)** Limiting the use for publicity purposes of names of licensors or authors of the 328 | material; or 329 | * **e)** Declining to grant rights under trademark law for use of some trade names, 330 | trademarks, or service marks; or 331 | * **f)** Requiring indemnification of licensors and authors of that material by anyone 332 | who conveys the material (or modified versions of it) with contractual assumptions of 333 | liability to the recipient, for any liability that these contractual assumptions 334 | directly impose on those licensors and authors. 335 | 336 | All other non-permissive additional terms are considered “further 337 | restrictions” within the meaning of section 10. If the Program as you received 338 | it, or any part of it, contains a notice stating that it is governed by this License 339 | along with a term that is a further restriction, you may remove that term. If a 340 | license document contains a further restriction but permits relicensing or conveying 341 | under this License, you may add to a covered work material governed by the terms of 342 | that license document, provided that the further restriction does not survive such 343 | relicensing or conveying. 344 | 345 | If you add terms to a covered work in accord with this section, you must place, in 346 | the relevant source files, a statement of the additional terms that apply to those 347 | files, or a notice indicating where to find the applicable terms. 348 | 349 | Additional terms, permissive or non-permissive, may be stated in the form of a 350 | separately written license, or stated as exceptions; the above requirements apply 351 | either way. 352 | 353 | ### 8. Termination 354 | 355 | You may not propagate or modify a covered work except as expressly provided under 356 | this License. Any attempt otherwise to propagate or modify it is void, and will 357 | automatically terminate your rights under this License (including any patent licenses 358 | granted under the third paragraph of section 11). 359 | 360 | However, if you cease all violation of this License, then your license from a 361 | particular copyright holder is reinstated **(a)** provisionally, unless and until the 362 | copyright holder explicitly and finally terminates your license, and **(b)** permanently, 363 | if the copyright holder fails to notify you of the violation by some reasonable means 364 | prior to 60 days after the cessation. 365 | 366 | Moreover, your license from a particular copyright holder is reinstated permanently 367 | if the copyright holder notifies you of the violation by some reasonable means, this 368 | is the first time you have received notice of violation of this License (for any 369 | work) from that copyright holder, and you cure the violation prior to 30 days after 370 | your receipt of the notice. 371 | 372 | Termination of your rights under this section does not terminate the licenses of 373 | parties who have received copies or rights from you under this License. If your 374 | rights have been terminated and not permanently reinstated, you do not qualify to 375 | receive new licenses for the same material under section 10. 376 | 377 | ### 9. Acceptance Not Required for Having Copies 378 | 379 | You are not required to accept this License in order to receive or run a copy of the 380 | Program. Ancillary propagation of a covered work occurring solely as a consequence of 381 | using peer-to-peer transmission to receive a copy likewise does not require 382 | acceptance. However, nothing other than this License grants you permission to 383 | propagate or modify any covered work. These actions infringe copyright if you do not 384 | accept this License. Therefore, by modifying or propagating a covered work, you 385 | indicate your acceptance of this License to do so. 386 | 387 | ### 10. Automatic Licensing of Downstream Recipients 388 | 389 | Each time you convey a covered work, the recipient automatically receives a license 390 | from the original licensors, to run, modify and propagate that work, subject to this 391 | License. You are not responsible for enforcing compliance by third parties with this 392 | License. 393 | 394 | An “entity transaction” is a transaction transferring control of an 395 | organization, or substantially all assets of one, or subdividing an organization, or 396 | merging organizations. If propagation of a covered work results from an entity 397 | transaction, each party to that transaction who receives a copy of the work also 398 | receives whatever licenses to the work the party's predecessor in interest had or 399 | could give under the previous paragraph, plus a right to possession of the 400 | Corresponding Source of the work from the predecessor in interest, if the predecessor 401 | has it or can get it with reasonable efforts. 402 | 403 | You may not impose any further restrictions on the exercise of the rights granted or 404 | affirmed under this License. For example, you may not impose a license fee, royalty, 405 | or other charge for exercise of rights granted under this License, and you may not 406 | initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging 407 | that any patent claim is infringed by making, using, selling, offering for sale, or 408 | importing the Program or any portion of it. 409 | 410 | ### 11. Patents 411 | 412 | A “contributor” is a copyright holder who authorizes use under this 413 | License of the Program or a work on which the Program is based. The work thus 414 | licensed is called the contributor's “contributor version”. 415 | 416 | A contributor's “essential patent claims” are all patent claims owned or 417 | controlled by the contributor, whether already acquired or hereafter acquired, that 418 | would be infringed by some manner, permitted by this License, of making, using, or 419 | selling its contributor version, but do not include claims that would be infringed 420 | only as a consequence of further modification of the contributor version. For 421 | purposes of this definition, “control” includes the right to grant patent 422 | sublicenses in a manner consistent with the requirements of this License. 423 | 424 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license 425 | under the contributor's essential patent claims, to make, use, sell, offer for sale, 426 | import and otherwise run, modify and propagate the contents of its contributor 427 | version. 428 | 429 | In the following three paragraphs, a “patent license” is any express 430 | agreement or commitment, however denominated, not to enforce a patent (such as an 431 | express permission to practice a patent or covenant not to sue for patent 432 | infringement). To “grant” such a patent license to a party means to make 433 | such an agreement or commitment not to enforce a patent against the party. 434 | 435 | If you convey a covered work, knowingly relying on a patent license, and the 436 | Corresponding Source of the work is not available for anyone to copy, free of charge 437 | and under the terms of this License, through a publicly available network server or 438 | other readily accessible means, then you must either **(1)** cause the Corresponding 439 | Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the 440 | patent license for this particular work, or **(3)** arrange, in a manner consistent with 441 | the requirements of this License, to extend the patent license to downstream 442 | recipients. “Knowingly relying” means you have actual knowledge that, but 443 | for the patent license, your conveying the covered work in a country, or your 444 | recipient's use of the covered work in a country, would infringe one or more 445 | identifiable patents in that country that you have reason to believe are valid. 446 | 447 | If, pursuant to or in connection with a single transaction or arrangement, you 448 | convey, or propagate by procuring conveyance of, a covered work, and grant a patent 449 | license to some of the parties receiving the covered work authorizing them to use, 450 | propagate, modify or convey a specific copy of the covered work, then the patent 451 | license you grant is automatically extended to all recipients of the covered work and 452 | works based on it. 453 | 454 | A patent license is “discriminatory” if it does not include within the 455 | scope of its coverage, prohibits the exercise of, or is conditioned on the 456 | non-exercise of one or more of the rights that are specifically granted under this 457 | License. You may not convey a covered work if you are a party to an arrangement with 458 | a third party that is in the business of distributing software, under which you make 459 | payment to the third party based on the extent of your activity of conveying the 460 | work, and under which the third party grants, to any of the parties who would receive 461 | the covered work from you, a discriminatory patent license **(a)** in connection with 462 | copies of the covered work conveyed by you (or copies made from those copies), or **(b)** 463 | primarily for and in connection with specific products or compilations that contain 464 | the covered work, unless you entered into that arrangement, or that patent license 465 | was granted, prior to 28 March 2007. 466 | 467 | Nothing in this License shall be construed as excluding or limiting any implied 468 | license or other defenses to infringement that may otherwise be available to you 469 | under applicable patent law. 470 | 471 | ### 12. No Surrender of Others' Freedom 472 | 473 | If conditions are imposed on you (whether by court order, agreement or otherwise) 474 | that contradict the conditions of this License, they do not excuse you from the 475 | conditions of this License. If you cannot convey a covered work so as to satisfy 476 | simultaneously your obligations under this License and any other pertinent 477 | obligations, then as a consequence you may not convey it at all. For example, if you 478 | agree to terms that obligate you to collect a royalty for further conveying from 479 | those to whom you convey the Program, the only way you could satisfy both those terms 480 | and this License would be to refrain entirely from conveying the Program. 481 | 482 | ### 13. Use with the GNU Affero General Public License 483 | 484 | Notwithstanding any other provision of this License, you have permission to link or 485 | combine any covered work with a work licensed under version 3 of the GNU Affero 486 | General Public License into a single combined work, and to convey the resulting work. 487 | The terms of this License will continue to apply to the part which is the covered 488 | work, but the special requirements of the GNU Affero General Public License, section 489 | 13, concerning interaction through a network will apply to the combination as such. 490 | 491 | ### 14. Revised Versions of this License 492 | 493 | The Free Software Foundation may publish revised and/or new versions of the GNU 494 | General Public License from time to time. Such new versions will be similar in spirit 495 | to the present version, but may differ in detail to address new problems or concerns. 496 | 497 | Each version is given a distinguishing version number. If the Program specifies that 498 | a certain numbered version of the GNU General Public License “or any later 499 | version” applies to it, you have the option of following the terms and 500 | conditions either of that numbered version or of any later version published by the 501 | Free Software Foundation. If the Program does not specify a version number of the GNU 502 | General Public License, you may choose any version ever published by the Free 503 | Software Foundation. 504 | 505 | If the Program specifies that a proxy can decide which future versions of the GNU 506 | General Public License can be used, that proxy's public statement of acceptance of a 507 | version permanently authorizes you to choose that version for the Program. 508 | 509 | Later license versions may give you additional or different permissions. However, no 510 | additional obligations are imposed on any author or copyright holder as a result of 511 | your choosing to follow a later version. 512 | 513 | ### 15. Disclaimer of Warranty 514 | 515 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 516 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 517 | PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER 518 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 519 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE 520 | QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 521 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 522 | 523 | ### 16. Limitation of Liability 524 | 525 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY 526 | COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS 527 | PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, 528 | INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 529 | PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE 530 | OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE 531 | WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 532 | POSSIBILITY OF SUCH DAMAGES. 533 | 534 | ### 17. Interpretation of Sections 15 and 16 535 | 536 | If the disclaimer of warranty and limitation of liability provided above cannot be 537 | given local legal effect according to their terms, reviewing courts shall apply local 538 | law that most closely approximates an absolute waiver of all civil liability in 539 | connection with the Program, unless a warranty or assumption of liability accompanies 540 | a copy of the Program in return for a fee. 541 | 542 | _END OF TERMS AND CONDITIONS_ 543 | 544 | ## How to Apply These Terms to Your New Programs 545 | 546 | If you develop a new program, and you want it to be of the greatest possible use to 547 | the public, the best way to achieve this is to make it free software which everyone 548 | can redistribute and change under these terms. 549 | 550 | To do so, attach the following notices to the program. It is safest to attach them 551 | to the start of each source file to most effectively state the exclusion of warranty; 552 | and each file should have at least the “copyright” line and a pointer to 553 | where the full notice is found. 554 | 555 | 556 | Copyright (C) 557 | 558 | This program is free software: you can redistribute it and/or modify 559 | it under the terms of the GNU General Public License as published by 560 | the Free Software Foundation, either version 3 of the License, or 561 | (at your option) any later version. 562 | 563 | This program is distributed in the hope that it will be useful, 564 | but WITHOUT ANY WARRANTY; without even the implied warranty of 565 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 566 | GNU General Public License for more details. 567 | 568 | You should have received a copy of the GNU General Public License 569 | along with this program. If not, see . 570 | 571 | Also add information on how to contact you by electronic and paper mail. 572 | 573 | If the program does terminal interaction, make it output a short notice like this 574 | when it starts in an interactive mode: 575 | 576 | Copyright (C) 577 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. 578 | This is free software, and you are welcome to redistribute it 579 | under certain conditions; type 'show c' for details. 580 | 581 | The hypothetical commands `show w` and `show c` should show the appropriate parts of 582 | the General Public License. Of course, your program's commands might be different; 583 | for a GUI interface, you would use an “about box”. 584 | 585 | You should also get your employer (if you work as a programmer) or school, if any, to 586 | sign a “copyright disclaimer” for the program, if necessary. For more 587 | information on this, and how to apply and follow the GNU GPL, see 588 | <>. 589 | 590 | The GNU General Public License does not permit incorporating your program into 591 | proprietary programs. If your program is a subroutine library, you may consider it 592 | more useful to permit linking proprietary applications with the library. If this is 593 | what you want to do, use the GNU Lesser General Public License instead of this 594 | License. But first, please read 595 | <>. --------------------------------------------------------------------------------