public void ResourceSet2XmlTest() { // create a sample resource set var resourceSet = new ResourceSet("el-GR") { { "key1", new ResourceItem { Name = "key1", Value = "value1" } }, { "key2", new ResourceItem { Name = "key2", Value = "value2" } }, { "key3", new ResourceItem { Name = "key3", Value = "value3" } }, { "key4", new ResourceItem { Name = "key4", Value = "value4" } }, { "key5", new ResourceItem { Name = "key5", Value = "value5" } } }; // do the actual job (convertion from resource set to xml memory stream) var stream = new MemoryStream(); ResXResourceBundleAdapter_Accessor.ResourceSet2Resx(resourceSet, stream, "ResxConvertFrom.xslt"); stream.Position = 0; // move position of stream to beginning to be ready for reading later // write to temporary file for debugging Console.WriteLine(Encoding.Default.GetString(stream.ToArray())); // convert the xml memory stream into xml document to help assertion of the result var xmlDoc = new XmlDocument(); xmlDoc.Load(stream); // assert the result var rootNode = xmlDoc.SelectSingleNode("//VIPTunnel/strings"); Assert.IsNotNull(rootNode); Assert.AreEqual(5, rootNode.ChildNodes.Count); Assert.IsNotNull(rootNode.SelectSingleNode("key1")); Assert.IsNotNull(rootNode.SelectSingleNode("key1").Attributes.GetNamedItem("text")); Assert.AreEqual("value1", rootNode.SelectSingleNode("key1").Attributes.GetNamedItem("text").Value); }
IEnumerable<string> Combine(ResourceSet set) { var locator = locators[set.Type]; var minifier = minifiers[set.Type]; return set.Names.Select(vp => minifier.Minify(Server.MapPath(locator.GetVirtualPath(vp)))); }
internal Resource(ResourceSet parent, XElement xe) { ParentSet = parent; Path = xe.Attr<string>(SchemaConstants.Resource.Path); if (Path.Contains("${")) { Path.Split('$').ToList().ForEach(p => { if (p.Contains('{')) { string resourceSetting = p.Split(new char[] {'{', '}'})[1]; String resourceContent = ConfigurationManager.AppSettings[resourceSetting]; if (String.IsNullOrEmpty(resourceContent)) { resourceContent = "empty"; } Path = Path.Replace("${" + resourceSetting + "}", resourceContent); } }); } Mode = xe.Attr(SchemaConstants.Resource.Mode, Default.Resource.Mode); if (Mode == ResourceMode.Auto) { Mode = Path.StartsWith("http") ? ResourceMode.Dynamic : ResourceMode.Static; } ForwardCookie = xe.Attr(SchemaConstants.Resource.ForwardCookie, Default.Resource.ForwardCookie); Minifier = ParentSet.Type == ResourceType.JS ? ModelUtils.LoadMinifier(xe, SchemaConstants.Resource.MinifierRef, ParentSet.Minifier.Name, ParentSet.Settings.JSMinifierMap) : ModelUtils.LoadMinifier(xe, SchemaConstants.Resource.MinifierRef, ParentSet.Minifier.Name, ParentSet.Settings.CssMinifierMap); if (Mode == ResourceMode.Static && ForwardCookie) throw new XmlSchemaException("ForwardCookie must not be True when Mode is Static"); }
/// <inheritdoc cref="IResourceMinifier.Minify" /> public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent) { var compressor = new CssCompressor(); compressor.LineBreakPosition = LineBreakPosition == null ? -1 : LineBreakPosition.Value; compressor.RemoveComments = RemoveComments == null ? true : RemoveComments.Value; return compressor.Compress(combinedContent); }
public string TransformContent(ResourceSet resourceSet, IEnumerable<Resource> resources, string content) { string rsrcs = "namespace(\"Parking.Templates\"); "; rsrcs += "(function(undefined) { "; rsrcs += "Parking.Templates = { " + content.Replace("',;","',") + " \"ping\":\"pong\" };"; rsrcs += "})();"; return rsrcs; }
/// <inheritdoc cref="IResourceMinifier.Minify" /> public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent) { var level = (ClosureCodeRequest.CompilationLevel)CompilationLevel.ConvertToType( typeof(ClosureCodeRequest.CompilationLevel), ClosureCodeRequest.CompilationLevel.SIMPLE_OPTIMIZATIONS); var request = new ClosureCodeRequest(ApiUrl, level, combinedContent); return request.GetCode(); }
internal Resource(ResourceSet parent, Resource copy) { ParentSet = parent; Path = copy.Path; Mode = copy.Mode; ForwardCookie = copy.ForwardCookie; Minifier = copy.Minifier; }
/// <inheritdoc cref="IResourceMinifier.Minify" /> public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent) { var type = (CssCompressionType)CssCompressionType.ConvertToType( typeof(CssCompressionType), Yahoo.Yui.Compressor.CssCompressionType.StockYuiCompressor); return CssCompressor.Compress(combinedContent, ColumnWidth == null ? -1 : ColumnWidth.Value, type); }
public string TransformContent(ResourceSet resourceSet, Resource resource, string content) { var extension = Path.GetExtension(resource.Path); if (extension != null && !extension.Equals(".coffee", StringComparison.InvariantCultureIgnoreCase)) return content; var engine = new CoffeeSharp.CoffeeScriptEngine(); return engine.Compile(content, filename: resource.Path); }
private static IEnumerable<AutoTranslationItem> GetValuesForTranslation(ResourceSet sourceResourceSet) { return from p in sourceResourceSet where !p.Value.Locked && p.Value is ResourceStringItem && !StringTools.ValueNullOrEmpty(p.Value.Value) select new AutoTranslationItem { Key = p.Key, Text = (string)p.Value.Value }; }
/// <inheritdoc cref="IResourceMinifier.Minify" /> public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent) { return JavaScriptCompressor.Compress(combinedContent, IsVerboseLogging == null ? false : IsVerboseLogging.Value, IsObfuscateJavascript == null ? true : IsObfuscateJavascript.Value, PreserveAllSemicolons == null ? false : PreserveAllSemicolons.Value, DisableOptimizations == null ? false : DisableOptimizations.Value, LineBreakPosition == null ? -1 : LineBreakPosition.Value, Encoding.UTF8, CultureInfo.InvariantCulture); }
/// <inheritdoc cref="IResourceMinifier.Minify" /> public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent) { var outputMode = (OutputMode)OutputMode.ConvertToType( typeof(OutputMode), Microsoft.Ajax.Utilities.OutputMode.SingleLine); var codeSettings = new CssSettings() { OutputMode = outputMode, MinifyExpressions = MinifyExpressions == null ? true : MinifyExpressions.Value, }; return new Minifier().MinifyStyleSheet(combinedContent, codeSettings); }
public IEnumerable<string> Resolve(ResourceSet resourceSet) { var locator = locators[resourceSet.Type]; //If any file changes, I need a new URL. //Therefore, I add all of the timestamps //of all of the files. Since they will //never decrease, there is no risk that //two changes might cancel eachother out var version = resourceSet.Names.Sum(vp => File.GetLastWriteTimeUtc(server.MapPath(locator.GetVirtualPath(vp))).Ticks); yield return url.Action(resourceSet.Type.ToString(), "Resources", new { id = resourceSet.SetName, version }); }
public static void Main(String[] args) { String assemblyFilename = "testserialization.dll"; String assemblyName = "testserialization"; AssemblyName aName = new AssemblyName(); aName.Name = assemblyName; String fqNamespace = "Newmoon.CompiledModules."+assemblyName; AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save, "."); assemblyBuilder.DefineDynamicModule(fqNamespace + "." + assemblyName, assemblyFilename, false); IResourceWriter rw = assemblyBuilder.DefineResource("literals", "Literal Scheme Data", "testserialization.resource"); StringReader sr = new StringReader("(hello #(world 1 2) 3 4 \"five\" #t)"); object o = Newmoon.Reader.Read(sr); o = new Pair(o, o); rw.AddResource("literal data", o); assemblyBuilder.Save(assemblyFilename); System.Console.WriteLine(o); FileStream fs = new FileStream("testserialization.output", FileMode.OpenOrCreate); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, o); fs.Close(); fs = new FileStream("testserialization.output", FileMode.Open); bf = new BinaryFormatter(); object p = bf.Deserialize(fs); System.Console.WriteLine(p); System.Console.WriteLine(p is Pair); System.Console.WriteLine(p == o); System.Console.WriteLine(((Pair) p).Car == ((Pair) p).Cdr); Assembly na = Assembly.LoadFrom(assemblyFilename); Stream rrs = na.GetManifestResourceStream("literals"); ResourceSet rr = new ResourceSet(rrs); System.Console.WriteLine("p2 "+rr.GetObject("literal data")); }
/// <inheritdoc cref="IResourceMinifier.Minify" /> public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent) { var compressor = new JavaScriptCompressor(); compressor.Encoding = Encoding.UTF8; compressor.ThreadCulture = CultureInfo.InvariantCulture; compressor.LoggingType = IsVerboseLogging == true ? LoggingType.Debug : LoggingType.None; compressor.PreserveAllSemicolons = PreserveAllSemicolons == null ? false : PreserveAllSemicolons.Value; compressor.DisableOptimizations = DisableOptimizations == null ? false : DisableOptimizations.Value; compressor.LineBreakPosition = LineBreakPosition == null ? -1 : LineBreakPosition.Value; compressor.IgnoreEval = IgnoreEval == null ? true : IgnoreEval.Value; compressor.ObfuscateJavascript = ObfuscateJavascript == null ? true : ObfuscateJavascript.Value; return compressor.Compress(combinedContent); }
internal Resource(ResourceSet parent, XElement xe) { ParentSet = parent; Path = xe.Attr<string>(SchemaConstants.Resource.Path); Mode = xe.Attr(SchemaConstants.Resource.Mode, Default.Resource.Mode); ForwardCookie = xe.Attr(SchemaConstants.Resource.ForwardCookie, Default.Resource.ForwardCookie); Minifier = ParentSet.Type == ResourceType.JS ? ModelUtils.LoadMinifier(xe, SchemaConstants.Resource.MinifierRef, ParentSet.Minifier.Name, ParentSet.Settings.JSMinifierMap) : ModelUtils.LoadMinifier(xe, SchemaConstants.Resource.MinifierRef, ParentSet.Minifier.Name, ParentSet.Settings.CssMinifierMap); if (Mode == ResourceMode.Static && ForwardCookie) throw new XmlSchemaException("ForwardCookie must not be True when Mode is Static"); }
public string TransformContent(ResourceSet resourceSet, Resource resource, string content) { content += " namespace(\"Parking.Resources.i18n\");"; Dictionary<string, string> en = Utilities.GetResources("en-US"); Dictionary<string, string> es = Utilities.GetResources("es-MX"); //Func<string, Dictionary<string, string>> toJSON = //ServiceStack.Text.JsonExtensions. string jsEn = string.Format("resx['i18n']['en-US'] = {0};", en.ToJson()); string jsEs = string.Format("resx['i18n']['es-MX'] = {0};", es.ToJson()); content += " (function(resx, undefined) { " + jsEn + jsEs + " })(Parking.Resources);"; return content; }
///<summary>Returns tags that reference a resource set.</summary> public static MvcHtmlString ResourceSet(this HtmlHelper html, ResourceSet set) { if (html == null) throw new ArgumentNullException("html"); if (set == null) throw new ArgumentNullException("set"); var resolver = Container.Resolve<IResourceResolver>(); return MvcHtmlString.Create( String.Join(Environment.NewLine, resolver.Resolve(set).Select(url => set.Type.CreateTag(url)) ) ); }
public void Initialize() { MyProcessInfo = new ProcessInfo() { Status = ProcessInfo.StatusCode.Initializing, Type = ProcessInfo.ProcessType.BalloonStore, Label = Options.Label }; RegistryEndPoint = new PublicEndPoint(Options.Registry); GameManagerEndPoint = new PublicEndPoint(Options.GameManagerEndPoint); Identity = new IdentityInfo() { Alias = Options.Alias, ANumber = Options.ANumber, FirstName = Options.FirstName, LastName = Options.LastName }; SetupCommSubsystem(new BalloonStoreConversationFactory() { DefaultMaxRetries = Options.Retries, DefaultTimeout = Options.Timeout, Process = this }, minPort: Options.MinPort, maxPort: Options.MaxPort); Game = new GameInfo(); PennyBankPublicKey = new PublicKey(); WaterSources = new List<GameProcessData>(); BalloonStores = new List<GameProcessData>(); UmbrellaSuppliers = new List<GameProcessData>(); Players = new List<GameProcessData>(); Balloons = new ResourceSet<Balloon>(); CachedPennies = new List<Penny>(); rsa = new RSACryptoServiceProvider(); rsaSigner = new RSAPKCS1SignatureFormatter(rsa); rsaSigner.SetHashAlgorithm("SHA1"); Hasher = new SHA1Managed(); RSAParameters parameters = rsa.ExportParameters(false); PublicKey = new PublicKey() { Exponent = parameters.Exponent, Modulus = parameters.Modulus }; NextId = 0; NumIds = 0; }
/// <summary> /// Copies all values from source to target resource set /// </summary> private static void CopyResourceSetContent(ResourceSet source, ResourceSet target, BaseValuesFilter filter) { foreach (var sourceResourceItem in source.Values.Where(p => !p.Locked)) { if (!target.ContainsKey(sourceResourceItem.Name)) { var targetResourceItem = new ResourceItem(); targetResourceItem.Name = sourceResourceItem.Name; targetResourceItem.Value = sourceResourceItem.Value; target.Add(sourceResourceItem.Name, targetResourceItem); } else { if (target[sourceResourceItem.Name].ValueEmpty || filter == BaseValuesFilter.AllUnlocked) { target[sourceResourceItem.Name].Value = sourceResourceItem.Value; } } } }
/// <inheritdoc cref="IVersionGenerator.Generate" /> public string Generate(ResourceSet rs) { if (Log.IsDebugEnabled) Log.Debug("Computing hash for set " + rs.Name + ". Current hash: " + rs.Hash); var contributingFactors = new StringBuilder(rs.DebugEnabled.ToString()); rs.Filters.ToList().ForEach(f => contributingFactors.Append(f.GetHashCode().ToString())); rs.CacheVaryProviders.ToList().ForEach(f => contributingFactors.Append(f.GetHashCode().ToString())); rs.Resources.ToList().ForEach(r => { contributingFactors.Append(r.ReadFromCache(true)); contributingFactors.Append(r.ForwardCookie.ToString()); contributingFactors.Append(r.Mode.GetHashCode().ToString()); contributingFactors.Append(r.Minifier.GetHashCode().ToString()); }); var hash = contributingFactors.ToString().GetHash(); if (Log.IsDebugEnabled) Log.Debug("New hash: " + hash); return hash; }
/// <inheritdoc cref="IVersionGenerator.Generate" /> public string Generate(ResourceSet rs) { if (Log.IsDebugEnabled) Log.Debug("Computing hash for set " + rs.Name + ". Current hash: " + rs.Hash); var contributingFactors = new List<object> {rs.DebugEnabled}; rs.Filters.ToList().ForEach(contributingFactors.Add); rs.CacheVaryProviders.ToList().ForEach(contributingFactors.Add); rs.Resources.ToList().ForEach(r => { contributingFactors.Add(r.ReadFromCache(true)); contributingFactors.Add(r.ForwardCookie); contributingFactors.Add(r.Mode); contributingFactors.Add(r.Minifier); }); var hash = contributingFactors.Select(f => f.GetHashCode()) .Aggregate(17, (accum, element) => 31 * accum + element) .ToString(); if (Log.IsDebugEnabled) Log.Debug("New hash: " + hash); return hash; }
/// <inheritdoc cref="ISingleContentFilter.TransformContent" /> public string TransformContent(ResourceSet resourceSet, Resource resource, string content) { // Remove comments because they may mess up the result content = Regex.Replace(content, @"/\*.*?\*/", string.Empty, RegexOptions.Singleline); var regex = new Regex(@"@define\s*{(?<define>.*?)}", RegexOptions.Singleline); var match = regex.Match(content); if (!match.Success) return content; var value = match.Groups["define"].Value; var variables = value.Split(';'); var sb = new StringBuilder(content); variables.ToList().ForEach(variable => { if (string.IsNullOrEmpty(variable.Trim())) return; var pair = variable.Split(':'); sb.Replace("@" + pair[0].Trim(), pair[1].Trim()); }); // Remove the variables declaration, it's not needed in the final output sb.Replace(match.ToString(), string.Empty); return sb.ToString(); }
public void SetComputeResourceSet(uint slot, ResourceSet rs) { NoAllocSetComputeResourceSetEntry entry = new NoAllocSetComputeResourceSetEntry(slot, Track(rs)); AddEntry(SetComputeResourceSetEntryID, ref entry); }
IEnumerable <Tuple <string, string> > WriteResourceFilesInProject(LoadedAssembly assembly, DecompilationOptions options, HashSet <string> directories) { //AppDomain bamlDecompilerAppDomain = null; //try { foreach (EmbeddedResource r in assembly.ModuleDefinition.Resources.OfType <EmbeddedResource>()) { string fileName; Stream s = r.GetResourceStream(); s.Position = 0; if (r.Name.EndsWith(".g.resources", StringComparison.OrdinalIgnoreCase)) { IEnumerable <DictionaryEntry> rs = null; try { rs = new ResourceSet(s).Cast <DictionaryEntry>(); } catch (ArgumentException) { } if (rs != null && rs.All(e => e.Value is Stream)) { foreach (var pair in rs) { fileName = Path.Combine(((string)pair.Key).Split('/').Select(p => cleanupName(p)).ToArray()); string dirName = Path.GetDirectoryName(fileName); if (!string.IsNullOrEmpty(dirName) && directories.Add(dirName)) { CreateDirSafely(Path.Combine(options.SaveAsProjectDirectory, dirName)); } Stream entryStream = (Stream)pair.Value; entryStream.Position = 0; if (fileName.EndsWith(".baml", StringComparison.OrdinalIgnoreCase)) { // MemoryStream ms = new MemoryStream(); // entryStream.CopyTo(ms); // TODO implement extension point // var decompiler = Baml.BamlResourceEntryNode.CreateBamlDecompilerInAppDomain(ref bamlDecompilerAppDomain, assembly.FileName); // string xaml = null; // try { // xaml = decompiler.DecompileBaml(ms, assembly.FileName, new ConnectMethodDecompiler(assembly), new AssemblyResolver(assembly)); // } // catch (XamlXmlWriterException) { } // ignore XAML writer exceptions // if (xaml != null) { // File.WriteAllText(Path.Combine(options.SaveAsProjectDirectory, Path.ChangeExtension(fileName, ".xaml")), xaml); // yield return Tuple.Create("Page", Path.ChangeExtension(fileName, ".xaml")); // continue; // } } using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) { entryStream.CopyTo(fs); } yield return(Tuple.Create("Resource", fileName)); } continue; } } fileName = GetFileNameForResource(r.Name, directories); using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) { s.CopyTo(fs); } yield return(Tuple.Create("EmbeddedResource", fileName)); } //} //finally { // if (bamlDecompilerAppDomain != null) // AppDomain.Unload(bamlDecompilerAppDomain); //} }
public void CreateResources(SceneContext sc) { // textures = model textures 0 - count // vertex buffer = all vertices // index buffer = indices grouped by texture, in texture order // indices per texture - number of indices per texture, in texture order // bone transforms - 128 matrices for the transforms of the current frame var vertices = new List <ModelVertex>(); var indices = new Dictionary <short, List <uint> >(); for (short i = 0; i < _mdl.Textures.Count; i++) { indices[i] = new List <uint>(); } var rectangles = CreateTexuture(sc); var texHeight = rectangles.Max(x => x.Bottom); var texWidth = rectangles.Max(x => x.Right); _bodyPartIndices = new uint[_mdl.BodyParts.Count][]; uint vi = 0; var skin = _mdl.Skins[0].Textures; for (var bpi = 0; bpi < _mdl.BodyParts.Count; bpi++) { var part = _mdl.BodyParts[bpi]; _bodyPartIndices[bpi] = new uint[part.Models.Length]; for (var mi = 0; mi < part.Models.Length; mi++) { var model = part.Models[mi]; _bodyPartIndices[bpi][mi] = (uint)model.Meshes.Sum(x => x.Vertices.Length); foreach (var mesh in model.Meshes) { var texId = skin[mesh.SkinRef]; var rec = rectangles.Count > texId ? rectangles[texId] : Rectangle.Empty; foreach (var x in mesh.Vertices) { vertices.Add(new ModelVertex { Position = x.Vertex, Normal = x.Normal, Texture = (x.Texture + new Vector2(rec.X, rec.Y)) / new Vector2(texWidth, texHeight), Bone = (uint)x.VertexBone }); indices[texId].Add(vi); vi++; } } } } var flatIndices = new uint[vi]; var currentIndexCount = 0; foreach (var kv in indices.OrderBy(x => x.Key)) { var num = kv.Value.Count; Array.Copy(kv.Value.ToArray(), 0, flatIndices, currentIndexCount, num); currentIndexCount += num; } var newVerts = vertices.ToArray(); _vertexBuffer = sc.Device.ResourceFactory.CreateBuffer(new BufferDescription((uint)newVerts.Length * ModelVertex.SizeInBytes, BufferUsage.VertexBuffer)); _indexBuffer = sc.Device.ResourceFactory.CreateBuffer(new BufferDescription((uint)flatIndices.Length * sizeof(uint), BufferUsage.IndexBuffer)); sc.Device.UpdateBuffer(_vertexBuffer, 0, newVerts); sc.Device.UpdateBuffer(_indexBuffer, 0, flatIndices); _transformsBuffer = sc.Device.ResourceFactory.CreateBuffer( new BufferDescription((uint)Unsafe.SizeOf <Matrix4x4>() * 128, BufferUsage.UniformBuffer) ); _transformsResourceSet = sc.ResourceCache.GetResourceSet( new ResourceSetDescription(sc.ResourceCache.ProjectionLayout, _transformsBuffer) ); _projectionBuffer = sc.Device.ResourceFactory.CreateBuffer( new BufferDescription((uint)Unsafe.SizeOf <UniformProjection>(), BufferUsage.UniformBuffer) ); _projectionResourceSet = sc.ResourceCache.GetResourceSet( new ResourceSetDescription(sc.ResourceCache.ProjectionLayout, _projectionBuffer) ); }
protected override void CreateResources(ResourceFactory factory) { _projectionBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _viewBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _worldBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); Matrix4x4 worldMatrix = Matrix4x4.CreateTranslation(0, 15000, -5000) * Matrix4x4.CreateRotationX(3 * (float)Math.PI / 2) * Matrix4x4.CreateScale(0.05f); GraphicsDevice.UpdateBuffer(_worldBuffer, 0, ref worldMatrix); Shader vs = LoadShader(factory, "Animated", ShaderStages.Vertex, "VS"); Shader fs = LoadShader(factory, "Animated", ShaderStages.Fragment, "FS"); ResourceLayout layout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("World", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("Bones", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("SurfaceTex", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment))); Texture texture; using (Stream ktxStream = OpenEmbeddedAssetStream("goblin_bc3_unorm.ktx")) { texture = KtxFile.LoadTexture( GraphicsDevice, factory, ktxStream, PixelFormat.BC3_UNorm); } _texView = ResourceFactory.CreateTextureView(texture); VertexLayoutDescription vertexLayouts = new VertexLayoutDescription( new[] { new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3), new VertexElementDescription("UV", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("BoneWeights", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4), new VertexElementDescription("BoneIndices", VertexElementSemantic.TextureCoordinate, VertexElementFormat.UInt4), }); GraphicsPipelineDescription gpd = new GraphicsPipelineDescription( BlendStateDescription.SingleOverrideBlend, DepthStencilStateDescription.DepthOnlyLessEqual, new RasterizerStateDescription(FaceCullMode.Back, PolygonFillMode.Solid, FrontFace.CounterClockwise, true, false), PrimitiveTopology.TriangleList, new ShaderSetDescription(new[] { vertexLayouts }, new[] { vs, fs }), layout, GraphicsDevice.SwapchainFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref gpd); AssimpContext ac = new AssimpContext(); using (Stream modelStream = OpenEmbeddedAssetStream("goblin.dae")) { _scene = ac.ImportFileFromStream(modelStream, "dae"); } _rootNodeInverseTransform = _scene.RootNode.Transform; _rootNodeInverseTransform.Inverse(); _firstMesh = _scene.Meshes[0]; AnimatedVertex[] vertices = new AnimatedVertex[_firstMesh.VertexCount]; for (int i = 0; i < vertices.Length; i++) { vertices[i].Position = new Vector3(_firstMesh.Vertices[i].X, _firstMesh.Vertices[i].Y, _firstMesh.Vertices[i].Z); vertices[i].UV = new Vector2(_firstMesh.TextureCoordinateChannels[0][i].X, _firstMesh.TextureCoordinateChannels[0][i].Y); } _animation = _scene.Animations[0]; List <int> indices = new List <int>(); foreach (Face face in _firstMesh.Faces) { if (face.IndexCount == 3) { indices.Add(face.Indices[0]); indices.Add(face.Indices[1]); indices.Add(face.Indices[2]); } } for (uint boneID = 0; boneID < _firstMesh.BoneCount; boneID++) { Bone bone = _firstMesh.Bones[(int)boneID]; _boneIDsByName.Add(bone.Name, boneID); foreach (VertexWeight weight in bone.VertexWeights) { vertices[weight.VertexID].AddBone(boneID, weight.Weight); } } Array.Resize(ref _boneTransformations, _firstMesh.BoneCount); _bonesBuffer = ResourceFactory.CreateBuffer(new BufferDescription( 64 * 64, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _rs = factory.CreateResourceSet(new ResourceSetDescription(layout, _projectionBuffer, _viewBuffer, _worldBuffer, _bonesBuffer, _texView, GraphicsDevice.Aniso4xSampler)); _indexCount = (uint)indices.Count; _vertexBuffer = ResourceFactory.CreateBuffer(new BufferDescription( (uint)(vertices.Length * Unsafe.SizeOf <AnimatedVertex>()), BufferUsage.VertexBuffer)); GraphicsDevice.UpdateBuffer(_vertexBuffer, 0, vertices); _indexBuffer = ResourceFactory.CreateBuffer(new BufferDescription( _indexCount * 4, BufferUsage.IndexBuffer)); GraphicsDevice.UpdateBuffer(_indexBuffer, 0, indices.ToArray()); _cl = factory.CreateCommandList(); _camera.Position = new Vector3(110, -87, -532); _camera.Yaw = 0.45f; _camera.Pitch = -0.55f; _camera.MoveSpeed = 1000f; _camera.FarDistance = 100000; }
public void SetResourceSet(uint slot, ResourceSet rs) { _commands.Add(_setResourceSetEntryPool.Rent().Init(slot, rs)); }
public bool TryResolveResourceSet(string name, out ResourceSet resourceSet) { return(_data.Sets.TryGetValue(name, out resourceSet)); }
/// <summary> /// 创建相关资源 /// </summary> /// <param name="gd"></param> /// <param name="factory"></param> public void CreateDeviceResources(GraphicsDevice gd, ResourceFactory factory) { _gd = gd; //计算每个mesh的boundbox _mesh = FeatureTrianglator.FeatureToMesh(this._feature, this._shape); //提取所有点绘制其线 _meshLine = FeatureTrianglator.FeatureToLineStripAdjacency(this._feature, this._shape); ///创建并更新资源 var result = _meshLine.CreateGraphicResource(gd, factory); _lineVertexBuffer = result.Item1; _lineIndicesBuffer = result.Item2; foreach (var item in _mesh) { var typle = item.CreateGraphicResource(gd, factory); var box = BoundingBox.CreateFromPoints(item.Positions); var ttt = box.CreateResource(gd, factory); _vertexBuffer.Add(typle.Item1); _indexBuffer.Add(typle.Item2); } //三角细分,细分精度为1度 //_mesh = TriangleMeshSubdivision.Compute(posClearUp, indices.ToArray(), Math.PI / 180); //创建一个PolygonStyle的Buffer并更新 _polygonstyleBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); gd.UpdateBuffer(_polygonstyleBuffer, 0, VectorStyle.PolygonStyle.ToUBO()); //创建一个LineStyle的Buffer _polylinetyleBuffer = _polygonstyleBuffer = factory.CreateBuffer(new BufferDescription(32, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); gd.UpdateBuffer(_polylinetyleBuffer, 0, VectorStyle.LineStyle.ToUBO()); //创建一个stylelayout ResourceLayout styleLayout = factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("LineStyle", ResourceKind.UniformBuffer, ShaderStages.Fragment | ShaderStages.Geometry), new ResourceLayoutElementDescription("PolygonStyle", ResourceKind.UniformBuffer, ShaderStages.Fragment) )); var curAss = this.GetType().Assembly; ShaderSetDescription shaderSet = new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3)) }, new[] { ResourceHelper.LoadEmbbedShader(ShaderStages.Vertex, "PolygonVS.spv", gd, curAss), ResourceHelper.LoadEmbbedShader(ShaderStages.Fragment, "PolygonFS.spv", gd, curAss) }); ShaderSetDescription shaderSetBoundingBox = new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3)) }, new[] { ResourceHelper.LoadEmbbedShader(ShaderStages.Vertex, "LineVS.spv", gd, curAss), ResourceHelper.LoadEmbbedShader(ShaderStages.Fragment, "LineFS.spv", gd, curAss), ResourceHelper.LoadEmbbedShader(ShaderStages.Geometry, "LineGS.spv", gd, curAss) }); _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription( BlendStateDescription.SingleOverrideBlend, DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, shaderSet, //共享View和prj的buffer new ResourceLayout[] { ShareResource.ProjectionResourceLayout, styleLayout }, gd.MainSwapchain.Framebuffer.OutputDescription)); //创建一个渲染boundingBox的渲染管线 var rasterizer = RasterizerStateDescription.Default; rasterizer.FillMode = PolygonFillMode.Solid; rasterizer.FrontFace = FrontFace.Clockwise; //gpu的lineWidth实际绘制的效果并不好仍然需要GeometryShader来实现更好的效果 //rasterizer.LineWidth = 8.0f; _boundingBoxPipeLine = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription( BlendStateDescription.SingleOverrideBlend, DepthStencilStateDescription.DepthOnlyLessEqual, rasterizer, _meshLine.PrimitiveTopology, shaderSetBoundingBox, //共享View和prj的buffer new ResourceLayout[] { ShareResource.ProjectionResourceLayout, styleLayout }, gd.MainSwapchain.Framebuffer.OutputDescription)); //创建一个StyleresourceSet,0是线样式1是面样式 _styleResourceSet = factory.CreateResourceSet(new ResourceSetDescription( styleLayout, _polylinetyleBuffer, _polygonstyleBuffer )); //创建一个ResourceSet //_cl = factory.CreateCommandList(); }
/// <summary> /// Creates a new resource set /// </summary> /// <param name="targetName">The name of the directory the resources in this resourceset are located</param> /// <param name="fallbackSet">The fallback resourceset that will be used if a given resource was not found in this set</param> public ResourceSet(string targetName, ResourceSet fallbackSet) { Fallback = fallbackSet; TargetName = targetName; }
private static async Task InitServices() { string globalConfigFile = Path.Combine(SharedInfo.ConfigDirectory, SharedInfo.GlobalConfigFileName); GlobalConfig = GlobalConfig.Load(globalConfigFile); if (GlobalConfig == null) { ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorGlobalConfigNotLoaded, globalConfigFile)); await Task.Delay(5 * 1000).ConfigureAwait(false); await Exit(1).ConfigureAwait(false); return; } if (!string.IsNullOrEmpty(GlobalConfig.CurrentCulture)) { try { // GetCultureInfo() would be better but we can't use it for specifying neutral cultures such as "en" CultureInfo culture = CultureInfo.CreateSpecificCulture(GlobalConfig.CurrentCulture); CultureInfo.DefaultThreadCurrentCulture = CultureInfo.DefaultThreadCurrentUICulture = culture; } catch (CultureNotFoundException) { ASF.ArchiLogger.LogGenericError(Strings.ErrorInvalidCurrentCulture); } } int defaultResourceSetCount = 0; int currentResourceSetCount = 0; ResourceSet defaultResourceSet = Strings.ResourceManager.GetResourceSet(CultureInfo.CreateSpecificCulture("en-US"), true, true); if (defaultResourceSet != null) { defaultResourceSetCount = defaultResourceSet.Cast <object>().Count(); } ResourceSet currentResourceSet = Strings.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, false); if (currentResourceSet != null) { currentResourceSetCount = currentResourceSet.Cast <object>().Count(); } if (currentResourceSetCount < defaultResourceSetCount) { float translationCompleteness = currentResourceSetCount / (float)defaultResourceSetCount; ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.TranslationIncomplete, CultureInfo.CurrentCulture.Name, translationCompleteness.ToString("P1"))); } string globalDatabaseFile = Path.Combine(SharedInfo.ConfigDirectory, SharedInfo.GlobalDatabaseFileName); if (!File.Exists(globalDatabaseFile)) { ASF.ArchiLogger.LogGenericInfo(Strings.Welcome); ASF.ArchiLogger.LogGenericWarning(Strings.WarningPrivacyPolicy); await Task.Delay(15 * 1000).ConfigureAwait(false); } GlobalDatabase = GlobalDatabase.Load(globalDatabaseFile); if (GlobalDatabase == null) { ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorDatabaseInvalid, globalDatabaseFile)); await Task.Delay(5 * 1000).ConfigureAwait(false); await Exit(1).ConfigureAwait(false); return; } ArchiWebHandler.Init(); WebBrowser.Init(); WCF.Init(); WebBrowser = new WebBrowser(ASF.ArchiLogger); }
private static async Task InitGlobalConfigAndLanguage() { string globalConfigFile = Path.Combine(SharedInfo.ConfigDirectory, SharedInfo.GlobalConfigFileName); GlobalConfig = await GlobalConfig.Load(globalConfigFile).ConfigureAwait(false); if (GlobalConfig == null) { ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorGlobalConfigNotLoaded, globalConfigFile)); await Task.Delay(5 * 1000).ConfigureAwait(false); await Exit(1).ConfigureAwait(false); return; } if (Debugging.IsUserDebugging) { ASF.ArchiLogger.LogGenericDebug(SharedInfo.GlobalConfigFileName + ": " + JsonConvert.SerializeObject(GlobalConfig, Formatting.Indented)); } if (!string.IsNullOrEmpty(GlobalConfig.CurrentCulture)) { try { // GetCultureInfo() would be better but we can't use it for specifying neutral cultures such as "en" CultureInfo culture = CultureInfo.CreateSpecificCulture(GlobalConfig.CurrentCulture); CultureInfo.DefaultThreadCurrentCulture = CultureInfo.DefaultThreadCurrentUICulture = culture; } catch (Exception) { ASF.ArchiLogger.LogGenericError(Strings.ErrorInvalidCurrentCulture); } } if (CultureInfo.CurrentUICulture.TwoLetterISOLanguageName.Equals("en")) { return; } ResourceSet defaultResourceSet = Strings.ResourceManager.GetResourceSet(CultureInfo.GetCultureInfo("en-US"), true, true); if (defaultResourceSet == null) { ASF.ArchiLogger.LogNullError(nameof(defaultResourceSet)); return; } HashSet <DictionaryEntry> defaultStringObjects = defaultResourceSet.Cast <DictionaryEntry>().ToHashSet(); if (defaultStringObjects.Count == 0) { ASF.ArchiLogger.LogNullError(nameof(defaultStringObjects)); return; } ResourceSet currentResourceSet = Strings.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); if (currentResourceSet == null) { ASF.ArchiLogger.LogNullError(nameof(currentResourceSet)); return; } HashSet <DictionaryEntry> currentStringObjects = currentResourceSet.Cast <DictionaryEntry>().ToHashSet(); if (currentStringObjects.Count >= defaultStringObjects.Count) { // Either we have 100% finished translation, or we're missing it entirely and using en-US HashSet <DictionaryEntry> testStringObjects = currentStringObjects.ToHashSet(); testStringObjects.ExceptWith(defaultStringObjects); // If we got 0 as final result, this is the missing language // Otherwise it's just a small amount of strings that happen to be the same if (testStringObjects.Count == 0) { currentStringObjects = testStringObjects; } } if (currentStringObjects.Count < defaultStringObjects.Count) { float translationCompleteness = currentStringObjects.Count / (float)defaultStringObjects.Count; ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.TranslationIncomplete, CultureInfo.CurrentUICulture.Name, translationCompleteness.ToString("P1"))); } }
/// <summary> /// Returns a base color for actor based on type and stuff /// </summary> public static ResourceSet GetActorResourceSet(RadarObject radarObject) { ResourceSet res = new ResourceSet(); res.Brush = ActorDefaultBrush; try { switch (radarObject.Actor.Type) { case TrinityObjectType.Avoidance: res.Brush = AvoidanceBrush; res.Pen = AvoidanceLightPen; break; case TrinityObjectType.Portal: case TrinityObjectType.Container: case TrinityObjectType.CursedChest: case TrinityObjectType.CursedShrine: case TrinityObjectType.Shrine: case TrinityObjectType.HealthWell: case TrinityObjectType.Interactable: case TrinityObjectType.Barricade: case TrinityObjectType.Destructible: res.Brush = GizmoBrush; res.Pen = GizmoLightPen; break; case TrinityObjectType.ProgressionGlobe: case TrinityObjectType.PowerGlobe: case TrinityObjectType.HealthGlobe: case TrinityObjectType.Gold: case TrinityObjectType.Item: res.Brush = ItemBrush; res.Pen = ItemLightPen; break; case TrinityObjectType.Player: res.Brush = PlayerBrush; res.Pen = PlayerLightPen; break; case TrinityObjectType.Unit: if (radarObject.Actor.IsElite) { res.Brush = EliteBrush; res.Pen = EliteLightPen; } else if (radarObject.Actor.IsHostile) { res.Brush = HostileUnitBrush; res.Pen = HostileUnitLightPen; } else { res.Brush = UnitBrush; } res.Pen = UnitLightPen; break; default: res.Brush = TransparentBrush; res.Pen = TransparentPen; break; } if (radarObject.Actor.IsBlacklisted) { res.Pen = BlacklistedPen; } } catch (Exception ex) { Core.Logger.Log("Exception in RadarUI.GetActorColor(). {0} {1}", ex.Message, ex.InnerException); } return(res); }
public void BasicCompute() { if (!GD.Features.ComputeShader) { return; } ResourceLayout layout = RF.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Params", ResourceKind.UniformBuffer, ShaderStages.Compute), new ResourceLayoutElementDescription("Source", ResourceKind.StructuredBufferReadWrite, ShaderStages.Compute), new ResourceLayoutElementDescription("Destination", ResourceKind.StructuredBufferReadWrite, ShaderStages.Compute))); uint width = 1024; uint height = 1024; DeviceBuffer paramsBuffer = RF.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <BasicComputeTestParams>(), BufferUsage.UniformBuffer)); DeviceBuffer sourceBuffer = RF.CreateBuffer(new BufferDescription(width * height * 4, BufferUsage.StructuredBufferReadWrite, 4)); DeviceBuffer destinationBuffer = RF.CreateBuffer(new BufferDescription(width * height * 4, BufferUsage.StructuredBufferReadWrite, 4)); GD.UpdateBuffer(paramsBuffer, 0, new BasicComputeTestParams { Width = width, Height = height }); float[] sourceData = new float[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int index = y * (int)width + x; sourceData[index] = index; } } GD.UpdateBuffer(sourceBuffer, 0, sourceData); ResourceSet rs = RF.CreateResourceSet(new ResourceSetDescription(layout, paramsBuffer, sourceBuffer, destinationBuffer)); Pipeline pipeline = RF.CreateComputePipeline(new ComputePipelineDescription( TestShaders.LoadCompute(RF, "BasicComputeTest"), layout, 16, 16, 1)); CommandList cl = RF.CreateCommandList(); cl.Begin(); cl.SetPipeline(pipeline); cl.SetComputeResourceSet(0, rs); cl.Dispatch(width / 16, width / 16, 1); cl.End(); GD.SubmitCommands(cl); GD.WaitForIdle(); DeviceBuffer sourceReadback = GetReadback(sourceBuffer); DeviceBuffer destinationReadback = GetReadback(destinationBuffer); MappedResourceView <float> sourceReadView = GD.Map <float>(sourceReadback, MapMode.Read); MappedResourceView <float> destinationReadView = GD.Map <float>(destinationReadback, MapMode.Read); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int index = y * (int)width + x; Assert.Equal(2 * sourceData[index], sourceReadView[index]); Assert.Equal(sourceData[index], destinationReadView[index]); } } GD.Unmap(sourceReadback); GD.Unmap(destinationReadback); }
/// <summary>Helper strongly typed method to create the query for a resource set root.</summary> /// <typeparam name="TElement">The instance type of a single resource in the set.</typeparam> /// <param name="resourceSet">The resource set to get the query root for.</param> /// <returns>Strongly typed query for the resource set root.</returns> private System.Linq.IQueryable GetTypedQueryRootForResourceSet <TElement>(ResourceSet resourceSet) { IQueryable source = DSPLinqQueryProvider.CreateQuery(this.dataSource.GetResourceSetEntities(resourceSet.Name).Cast <TElement>().AsQueryable()); return(WrapWithPagingProvider(source)); }
/// <summary> /// Returns the IQueryable that represents the resource set. /// </summary> /// <param name="resourceSet">resource set representing the entity set.</param> /// <returns> /// An IQueryable that represents the set; null if there is /// no set for the specified name. /// </returns> public IQueryable GetQueryRootForResourceSet(ResourceSet resourceSet) { Log.Trace(resourceSet.Name); return(GetCurrentProvider <IDataServiceQueryProvider>().GetQueryRootForResourceSet(resourceSet)); }
void LoadMetadata() { var n = 0; var list = ( from p in typeof(T).GetProperties() let t = p.PropertyType where typeof(ITable <>).IsSameOrParentOf(t) let tt = t.GetGenericArguments()[0] let tbl = new SqlTable(_mappingSchema, tt) where tbl.Fields.Values.Any(f => f.IsPrimaryKey) let m = _mappingSchema.GetEntityDescriptor(tt) select new { p.Name, ID = n++, Type = tt, Table = tbl, Mapper = m } ).ToList(); var baseTypes = new Dictionary <Type, Type>(); foreach (var item in list) { foreach (var m in item.Mapper.InheritanceMapping) { if (!baseTypes.ContainsKey(m.Type)) { baseTypes.Add(m.Type, item.Type); } } } list.Sort((x, y) => { if (baseTypes.TryGetValue(x.Type, out var baseType)) { if (y.Type == baseType) { return(1); } } if (baseTypes.TryGetValue(y.Type, out baseType)) { if (x.Type == baseType) { return(-1); } } return(x.ID - y.ID); }); foreach (var item in list) { baseTypes.TryGetValue(item.Type, out var baseType); var type = GetTypeInfo(item.Type, baseType, item.Table, item.Mapper); var set = new ResourceSet(item.Name, type.Type); set.SetReadOnly(); Sets.Add(set.Name, set); } foreach (var item in list) { foreach (var m in item.Mapper.InheritanceMapping) { if (!TypeDic.ContainsKey(m.Type)) { GetTypeInfo( m.Type, item.Type, new SqlTable(_mappingSchema, item.Type), _mappingSchema.GetEntityDescriptor(item.Type)); } } } }
private void RenderImDrawData(ImDrawDataPtr draw_data, GraphicsDevice gd, CommandList cl) { uint vertexOffsetInVertices = 0; uint indexOffsetInElements = 0; if (draw_data.CmdListsCount == 0) { return; } uint totalVBSize = (uint)(draw_data.TotalVtxCount * Unsafe.SizeOf <ImDrawVert>()); if (totalVBSize > _vertexBuffer.SizeInBytes) { gd.DisposeWhenIdle(_vertexBuffer); _vertexBuffer = gd.ResourceFactory.CreateBuffer(new BufferDescription((uint)(totalVBSize * 1.5f), BufferUsage.VertexBuffer | BufferUsage.Dynamic)); } uint totalIBSize = (uint)(draw_data.TotalIdxCount * sizeof(ushort)); if (totalIBSize > _indexBuffer.SizeInBytes) { gd.DisposeWhenIdle(_indexBuffer); _indexBuffer = gd.ResourceFactory.CreateBuffer(new BufferDescription((uint)(totalIBSize * 1.5f), BufferUsage.IndexBuffer | BufferUsage.Dynamic)); } for (int i = 0; i < draw_data.CmdListsCount; i++) { ImDrawListPtr cmd_list = draw_data.CmdListsRange[i]; cl.UpdateBuffer( _vertexBuffer, vertexOffsetInVertices * (uint)Unsafe.SizeOf <ImDrawVert>(), cmd_list.VtxBuffer.Data, (uint)(cmd_list.VtxBuffer.Size * Unsafe.SizeOf <ImDrawVert>())); cl.UpdateBuffer( _indexBuffer, indexOffsetInElements * sizeof(ushort), cmd_list.IdxBuffer.Data, (uint)(cmd_list.IdxBuffer.Size * sizeof(ushort))); vertexOffsetInVertices += (uint)cmd_list.VtxBuffer.Size; indexOffsetInElements += (uint)cmd_list.IdxBuffer.Size; } // Setup orthographic projection matrix into our constant buffer ImGuiIOPtr io = ImGui.GetIO(); Matrix4x4 mvp = Matrix4x4.CreateOrthographicOffCenter( draw_data.DisplayPos.X, draw_data.DisplayPos.X + draw_data.DisplaySize.X, draw_data.DisplayPos.Y + draw_data.DisplaySize.Y, draw_data.DisplayPos.Y, 0.0f, 1.0f); cl.SetPipeline(_pipeline); cl.SetViewport(0, new Viewport(draw_data.DisplayPos.X, draw_data.DisplayPos.Y, draw_data.DisplaySize.X, draw_data.DisplaySize.Y, 0, 1)); cl.SetFullViewports(); cl.SetVertexBuffer(0, _vertexBuffer); cl.SetIndexBuffer(_indexBuffer, IndexFormat.UInt16); DeviceBuffer projMatrix = gd.ResourceFactory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); ResourceSet resourceSet = gd.ResourceFactory.CreateResourceSet(new ResourceSetDescription(_layout, projMatrix, gd.PointSampler)); gd.UpdateBuffer(projMatrix, 0, mvp); cl.SetGraphicsResourceSet(0, resourceSet); resourceSet.Dispose(); projMatrix.Dispose(); draw_data.ScaleClipRects(io.DisplayFramebufferScale); // Render command lists int vtx_offset = 0; int idx_offset = 0; for (int n = 0; n < draw_data.CmdListsCount; n++) { ImDrawListPtr cmd_list = draw_data.CmdListsRange[n]; for (int cmd_i = 0; cmd_i < cmd_list.CmdBuffer.Size; cmd_i++) { ImDrawCmdPtr pcmd = cmd_list.CmdBuffer[cmd_i]; if (pcmd.UserCallback != IntPtr.Zero) { throw new NotImplementedException(); } else { if (pcmd.TextureId != IntPtr.Zero) { if (pcmd.TextureId == _fontAtlasID) { cl.SetGraphicsResourceSet(1, _fontTextureResourceSet); } else { cl.SetGraphicsResourceSet(1, GetImageResourceSet(pcmd.TextureId)); } } Vector2 clipOff = draw_data.DisplayPos; Vector2 clipScale = draw_data.FramebufferScale; cl.SetScissorRect( 0, (uint)((pcmd.ClipRect.X - clipOff.X) * clipScale.X), (uint)((pcmd.ClipRect.Y - clipOff.Y) * clipScale.Y), (uint)((pcmd.ClipRect.Z - clipOff.X) * clipScale.X), (uint)((pcmd.ClipRect.W - clipOff.Y) * clipScale.Y)); cl.DrawIndexed(pcmd.ElemCount, 1, (uint)idx_offset, vtx_offset, 0); } idx_offset += (int)pcmd.ElemCount; } vtx_offset += cmd_list.VtxBuffer.Size; } }
/// <summary> /// Returns a base color for actor based on type and stuff /// </summary> public static ResourceSet GetActorResourceSet(RadarObject radarObject) { var res = new ResourceSet(); res.Brush = ActorDefaultBrush; res.Brush = TransparentBrush; res.Pen = TransparentPen; return res; }
public static IDictionaryEnumerator GetResourcesEnumerator(Assembly assembly) { ResourceSet rs = GetResources(assembly); return(rs == null ? null : rs.GetEnumerator()); }
public void ResXFile2ResourceSetTest() { var actual = new ResourceSet(ResourceSet.NeutralCulture); ResXResourceBundleAdapter_Accessor.Resx2ResourceSet(actual, "ResXResourceBundleAdapterTest.Sample.resx", null); Assert.AreEqual(15, actual.Values.Count); Assert.IsTrue(actual.ContainsKey("Ampersands")); Assert.IsTrue(actual.ContainsKey("MaxLengthString")); Assert.IsTrue(actual.ContainsKey("ReadOnlyString")); Assert.IsTrue(actual.ContainsKey("Set1_Placeholder1")); Assert.IsTrue(actual.ContainsKey("Set1_Placeholder2")); Assert.IsTrue(actual.ContainsKey("Set2")); Assert.IsTrue(actual.ContainsKey("Set2_SubString1")); Assert.IsTrue(actual.ContainsKey("Set2_SubString2")); Assert.IsTrue(actual.ContainsKey("String2Multiline")); Assert.IsTrue(actual.ContainsKey(">>FrameworkLocked")); Assert.IsTrue(actual.ContainsKey("Exclude1")); Assert.IsTrue(actual.ContainsKey("StringWithExclusions")); Assert.IsTrue(actual.ContainsKey("ItemWithoutValue")); Assert.AreEqual(4, actual.CountLocked()); Assert.AreEqual(13, actual.CountStringItems(false)); Assert.AreEqual(14, actual.CountStringItems(true)); Assert.AreEqual(52, actual.CountWords()); Assert.IsInstanceOfType(actual["MaxLengthString"], typeof(ResourceStringItem)); var item = (ResourceStringItem)actual["MaxLengthString"]; Assert.AreEqual(10, item.MaxLength); Assert.IsTrue(actual["ReadOnlyString"].Locked); Assert.AreEqual(LockedReason.DeveloperLock, actual["ReadOnlyString"].LockedReason); Assert.IsTrue(actual[">>FrameworkLocked"].Locked); Assert.AreEqual(LockedReason.FrameworkLock, actual[">>FrameworkLocked"].LockedReason); Assert.IsTrue(actual["Exclude1"].Locked); Assert.AreEqual(LockedReason.ResexMetadata, actual["Exclude1"].LockedReason); // exclusions var exclusions = actual.Exclusions; Assert.AreEqual(3, exclusions.Count); Assert.AreEqual(@"\{.*}", exclusions[1].Pattern); Assert.AreEqual(@"{Text}", exclusions[1].Sample); Assert.AreEqual(@"Windows", exclusions[2].Pattern); }
public ResourceAssociationSet GetResourceAssociationSet(ResourceSet resourceSet, ResourceType resourceType, ResourceProperty resourceProperty) { throw new NotImplementedException(); }
public void RenderShadowMap( Scene3D scene, GraphicsDevice graphicsDevice, CommandList commandList, Action<Framebuffer, BoundingFrustum> drawSceneCallback) { // TODO: Use terrain light for terrain self-shadowing? var light = scene.Lighting.CurrentLightingConfiguration.ObjectLightsPS.Light0; // Calculate size of shadow map. var shadowMapSize = scene.Shadows.ShadowMapSize; var numCascades = (uint) scene.Shadows.ShadowMapCascades; if (_shadowData != null && _shadowData.ShadowMap != null && (_shadowData.ShadowMap.Width != shadowMapSize || _shadowData.ShadowMap.Height != shadowMapSize || _shadowData.NearPlaneDistance != scene.Camera.NearPlaneDistance || _shadowData.FarPlaneDistance != scene.Camera.FarPlaneDistance || _shadowData.NumSplits != numCascades)) { RemoveAndDispose(ref _shadowData); RemoveAndDispose(ref _resourceSet); } if (_shadowData == null) { _shadowData = AddDisposable(new ShadowData( numCascades, scene.Camera.NearPlaneDistance, scene.Camera.FarPlaneDistance, shadowMapSize, graphicsDevice)); _resourceSet = AddDisposable(graphicsDevice.ResourceFactory.CreateResourceSet( new ResourceSetDescription( _globalShaderResources.GlobalShadowResourceLayout, _shadowConstantsPSBuffer.Buffer, _shadowData.ShadowMap, _globalShaderResources.ShadowSampler))); } if (scene.Shadows.ShadowsType != ShadowsType.None) { _shadowFrustumCalculator.CalculateShadowData( light, scene.Camera, _shadowData, scene.Shadows); _shadowConstants.Set(numCascades, scene.Shadows, _shadowData); // Render scene geometry to each split of the cascade. for (var splitIndex = 0; splitIndex < _shadowData.NumSplits; splitIndex++) { _lightFrustum.Matrix = _shadowData.ShadowCameraViewProjections[splitIndex]; drawSceneCallback( _shadowData.ShadowMapFramebuffers[splitIndex], _lightFrustum); } } else { _shadowConstants.ShadowsType = ShadowsType.None; } _shadowConstantsPSBuffer.Value = _shadowConstants; _shadowConstantsPSBuffer.Update(commandList); }
// validate user entry and populate the game grid with cards private void startGame() { string entry = numberOfPairsBox.Text.ToString(); // if text is valid, get needed info and start the game. Otherwise, do not start the game. // int.Parse will not fail since && has short circuit evaluation in C#, and isTextAllowed guarantees the entry is numeric if (isTextAllowed(entry) && int.TryParse(entry, out numberOfPairs) && isLegalNumber(numberOfPairs)) { errorMessage.Visibility = Visibility.Collapsed; //numberOfPairs = int.Parse(entry); } else { errorMessage.Visibility = Visibility.Visible; return; } StarterPanel.Visibility = Visibility.Collapsed; GamePanel.Visibility = Visibility.Visible; updateNumberOfMistakes(); ResourceManager myResources = new ResourceManager(typeof(Resources)); ResourceSet resourceSet = myResources.GetResourceSet(CultureInfo.CurrentUICulture, true, true); cardBackImageSource = convertBitmapToBitmapImage(MatchingCardGame.Properties.Resources.red_back); // card back int index = 0; // we will populate this panel list with all of the cards that will be placed, and they will be randomized afterwards var panelList = new List <StackPanel>(); // using a foreach loop to easily access the images in the resourceSet. The specific images used don't matter. foreach (DictionaryEntry cardImage in resourceSet) { // just in case, we don't want the back of a card to be entered as the card's front if (cardImage.Key.ToString() == "red_back") { continue; } // We've reached the end at this point, so break out if (index == numberOfPairs * 2) { break; } var imageSource = convertBitmapToBitmapImage((Bitmap)cardImage.Value); panelList.Add(createCardStackPanel(imageSource, index)); index++; panelList.Add(createCardStackPanel(imageSource, index)); index++; } // randomize the cards that were placed in the panelList and place them in the GameGrid for display. for (int i = 0; i < numberOfPairs * 2; i++) { int randomIndex = random.Next(0, panelList.Count - 1); GameGrid.Children.Add(panelList[randomIndex]); panelList.RemoveAt(randomIndex); } }
public override void Construct() { Border = ""; Font = "font10"; TextColor = new Vector4(0, 0, 0, 1); InteriorMargin = new Margin(16, 16, 16, 16); var titleBar = AddChild(new Widget() { AutoLayout = AutoLayout.DockTop, MinimumSize = new Point(0, 34), }); for (var i = 0; i < Data.RequiredResources.Count; ++i) { var resource = Library.EnumerateResourceTypesWithTag(Data.RequiredResources[i].Tag).FirstOrDefault(); if (resource != null) { titleBar.AddChild(new Widget { MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), Background = resource.GuiLayers[0], AutoLayout = AutoLayout.DockLeft, Text = Data.RequiredResources[i].Count.ToString(), TextHorizontalAlign = HorizontalAlign.Right, TextVerticalAlign = VerticalAlign.Bottom, Font = "font10-outline-numsonly", TextColor = Color.White.ToVector4(), Tooltip = Data.RequiredResources[i].Tag }); } if (i < Data.RequiredResources.Count - 1) { titleBar.AddChild(new Widget { MinimumSize = new Point(16, 32), MaximumSize = new Point(16, 32), AutoLayout = AutoLayout.DockLeft, Text = "+", TextHorizontalAlign = HorizontalAlign.Center, TextVerticalAlign = VerticalAlign.Bottom, Font = "font10" }); } else { titleBar.AddChild(new Widget { MinimumSize = new Point(16, 32), MaximumSize = new Point(16, 32), AutoLayout = AutoLayout.DockLeft, Text = ">>", TextHorizontalAlign = HorizontalAlign.Center, TextVerticalAlign = VerticalAlign.Bottom, Font = "font10" }); } } titleBar.AddChild(new Widget { MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), Background = Data.Icon, AutoLayout = AutoLayout.DockLeft, Text = Data.CraftedResultsCount.ToString(), Font = "font10-outline-numsonly", TextHorizontalAlign = HorizontalAlign.Right, TextVerticalAlign = VerticalAlign.Bottom, TextColor = Color.White.ToVector4() }); titleBar.AddChild(new Widget { Text = " " + Data.Name, Font = "font16", AutoLayout = AutoLayout.DockLeft, TextVerticalAlign = VerticalAlign.Center, MinimumSize = new Point(0, 34), Padding = new Margin(0, 0, 16, 0) }); AddChild(new Widget { Text = Data.Description + "\n", AutoLayout = AutoLayout.DockTop, AutoResizeToTextHeight = true }); foreach (var resourceAmount in Data.RequiredResources) { var child = AddChild(new Widget() { AutoLayout = AutoLayout.DockTop, MinimumSize = new Point(200, 18) }); child.AddChild(new Widget() { Font = "font8", Text = String.Format("{0} {1}: ", resourceAmount.Count, resourceAmount.Tag), AutoLayout = AutoLayout.DockLeft }); child.Layout(); var resourceSelector = child.AddChild(new ComboBox { Font = "font8", Items = new List <string> { "<Not enough!>" }, AutoLayout = AutoLayout.DockLeft, MinimumSize = new Point(200, 18), Tooltip = String.Format("Type of {0} to use.", resourceAmount.Tag) }) as ComboBox; var resourceCountIndicator = child.AddChild(new Widget { Font = "font8", AutoLayout = AutoLayout.DockFill }); ResourceCombos.Add(new ResourceCombo { Resource = resourceAmount, Combo = resourceSelector, Count = resourceCountIndicator }); } var child2 = AddChild(new Widget() { AutoLayout = AutoLayout.DockTop, MinimumSize = new Point(100, 18) }); child2.AddChild(new Widget() { Font = "font8", Text = "Repeat ", AutoLayout = AutoLayout.DockLeft }); NumCombo = child2.AddChild(new ComboBox { Font = "font8", Items = new List <string>() { "1x", "5x", "10x", "100x" }, AutoLayout = AutoLayout.DockLeft, MinimumSize = new Point(64, 18), MaximumSize = new Point(64, 18), Tooltip = "Craft this many objects." }) as ComboBox; NumCombo.SelectedIndex = 0; BottomBar = AddChild(new Widget() { AutoLayout = AutoLayout.DockTop, MinimumSize = new Point(256, 32), TextColor = new Vector4(1, 0, 0, 1) }); Button = BottomBar.AddChild(new Button() { Text = Library.GetString("craft-new", Data.Verb.Base), Tooltip = Library.GetString("craft-new-tooltip", Data.Verb.PresentTense, Data.DisplayName), OnClick = (widget, args) => { if (Button.Hidden) { return; } BuildAction(this, args); }, AutoLayout = AutoLayout.DockLeftCentered, MinimumSize = new Point(64, 28), }); OnUpdate += (sender, time) => { if (Hidden) { return; } var notEnoughResources = false; var availableResources = World.ListApparentResources(); foreach (var combo in ResourceCombos) { var currentSelection = combo.Combo.SelectedItem; // Todo: Aggregate by display name instead. And then - ?? combo.Combo.Items = ResourceSet.GroupByApparentType( World.GetResourcesWithTag(combo.Resource.Tag)).Where(r => r.Count >= combo.Resource.Count).Select(r => r.ApparentType).OrderBy(p => p).ToList(); if (combo.Combo.Items.Count == 0) { combo.Combo.Items.Add("<Not enough!>"); notEnoughResources = true; } if (combo.Combo.Items.Contains(currentSelection)) { combo.Combo.SelectedIndex = combo.Combo.Items.IndexOf(currentSelection); } else { combo.Combo.SelectedIndex = 0; } if (combo.Combo.SelectedItem == "<Not enough!>") { combo.Count.Text = ""; } else { if (availableResources.ContainsKey(combo.Combo.SelectedItem)) { combo.Count.Text = String.Format("Available: {0}", availableResources[combo.Combo.SelectedItem].Count); } else { combo.Count.Text = "Available: None!"; } } combo.Combo.Invalidate(); combo.Count.Invalidate(); } Button.Hidden = true; if (notEnoughResources) { BottomBar.Text = "You don't have enough resources."; } else { if (!World.PlayerFaction.Minions.Any(m => m.Stats.IsTaskAllowed(Data.CraftTaskCategory))) { BottomBar.Text = String.Format("You need a minion capable of {0} tasks to {1} this.", Data.CraftTaskCategory, Data.Verb); } else { var nearestBuildLocation = World.PlayerFaction.FindNearestItemWithTags(Data.CraftLocation, Vector3.Zero, false, null); if (!String.IsNullOrEmpty(Data.CraftLocation) && nearestBuildLocation == null) { BottomBar.Text = String.Format("Needs {0} to {1}!", Data.CraftLocation, Data.Verb); } else { Button.Hidden = false; BottomBar.Text = ""; } } } }; Root.RegisterForUpdate(this); Layout(); }
/// <inheritdoc cref="IResourceMinifier.Minify" /> public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent) { return combinedContent; }
public DocumentView(int _CURENT_USER_ID, int _ID_DOSAR, string conStr) { this.ID_DOSAR = _ID_DOSAR; TipDocumenteRepository tdr = new TipDocumenteRepository(_CURENT_USER_ID, conStr); //this.TipuriDocumente = (TipDocument[])tdr.GetAll().Result; TipDocument[] tipuriDocumente = (TipDocument[])tdr.GetAll().Result; DosareRepository dr = new DosareRepository(_CURENT_USER_ID, conStr); Dosar d = (Dosar)dr.Find(_ID_DOSAR).Result; //this.DocumenteScanate = (DocumentScanat[])d.GetDocumente().Result; DocumentScanat[] dss = (DocumentScanat[])d.GetDocumente().Result; /* * List<TipDocumentJson> l = new List<TipDocumentJson>(); * foreach (TipDocument td in tipuriDocumente) * { * List<DocumentScanat> ld = new List<DocumentScanat>(); * foreach(DocumentScanat ds in dss) * { * if(ds.ID_TIP_DOCUMENT == td.ID) * { * ld.Add(ds); * } * } * l.Add(new TipDocumentJson(td, ld.ToArray())); * } * this.TipuriDocumente = l.ToArray(); * //this.CurDocumentScanat = new DocumentScanat(); */ this.TipuriDocumente = new TipDocumentJson[tipuriDocumente.Length]; for (int i = 0; i < tipuriDocumente.Length; i++) { List <DocumentScanat> ld = new List <DocumentScanat>(); for (int j = 0; j < dss.Length; j++) { if (dss[j].ID_TIP_DOCUMENT == tipuriDocumente[i].ID) { ld.Add(dss[j]); } } this.TipuriDocumente[i] = new TipDocumentJson(tipuriDocumente[i], ld.ToArray()); } ResourceSet resourceSet = socisaV2.Resources.TipDocumenteResx.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); List <KeyValuePair <string, string> > t = new List <KeyValuePair <string, string> >(); foreach (DictionaryEntry entry in resourceSet) { t.Add(new KeyValuePair <string, string>(entry.Key.ToString(), entry.Value.ToString())); } this.TranslatedTipDocumenteNames = new string[t.Count][]; for (int i = 0; i < t.Count; i++) { this.TranslatedTipDocumenteNames[i] = new string[2]; this.TranslatedTipDocumenteNames[i][0] = t[i].Key; this.TranslatedTipDocumenteNames[i][1] = t[i].Value; } }
public void CreateDeviceResources(GraphicsDevice gd) { var factory = new DisposeCollectorResourceFactory(gd.ResourceFactory, disposeCollector); vertexBuffer = model.CreateVertexBuffer(gd); indexBuffer = model.CreateIndexBuffer(gd, out indexCount); transformationBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); projectionBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); viewBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); texture = textureData.CreateDeviceTexture(gd, factory); lightDirectionBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); lightColorBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); shineDamperBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); reflectivityBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); var vertexLayoutDesc = new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementFormat.Float3, VertexElementSemantic.TextureCoordinate), new VertexElementDescription("TexCoord", VertexElementFormat.Float2, VertexElementSemantic.TextureCoordinate), new VertexElementDescription("Normal", VertexElementFormat.Float3, VertexElementSemantic.TextureCoordinate) ) }; var transformationResourceLayout = factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription[] { new ResourceLayoutElementDescription("TransformationBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("ProjectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("ViewBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex) } )); var textureResourceLayout = factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription[] { new ResourceLayoutElementDescription("Texture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("LightDirectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("LightColorBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("ShineDamperBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("ReflectivityBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment) } )); transformationResourceSet = factory.CreateResourceSet( new ResourceSetDescription( transformationResourceLayout, transformationBuffer, projectionBuffer, viewBuffer)); textureResourceSet = factory.CreateResourceSet( new ResourceSetDescription( textureResourceLayout, texture, gd.Aniso4xSampler, lightDirectionBuffer, lightColorBuffer, shineDamperBuffer, reflectivityBuffer)); var pipelineDesc = new GraphicsPipelineDescription { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual ), RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.CounterClockwise, depthClipEnabled: true, scissorTestEnabled: false), PrimitiveTopology = PrimitiveTopology.TriangleList, ResourceLayouts = new ResourceLayout[] { transformationResourceLayout, textureResourceLayout }, ShaderSet = new ShaderSetDescription( vertexLayouts: vertexLayoutDesc, shaders: new[] { vertexShader, fragmentShader }), Outputs = gd.SwapchainFramebuffer.OutputDescription }; pipeline = factory.CreateGraphicsPipeline(pipelineDesc); }
private static DataServiceProviderWrapper CreateProvider(out DataServiceConfiguration config, out DataServiceOperationContext operationContext) { var baseUri = new Uri("http://localhost"); var host = new DataServiceHostSimulator() { AbsoluteServiceUri = baseUri, AbsoluteRequestUri = new Uri(baseUri.AbsoluteUri + "/$metadata", UriKind.Absolute), RequestHttpMethod = "GET", RequestAccept = "application/xml+atom", RequestVersion = "4.0", RequestMaxVersion = "4.0", }; operationContext = new DataServiceOperationContext(host); var dataService = new DataServiceSimulator() { OperationContext = operationContext }; operationContext.InitializeAndCacheHeaders(dataService); DataServiceProviderSimulator providerSimulator = new DataServiceProviderSimulator(); providerSimulator.ContainerNamespace = "MyModel"; providerSimulator.ContainerName = "CustomersContainer"; ResourceType customerEntityType = new ResourceType( typeof(object), ResourceTypeKind.EntityType, null, "MyModel", "Customer", false) { CanReflectOnInstanceType = false }; ResourcePropertyKind idPropertyKind = ResourcePropertyKind.Primitive | ResourcePropertyKind.Key; ResourceProperty idProperty = new ResourceProperty( "Id", idPropertyKind, ResourceType.GetPrimitiveResourceType(typeof(int))) { CanReflectOnInstanceTypeProperty = false }; customerEntityType.AddProperty(idProperty); ResourcePropertyKind firstNamePropertyKind = ResourcePropertyKind.Primitive | ResourcePropertyKind.Key; ResourceProperty firstNameProperty = new ResourceProperty( "FirstName", firstNamePropertyKind, ResourceType.GetPrimitiveResourceType(typeof(string))) { CanReflectOnInstanceTypeProperty = false }; customerEntityType.AddProperty(firstNameProperty); customerEntityType.SetReadOnly(); providerSimulator.AddResourceType(customerEntityType); ResourceSet customerSet = new ResourceSet("Customers", customerEntityType); customerSet.SetReadOnly(); providerSimulator.AddResourceSet(customerSet); config = new DataServiceConfiguration(providerSimulator); config.SetEntitySetAccessRule("*", EntitySetRights.All); config.DataServiceBehavior.MaxProtocolVersion = ODataProtocolVersion.V4; IDataServiceProviderBehavior providerBehavior = DataServiceProviderBehavior.CustomDataServiceProviderBehavior; DataServiceStaticConfiguration staticConfig = new DataServiceStaticConfiguration(dataService.Instance.GetType(), providerSimulator); DataServiceProviderWrapper provider = new DataServiceProviderWrapper( new DataServiceCacheItem(config, staticConfig), providerSimulator, providerSimulator, dataService, false); dataService.ProcessingPipeline = new DataServiceProcessingPipeline(); dataService.Provider = provider; provider.ProviderBehavior = providerBehavior; dataService.ActionProvider = DataServiceActionProviderWrapper.Create(dataService); #if DEBUG dataService.ProcessingPipeline.SkipDebugAssert = true; #endif operationContext.RequestMessage.InitializeRequestVersionHeaders(VersionUtil.ToVersion(config.DataServiceBehavior.MaxProtocolVersion)); return(provider); }
public string TransformContent(ResourceSet resourceSet, Resource resource, string content) { var engine = new LessEngine(new Parser(new ConsoleStylizer(), new Importer(new AdeptFileReader(resource.Path)))); return engine.TransformToCss(content, resource.Path); }
public TechTreeTitles(ResourceSet parent) : base("TreeTitles", parent) { }
/// <inheritdoc cref="ISingleContentFilter.TransformContent" /> public string TransformContent(ResourceSet resourceSet, Resource resource, string content) { return EngineFactory.GetEngine().TransformToCss(content, null); }
public ResourceSetInfo(IntPtr imGuiBinding, ResourceSet resourceSet) { ImGuiBinding = imGuiBinding; ResourceSet = resourceSet; }
private static string GetResourceSetUrl(ResourceSet set) { Predicate<ICacheVaryProvider> predicate = p => p.AppendKeyToUrl; var cacheVaryKeys = string.Join("/", set.GetCacheVaryStates(HttpContext.Current, predicate) .Select(s => s.Key).ToArray()); var fullUrl = string.Format(CultureInfo.InvariantCulture, UrlPattern, set.Settings.Url, set.Name, set.GetVersionString() ) + cacheVaryKeys; return fullUrl.ResolveUrl().AppendHost(set.Settings); }
/// <summary>Adds a resource set reference property to the specified <paramref name="resourceType"/>.</summary> /// <param name="resourceType">The resource type to add the property to.</param> /// <param name="name">The name of the property to add.</param> /// <param name="targetResourceSet">The resource set the resource set reference property points to.</param> /// <param name="targetResourceType">The resource type the resource set reference property points to. /// Can be null in which case the base resource type of the resource set is used.</param> /// <remarks>This creates a property pointing to multiple resources in the target resource set.</remarks> public void AddResourceSetReferenceProperty(ResourceType resourceType, string name, ResourceSet targetResourceSet, ResourceType targetResourceType) { AddReferenceProperty(resourceType, name, targetResourceSet, targetResourceType, true); }
private void LoadResourceSets(XContainer xe) { var rsXe = xe.Element(XName.Get(SchemaConstants.Setting.ResourceSets, SchemaConstants.Namespace)); Url = rsXe.Attr<string>(SchemaConstants.Setting.Url); DefaultDuration = rsXe.Attr<int?>(SchemaConstants.Setting.DefaultDuration); DefaultVersion = rsXe.Attr<string>(SchemaConstants.Setting.DefaultVersion); var generatorType = rsXe.Attr<string>(SchemaConstants.Setting.DefaultVersionGenerator); DefaultVersionGeneratorType = string.IsNullOrEmpty(generatorType) ? Default.ResourceSet.VersionGeneratorType : ModelUtils.LoadType("Generator", generatorType, SchemaConstants.VersionGenerator.ValidTypes); LocalChangeMonitorInterval = rsXe.Attr<int?>(SchemaConstants.Setting.LocalChangeMonitorInterval); RemoteChangeMonitorInterval = rsXe.Attr<int?>(SchemaConstants.Setting.RemoteChangeMonitorInterval); var debugEnabled = rsXe.Attr<string>(SchemaConstants.Setting.DefaultDebugEnabled); DefaultDebugEnabled = string.IsNullOrEmpty(debugEnabled) ? Default.ResourceSet.DebugEnabled : debugEnabled.Equals(SchemaConstants.Set.Auto, StringComparison.OrdinalIgnoreCase) ? HttpContext.Current.IsDebuggingEnabled : bool.Parse(debugEnabled); DefaultIgnorePipelineWhenDebug = (bool)rsXe.Attr<string>(SchemaConstants.Setting.DefaultIgnorePipelineWhenDebug) .ConvertToType(typeof(bool), Default.ResourceSet.IgnorePipelineWhenDebug); DefaultCompressionEnabled = (bool)rsXe.Attr<string>(SchemaConstants.Setting.DefaultCompressionEnabled) .ConvertToType(typeof(bool), Default.ResourceSet.CompressionEnabled); DefaultJSMinifierRef = GetMinifier(rsXe, SchemaConstants.Setting.DefaultJSMinifierRef, JSMinifierMap); DefaultCssMinifierRef = GetMinifier(rsXe, SchemaConstants.Setting.DefaultCssMinifierRef, CssMinifierMap); ResourceSets = new List<ResourceSet>(); foreach (var node in rsXe.Elements()) { var rs = new ResourceSet(this, node); if (ResourceSets.Contains(rs)) throw new XmlSchemaException("Duplicated resource set"); ResourceSets.Add(rs); } ResourceSets = ResourceSets.ToList().AsReadOnly(); }
public string CreateClassFromResourceSet(ResourceSet resourceSet, string nameSpace, string classname, string fileName) { IsVb = IsFileVb(fileName); StringBuilder sbClass = new StringBuilder(); CreateClassHeader(classname, nameSpace, IsVb, sbClass); string indent = "\t\t"; // Any resource set that contains a '.' is considered a Local Resource bool IsGlobalResource = !classname.Contains("."); // We'll enumerate through the Recordset to get all the resources IDictionaryEnumerator Enumerator = resourceSet.GetEnumerator(); // We have to turn into a concrete Dictionary while (Enumerator.MoveNext()) { DictionaryEntry item = (DictionaryEntry)Enumerator.Current; if (item.Value == null) { item.Value = string.Empty; } string typeName = item.Value.GetType().FullName; string key = item.Key as string; if (string.IsNullOrEmpty(key)) { continue; } string varName = SafeVarName(key); // It's a string if (!IsVb) { sbClass.Append(indent + "public static " + typeName + " " + varName + "\r\n" + indent + "{\r\n"); sbClass.AppendFormat(indent + "\tget\r\n" + indent + "\t{{\r\n" + indent + (string.IsNullOrEmpty(typeName) || typeName == "System.String" ? "\t\t" + @"return GeneratedResourceHelper.GetResourceString(""{0}"",""{1}"",ResourceManager,GeneratedResourceSettings.ResourceAccessMode);" + "\r\n" : "\t\t" + @"return ({2}) GeneratedResourceHelper.GetResourceObject(""{0}"",""{1}"",ResourceManager,GeneratedResourceSettings.ResourceAccessMode);" + "\r\n") + indent + "\t}}\r\n", classname, key, typeName); sbClass.Append(indent + "}\r\n\r\n"); } else { sbClass.Append(indent + "Public Shared Property " + varName + "() as " + typeName + "\r\n"); sbClass.AppendFormat(indent + "\tGet\r\n" + indent + "\t\treturn CType( HttpContext.GetGlobalResourceObject(\"{0}\",\"{1}\"), {2})\r\n", classname, key, typeName); sbClass.Append(indent + "\tEnd Get\r\n"); sbClass.Append(indent + "End Property\r\n\r\n"); } } if (!IsVb) { sbClass.Append("\t}\r\n\r\n"); } else { sbClass.Append("End Class\r\n\r\n"); } string Output = CreateNameSpaceWrapper(nameSpace, IsVb, sbClass.ToString()); if (!string.IsNullOrEmpty(fileName)) { File.WriteAllText(fileName, Output); return(Output); } return(sbClass.ToString()); }
public ODataServiceMetadataProvider GetMetadataProvider(Type dataSourceType) { ODataServiceMetadataProvider metadata = new ODataServiceMetadataProvider(); ResourceType customer = new ResourceType( typeof(Customer), ResourceTypeKind.EntityType, null, "MyNamespace", "Customer", false ); ResourceProperty customerCustomerID = new ResourceProperty( "CustomerID", ResourcePropertyKind.Key | ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid)) ); customer.AddProperty(customerCustomerID); ResourceProperty customerCustomerName = new ResourceProperty( "CustomerName", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(string)) ); customer.AddProperty(customerCustomerName); ResourceType residentialCustomer = new ResourceType( typeof(ResidentialCustomer), ResourceTypeKind.EntityType, customer, "MyNamespace", "ResidentialCustomer", false ); ResourceType user = new ResourceType( typeof(User), ResourceTypeKind.EntityType, null, "MyNamespace", "User", false ); ResourceProperty userUserID = new ResourceProperty( "UserID", ResourcePropertyKind.Key | ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid)) ); user.AddProperty(userUserID); ResourceProperty userCustomerID = new ResourceProperty( "CustomerID", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid)) ); user.AddProperty(userCustomerID); ResourceProperty userEmailAddress = new ResourceProperty( "EmailAddress", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(string)) ); user.AddProperty(userEmailAddress); var customerSet = new ResourceSet("Customers", customer); var residentialCustomerSet = new ResourceSet("ResidentialCustomers", residentialCustomer); var userSet = new ResourceSet("Users", user); var userCustomer = new ResourceProperty( "Customer", ResourcePropertyKind.ResourceReference, customer ); user.AddProperty(userCustomer); var customerUserList = new ResourceProperty( "UserList", ResourcePropertyKind.ResourceSetReference, user ); customer.AddProperty(customerUserList); metadata.AddResourceType(customer); metadata.AddResourceSet(customerSet); metadata.AddResourceType(residentialCustomer); metadata.AddResourceSet(residentialCustomerSet); metadata.AddResourceType(user); metadata.AddResourceSet(userSet); ResourceAssociationSet customerUserListSet = new ResourceAssociationSet( "CustomerUserList", new ResourceAssociationSetEnd( customerSet, customer, customerUserList ), new ResourceAssociationSetEnd( userSet, user, userCustomer ) ); customerUserList.CustomState = customerUserListSet; userCustomer.CustomState = customerUserListSet; metadata.AddAssociationSet(customerUserListSet); return(metadata); }
private static E <string> LoadLanguageAssembly(LanguageData languageDataInfo, CultureInfo culture, bool forceDownload) { var avaliableToDownload = new Lazy <HashSet <string> >(() => { var arr = DownloadAvaliableLanguages(); return(arr != null ? new HashSet <string>(arr) : null); }); var triedDownloading = languageDataInfo.TriedDownloading; foreach (var currentResolveCulture in GetWithFallbackCultures(culture)) { // Try loading the resource set from memory if (strings.ResourceManager.GetResourceSet(currentResolveCulture, true, false) != null) { return(R.Ok); } // Do not attempt to download or load integrated languages if (languageDataInfo.IsIntenal) { continue; } var tryFile = GetCultureFileInfo(currentResolveCulture); // Check if we need to download the resource if (forceDownload || (!tryFile.Exists && !triedDownloading)) { var list = avaliableToDownload.Value; if (list is null || !list.Contains(currentResolveCulture.Name)) { if (list != null) { Log.Info("Language \"{0}\" is not available on the server", currentResolveCulture.Name); } continue; } try { languageDataInfo.TriedDownloading = true; Directory.CreateDirectory(tryFile.DirectoryName); Log.Info("Downloading the resource pack for the language '{0}'", currentResolveCulture.Name); WebWrapper.GetResponse(new Uri($"https://splamy.de/api/language/project/ts3ab/language/{currentResolveCulture.Name}/dll"), response => { using (var dataStream = response.GetResponseStream()) using (var fs = File.Open(tryFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None)) { dataStream.CopyTo(fs); } }).UnwrapToLog(Log); } catch (Exception ex) { Log.Warn(ex, "Failed trying to download language '{0}'", currentResolveCulture.Name); } } // Try loading the resource set from file try { var asm = Assembly.LoadFrom(tryFile.FullName); var resStream = asm.GetManifestResourceStream($"TS3AudioBot.Localization.strings.{currentResolveCulture.Name}.resources"); var rr = new ResourceReader(resStream); var set = new ResourceSet(rr); dynResMan.SetResourceSet(currentResolveCulture, set); if (strings.ResourceManager.GetResourceSet(currentResolveCulture, true, false) != null) { return(R.Ok); } Log.Error("The resource set was not found after initialization"); } catch (Exception ex) { Log.Warn(ex, "Failed to load language file '{0}'", tryFile.FullName); } } return("Could not find language file"); }