public Shader(CompiledShader vertex, CompiledShader fragment, VertexShader vshader, PixelShader pshader) { XnaCompiledVertexShader = vertex; XnaCompiledPixelShader = fragment; XnaVertexShader = vshader; XnaPixelShader = pshader; }
private void ParseVCS(string path, Stream stream) { lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("--- Loading shader file \"{0}\" ---", path); Console.ResetColor(); } var shader = new CompiledShader(); try { shader.Read(path, stream); } catch (Exception e) { lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(e); Console.ResetColor(); } } shader.Dispose(); }
private void RenderGeometry(Camera camera) { FrameBuffer.Current = this.frameBufferGeometry; this.Matrices.View = camera.ViewMatrix; this.Matrices.Projection = camera.ProjectionMatrix; GL.Disable(EnableCap.Blend); GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode.Back); GL.DepthFunc(DepthFunction.Less); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.ClearDepth(1.0f); GL.Clear(ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit); foreach (var job in this.SolidRenderJobs) { this.Matrices.World = job.Transform; var shader = job.Material.Shader ?? this.DefaultShader; CompiledShader cs = shader.Select("DeferredRenderer", this.geometryPixelShader); cs.Bind(); cs.BindUniforms(Game.Current.Time, job.Material, this.Matrices, this); job.Model.Draw((mesh) => cs.BindUniform(mesh), cs.HasTesselation); } FrameBuffer.Current = null; }
static void FixupShader(ref CompiledShader shader, ShaderType fixup) { if (!shader.Type.IsValid()) { shader = new(null, 0, fixup); } }
public void CompileFromFiles(Canvas canvas, string psName, string vsName) { this.psFileName = psName; this.vsFileName = vsName; ShaderProfile psProf = ShaderProfile.PS_1_1; switch (PSTarget) { case 2: psProf = ShaderProfile.PS_2_0; break; case 3: psProf = ShaderProfile.PS_3_0; break; } ShaderProfile vsProf = ShaderProfile.VS_1_1; switch (VSTarget) { case 2: vsProf = ShaderProfile.VS_2_0; break; case 3: vsProf = ShaderProfile.VS_3_0; break; } CompiledShader psShader = ShaderCompiler.CompileFromFile(psFileName, null, null, CompilerOptions.PackMatrixRowMajor, "main", psProf, TargetPlatform.Windows); Log.GetInstance().WriteLine(psShader.ErrorsAndWarnings); CompiledShader vsShader = ShaderCompiler.CompileFromFile(vsFileName, null, null, CompilerOptions.PackMatrixRowMajor, "main", vsProf, TargetPlatform.Windows); Log.GetInstance().WriteLine(vsShader.ErrorsAndWarnings); errorMessage = null; if (vsShader.ErrorsAndWarnings.Length > 1) { errorMessage = "Vertex Shader: " + vsShader.ErrorsAndWarnings; } if (psShader.ErrorsAndWarnings.Length > 1) { if (errorMessage == null) { errorMessage = "Pixel Shader: " + psShader.ErrorsAndWarnings; } else { errorMessage = errorMessage + "\n Pixel Shader: " + psShader.ErrorsAndWarnings; } } if (psShader.Success && vsShader.Success) { ps = new PixelShader(canvas.GetDevice(), psShader.GetShaderCode()); vs = new VertexShader(canvas.GetDevice(), vsShader.GetShaderCode()); compiled = true; } }
public void Test() { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Shaders"); var files = Directory.GetFiles(path, "*.vcs"); foreach (var file in files) { var shader = new CompiledShader(); shader.Read(file); } }
public void Initialize(GraphicsDevice device) { FileStream fileStream = new FileStream("Data\\Envs\\TestLevel.senv", FileMode.Open); Load(fileStream); CompiledShader compiledShader = ShaderCompiler.CompileFromFile("Data\\Shaders\\Simple.vsh", null, null, CompilerOptions.None, "VertexShaderMain", ShaderProfile.VS_3_0, TargetPlatform.Windows); this.vertexShader = new VertexShader(device, compiledShader.GetShaderCode()); compiledShader = ShaderCompiler.CompileFromFile("Data\\Shaders\\Simple.psh", null, null, CompilerOptions.None, "PixelShaderMain", ShaderProfile.PS_3_0, TargetPlatform.Windows); this.pixelShader = new PixelShader(device, compiledShader.GetShaderCode()); this.texture = (Texture2D)ResourceMgr.Instance.GetResource <Texture>("UV1024"); }
/// <summary> /// Creates a new <see cref="RootSignature"/> from a <see cref="CompiledShader"/> /// </summary> /// <param name="device">The <see cref="ComputeDevice"/> used to create the root signature</param> /// <param name="rootSignatureShader"></param> /// <param name="deserialize"></param> /// <returns>A new <see cref="RootSignature"/></returns> internal static RootSignature Create(ComputeDevice device, CompiledShader rootSignatureShader, bool deserialize = false) { fixed(byte *pSignature = rootSignatureShader) { using UniqueComPtr <ID3D12RootSignature> rootSig = device.CreateRootSignature( 0 /* TODO: MULTI-GPU */, pSignature, (uint)rootSignatureShader.Length ); if (deserialize) { RootSignatureDeserializer.DeserializeSignature(device, pSignature, (int)rootSignatureShader.Length); } return(new RootSignature(rootSig.Move(), null, null)); } }
public Cheetah.Shader CreateShader(string vertex, string fragment) { if (vertex == null) { throw new XnaException("no vertexshader"); } if (fragment == null) { throw new XnaException("no fragmentshader"); } CompiledShader v = ShaderCompiler.CompileFromSource(vertex, new CompilerMacro[] { }, new Include(), CompilerOptions.None, "main", ShaderProfile.VS_2_0, false); CompiledShader p = ShaderCompiler.CompileFromSource(fragment, new CompilerMacro[] { }, new Include(), CompilerOptions.None, "main", ShaderProfile.PS_2_0, false); return(new Shader( v, p, new VertexShader(Device, v.GetShaderCode()), new PixelShader(Device, p.GetShaderCode()) )); }
public void ParseShaders() { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Shaders"); var files = Directory.GetFiles(path, "*.vcs"); foreach (var file in files) { var shader = new CompiledShader(); using var sw = new StringWriter(CultureInfo.InvariantCulture); var originalOutput = Console.Out; Console.SetOut(sw); shader.Read(file); Console.SetOut(originalOutput); } }
public override TOutput Process(TInput input, ContentProcessorContext context) { #if !XNA4 // Populate preprocessor defines string stringBuffer = string.Empty; List <CompilerMacro> defines = new List <CompilerMacro>(); if (preprocessorDefines != string.Empty) { stringBuffer = preprocessorDefines; // Split preprocessor defines and build up macro array if (stringBuffer.Contains(",")) { string[] definesArr = stringBuffer.Split(','); foreach (string def in definesArr) { CompilerMacro macro = new CompilerMacro(); macro.Definition = "1\0"; macro.Name = def + "\0"; defines.Add(macro); } } } CompiledShader shader = ShaderCompiler.CompileFromSource(input, defines.ToArray(), includeHandler, CompilerOptions.PackMatrixRowMajor, entryPoint, shaderProfile, context.TargetPlatform); if (!shader.Success) { throw new InvalidContentException(shader.ErrorsAndWarnings); } HlslCompiledShader compiledShader = new HlslCompiledShader(entryPoint, shader.GetShaderCode()); #else throw new NotImplementedException(); //var shader = new EffectProcessor().Process(new EffectContent { EffectCode = input }, context); HlslCompiledShader compiledShader = new HlslCompiledShader(entryPoint, /**/ null /*/shader.GetEffectCode()/**/); #endif HlslCompiledShaders compiledShaders = new HlslCompiledShaders(); compiledShaders.Add(compiledShader); return(compiledShaders); }
private void RenderOpaque(Camera camera) { this.Matrices.View = camera.ViewMatrix; this.Matrices.Projection = camera.ProjectionMatrix; FrameBuffer.Current = this.frameBufferScene; // No depth, we use the depth from the previous pass. GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); // Don't write z, just compare GL.DepthMask(false); this.Sky.Draw(this, camera); GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.CullFace); GL.Disable(EnableCap.Blend); GL.CullFace(CullFaceMode.Back); GL.DepthFunc(DepthFunction.Lequal); //this.OpaqueCount = 0; foreach (var job in this.SolidRenderJobs) { this.Matrices.World = job.Transform; var shader = job.Material.Shader ?? this.DefaultShader; CompiledShader cs = shader.Select("DeferredRenderer"); cs.Bind(); cs.BindUniforms(Game.Current.Time, job.Material, this.Matrices, this); job.Model.Draw((mesh) => cs.BindUniform(mesh), cs.HasTesselation); //this.OpaqueCount += 1; } GL.DepthMask(true); FrameBuffer.Current = null; }
private static CompiledShader CompileShader(ShaderType?type, string code) { if (type.HasValue) { if (string.IsNullOrEmpty(code)) { Globals.Logger.Error($"Shader compilation warning: {type} shader empty"); return(null); } else { var shader = new CompiledShader(type.Value, code); if (!shader.Compile()) { return(null); } return(shader); } } return(null); }
private TabPage ProcessFile(string fileName, byte[] input, Package currentPackage) { var tab = new TabPage(); if (fileName.EndsWith(".vpk", StringComparison.Ordinal)) { var package = new Package(); try { if (input != null) { package.SetFileName(fileName); package.Read(new MemoryStream(input)); } else { package.Read(fileName); } } catch (InvalidDataException) when(input == null && Regex.IsMatch(fileName, @"_[0-9]{3}\.vpk$")) { // TODO: Update tab name fileName = $"{fileName.Substring(0, fileName.Length - 8)}_dir.vpk"; package.Read(fileName); } // create a TreeView with search capabilities, register its events, and add it to the tab var treeViewWithSearch = new TreeViewWithSearchResults(ImageList) { Dock = DockStyle.Fill, }; treeViewWithSearch.InitializeTreeViewFromPackage("treeViewVpk", package); treeViewWithSearch.TreeNodeMouseDoubleClick += VPK_OpenFile; treeViewWithSearch.TreeNodeMouseClick += VPK_OnClick; treeViewWithSearch.ListViewItemDoubleClick += VPK_OpenFile; treeViewWithSearch.ListViewItemRightClick += VPK_OnClick; tab.Controls.Add(treeViewWithSearch); // since we're in a separate thread, invoke to update the UI Invoke((MethodInvoker)(() => findToolStripButton.Enabled = true)); } else if (fileName.EndsWith(".vcs", StringComparison.Ordinal)) { var shader = new CompiledShader(); var buffer = new StringWriter(); var oldOut = Console.Out; Console.SetOut(buffer); if (input != null) { shader.Read(fileName, new MemoryStream(input)); } else { shader.Read(fileName); } Console.SetOut(oldOut); var control = new TextBox(); control.Font = new Font(FontFamily.GenericMonospace, control.Font.Size); control.Text = NormalizeLineEndings(buffer.ToString()); control.Dock = DockStyle.Fill; control.Multiline = true; control.ReadOnly = true; control.ScrollBars = ScrollBars.Both; tab.Controls.Add(control); } else { var resource = new Resource(); if (input != null) { resource.Read(new MemoryStream(input)); } else { resource.Read(fileName); } var resTabs = new TabControl { Dock = DockStyle.Fill, }; switch (resource.ResourceType) { case ResourceType.Texture: var tab2 = new TabPage("TEXTURE") { AutoScroll = true, }; try { var tex = (Texture)resource.Blocks[BlockType.DATA]; var control = new Forms.Texture { BackColor = Color.Black, }; control.SetImage(tex.GenerateBitmap().ToBitmap(), Path.GetFileNameWithoutExtension(fileName), tex.Width, tex.Height); tab2.Controls.Add(control); Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as an image", fileName, new ExportData { Resource = resource }); } catch (Exception e) { var control = new TextBox { Dock = DockStyle.Fill, Font = new Font(FontFamily.GenericMonospace, 8), Multiline = true, ReadOnly = true, Text = e.ToString(), }; tab2.Controls.Add(control); } resTabs.TabPages.Add(tab2); break; case ResourceType.Panorama: if (((Panorama)resource.Blocks[BlockType.DATA]).Names.Count > 0) { var nameTab = new TabPage("PANORAMA NAMES"); var nameControl = new DataGridView { Dock = DockStyle.Fill, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <Panorama.NameEntry>(((Panorama)resource.Blocks[BlockType.DATA]).Names), null), }; nameTab.Controls.Add(nameControl); resTabs.TabPages.Add(nameTab); } break; case ResourceType.PanoramaLayout: Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as XML", fileName, new ExportData { Resource = resource }); break; case ResourceType.PanoramaScript: Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as JS", fileName, new ExportData { Resource = resource }); break; case ResourceType.PanoramaStyle: Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as CSS", fileName, new ExportData { Resource = resource }); break; case ResourceType.Sound: var soundTab = new TabPage("SOUND"); var ap = new AudioPlayer(resource, soundTab); resTabs.TabPages.Add(soundTab); Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as {((Sound)resource.Blocks[BlockType.DATA]).Type}", fileName, new ExportData { Resource = resource }); break; case ResourceType.World: var world = new World(resource); var worldmv = new Renderer(mainTabs, fileName, currentPackage, RenderSubject.World); world.AddObjects(worldmv, fileName, currentPackage); var worldmeshTab = new TabPage("MAP"); var worldglControl = worldmv.CreateGL(); worldmeshTab.Controls.Add(worldglControl); resTabs.TabPages.Add(worldmeshTab); break; case ResourceType.WorldNode: var node = new WorldNode(resource); var nodemv = new Renderer(mainTabs, fileName, currentPackage); node.AddMeshes(nodemv, fileName, currentPackage); var nodemeshTab = new TabPage("MAP"); var nodeglControl = nodemv.CreateGL(); nodemeshTab.Controls.Add(nodeglControl); resTabs.TabPages.Add(nodemeshTab); break; case ResourceType.Model: // Create model var model = new Model(resource); // Create skeleton var skeleton = new Skeleton(resource); // Create tab var modelmeshTab = new TabPage("MESH"); var modelmv = new Renderer(mainTabs, fileName, currentPackage, RenderSubject.Model); model.LoadMeshes(modelmv, fileName, Matrix4.Identity, Vector4.One, currentPackage); // Add skeleton to renderer modelmv.SetSkeleton(skeleton); // Add animations if available var animGroupPaths = model.GetAnimationGroups(); foreach (var animGroupPath in animGroupPaths) { var animGroup = FileExtensions.LoadFileByAnyMeansNecessary(animGroupPath + "_c", fileName, currentPackage); modelmv.AddAnimations(AnimationGroupLoader.LoadAnimationGroup(animGroup, fileName)); } //Initialise OpenGL var modelglControl = modelmv.CreateGL(); modelmeshTab.Controls.Add(modelglControl); resTabs.TabPages.Add(modelmeshTab); break; case ResourceType.Mesh: if (!resource.Blocks.ContainsKey(BlockType.VBIB)) { Console.WriteLine("Old style model, no VBIB!"); break; } var meshTab = new TabPage("MESH"); var mv = new Renderer(mainTabs, fileName, currentPackage, RenderSubject.Model); Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as OBJ", fileName, new ExportData { Resource = resource, Renderer = mv }); mv.AddMeshObject(new MeshObject { Resource = resource }); var glControl = mv.CreateGL(); meshTab.Controls.Add(glControl); resTabs.TabPages.Add(meshTab); break; } foreach (var block in resource.Blocks) { if (block.Key == BlockType.RERL) { var externalRefsTab = new TabPage("External Refs"); var externalRefs = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ResourceExtRefList.ResourceReferenceInfo>(resource.ExternalReferences.ResourceRefInfoList), null), }; externalRefsTab.Controls.Add(externalRefs); resTabs.TabPages.Add(externalRefsTab); continue; } if (block.Key == BlockType.NTRO) { if (((ResourceIntrospectionManifest)block.Value).ReferencedStructs.Count > 0) { var externalRefsTab = new TabPage("Introspection Manifest: Structs"); var externalRefs = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ResourceIntrospectionManifest.ResourceDiskStruct>(((ResourceIntrospectionManifest)block.Value).ReferencedStructs), null), }; externalRefsTab.Controls.Add(externalRefs); resTabs.TabPages.Add(externalRefsTab); } if (((ResourceIntrospectionManifest)block.Value).ReferencedEnums.Count > 0) { var externalRefsTab = new TabPage("Introspection Manifest: Enums"); var externalRefs2 = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ResourceIntrospectionManifest.ResourceDiskEnum>(((ResourceIntrospectionManifest)block.Value).ReferencedEnums), null), }; externalRefsTab.Controls.Add(externalRefs2); resTabs.TabPages.Add(externalRefsTab); } //continue; } var tab2 = new TabPage(block.Key.ToString()); var control = new TextBox(); control.Font = new Font(FontFamily.GenericMonospace, control.Font.Size); try { if (block.Key == BlockType.DATA) { switch (resource.ResourceType) { case ResourceType.Particle: case ResourceType.Mesh: //Wrap it around a KV3File object to get the header. control.Text = NormalizeLineEndings(new KV3File(((BinaryKV3)block.Value).Data).ToString()); break; default: control.Text = NormalizeLineEndings(block.Value.ToString()); break; } } else { control.Text = NormalizeLineEndings(block.Value.ToString()); } } catch (Exception e) { control.Text = e.ToString(); } control.Dock = DockStyle.Fill; control.Multiline = true; control.ReadOnly = true; control.ScrollBars = ScrollBars.Both; tab2.Controls.Add(control); resTabs.TabPages.Add(tab2); } tab.Controls.Add(resTabs); } return(tab); }
public static CompiledShader CompileShader( this ID3DXEffectCompilerCustom compiler, string function, string profile, CompilerOptions option) { VerifyNonNullArgument( compiler, "compiler"); var buffer = default(ID3DXBuffer); var msg = default(ID3DXBuffer); var constantTable = default(ID3DXConstantTable); try { var ret = new CompiledShader(); if ( Succeeded( compiler.CompileShader( function, profile, option.ToD3DXSHADER(), out buffer, out msg, out constantTable))) { var constantDesc = constantTable.GetDesc(); if (constantDesc.HasValue) { var constantsList = from handle in constantTable.GetTopLevelConstantHandles() let constatns = from desc in constantTable.GetConstantDesc(handle) select desc.ToConstantInfo() select constatns.ToArray(); ret.TopLevelConstants = constantsList.ToArray(); ret.ConstantTableCreator = constantDesc.Value.Creator.ReadAsAnsiString(); ret.ConstantTableVersion = (int)constantDesc.Value.Version; } ret.Data = buffer.AsByteArray(); } ret.ErrorMessage = msg != null?msg.AsAnsiString() : String.Empty; return(ret); } finally { if (buffer != null) { Marshal.ReleaseComObject(buffer); buffer = null; } if (msg != null) { Marshal.ReleaseComObject(msg); msg = null; } if (constantTable != null) { Marshal.ReleaseComObject(constantTable); constantTable = null; } } }
public AsmToHlslAsmConverter(AsmListing asmSource, Microsoft.Xna.Framework.TargetPlatform platform, int shaderMaxConstants, int shaderMaxBooleanConstants, bool throwOnError) { maxConstant = -1; if (shaderMaxConstants != 0) { maxConstant = shaderMaxConstants; } maxBoolean = -1; if (shaderMaxBooleanConstants != 0) { maxBoolean = shaderMaxBooleanConstants; } maxRegister = -1; this.samplers = new List <InputOutput>(); this.inputs = new List <InputOutput>(); this.outputs = new List <InputOutput>(); this.assignedConstants = new Dictionary <int, bool>(); this.localConstants = new Dictionary <int, string>(); this.localBooleanConstants = new Dictionary <int, string>(); this.localIntegerConstants = new Dictionary <int, string>(); for (int i = 0; i < 256; i++) { assignedConstants.Add(i, false); } this.source = new StringBuilder(); this.listing = asmSource; if (listing.GetCommandCount() > 0) { //attempt to decode the shader if (DetectProfile()) { List <Command> commands = new List <Command>(); for (int i = 1; i < listing.GetCommandCount(); i++) { //extract the commands Command cmd = new Command(listing.GetCommand(i)); if (cmd.name != null) { commands.Add(cmd); } } List <Command> allCommands = new List <Command>(); List <Command> newCommands = new List <Command>(); foreach (Command command in commands) { newCommands.Clear(); GenerateCode(command, newCommands); allCommands.AddRange(newCommands); } commands = allCommands; bool isAsm = false; foreach (Command cmd in commands) { if (cmd.isAsm != isAsm) { if (isAsm) { this.source.Append("};"); this.source.AppendLine(); } else { this.source.Append("asm{"); this.source.AppendLine(); } isAsm = cmd.isAsm; } this.source.Append(cmd.name); for (int i = 0; i < cmd.args.Length; i++) { this.source.Append(' '); if (i != 0) { this.source.Append(','); } for (int a = 0; a < cmd.args[i].Length; a++) { this.source.Append(cmd.args[i][a]); } } this.source.AppendLine(); } if (isAsm) { this.source.Append("};"); } } } BuildMethod(); CompiledShader shader = ShaderCompiler.CompileFromSource( this.source.ToString(), null, null, CompilerOptions.AvoidFlowControl, "Main", profile, platform); if (throwOnError && !shader.Success) { Common.ThrowError("An error occured running the Xbox shader HLSL/ASM preprocessor", shader.ErrorsAndWarnings, asmSource.ToString()); } if (!shader.Success) { //tried the best.. if it failed, ohh well, go back to AssembleFromSource //probably used complex flow control? string rawAsm = asmSource.ToString(); shader = ShaderCompiler.AssembleFromSource(rawAsm, null, null, CompilerOptions.None, platform); if (!shader.Success) { Common.ThrowError(shader.ErrorsAndWarnings, rawAsm); } } output = shader.GetShaderCode(); }
// public void Awake() // { // } // public void OnDestroy() // { // } void OnGUI() { Color originalBackgroundColor = GUI.backgroundColor; //Title GUI.color = Color.cyan; GUILayout.Label("Build the player and see the variants list here.", EditorStyles.wordWrappedLabel); GUI.color = Color.white; if (savedFile != "") { GUI.color = Color.green; //Result GUILayout.Label("Build Time : " + SVL.buildTime.ToString("0.000") + " seconds", EditorStyles.wordWrappedLabel); GUILayout.Label("Shader Count : " + SVL.shaderlist.Count, EditorStyles.wordWrappedLabel); GUILayout.Label("Total Variant Count : " + SVL.variantTotalCount, EditorStyles.wordWrappedLabel); //GUILayout.Label ( "Total Data Count : " + SVL.compiledTotalCount, EditorStyles.wordWrappedLabel ); //Saved file path GUILayout.Label("Saved: " + savedFile, EditorStyles.wordWrappedLabel); //Show folder button GUI.color = Color.white; if (GUILayout.Button("Show in explorer", GUILayout.Width(200))) { System.Diagnostics.Process.Start("explorer.exe", "/select," + savedFile.Replace(@"/", @"\")); // explorer doesn't like front slashes } } GUI.color = Color.white; GUILayout.Space(15); //Width for the columns & style float currentSize = this.position.width; float widthForEach = currentSize / (SVL.columns.Length - 1 + currentSize * 0.0002f); GUIStyle background = new GUIStyle { normal = { background = Texture2D.whiteTexture, textColor = Color.white } }; //Column Titles EditorGUILayout.BeginHorizontal(); for (int i = 1; i < SVL.columns.Length; i++) { int al = i % 2; GUI.backgroundColor = al == 0 ? columnColor1 :columnColor2; GUILayoutOption[] columnLayoutOption = new GUILayoutOption[] { GUILayout.Width(Mathf.RoundToInt(widthForEach * widthScale[i])), GUILayout.Height(55) }; EditorGUILayout.LabelField(SVL.columns[i].Replace(" ", "\n"), background, columnLayoutOption); } EditorGUILayout.EndHorizontal(); //Reset color GUI.backgroundColor = originalBackgroundColor; GUI.color = Color.white; //Scroll Start scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(0), GUILayout.Height(0)); //Display result if (SVL.shaderlist.Count > 0 && SVL.rowData.Count > 0) { for (int k = 1; k < SVL.rowData.Count; k++) //first row is title so start with 1 { string shaderName = SVL.rowData[k][0]; int shaderIndex = SVL.shaderlist.FindIndex(o => o.name == shaderName); CompiledShader currentShader = SVL.shaderlist[shaderIndex]; if (shaderName != SVL.rowData[k - 1][0]) //show title { GUI.backgroundColor = originalBackgroundColor; currentShader.guiEnabled = EditorGUILayout.Foldout(currentShader.guiEnabled, shaderName + " (" + currentShader.noOfVariantsForThisShader + ")"); SVL.shaderlist[shaderIndex] = currentShader; } //Show the shader variants if (currentShader.guiEnabled) { EditorGUILayout.BeginHorizontal(); for (int i = 1; i < SVL.columns.Length; i++) { string t = SVL.rowData[k][i]; int al = i % 2; GUI.backgroundColor = al == 0 ? columnColor1 :columnColor2; if (t == "True") { background.normal.textColor = Color.green; } else if (t == "False") { background.normal.textColor = Color.red; } else if (t.Contains("[Global]")) { background.normal.textColor = Color.cyan; } else if (t.Contains("[Local]")) { background.normal.textColor = Color.yellow; } else { background.normal.textColor = Color.white; } EditorGUILayout.LabelField(t, background, GUILayout.Width(widthForEach * widthScale[i])); } EditorGUILayout.EndHorizontal(); } GUI.backgroundColor = originalBackgroundColor; } } //Scroll End GUILayout.FlexibleSpace(); GUILayout.EndScrollView(); EditorGUILayout.Separator(); }
private void ExtractBytes() { if (platform == Platform.Both || platform == Platform.Windows) { string vsAsm = asmTechnique.VertexShader.ToString(); string psAsm = asmTechnique.PixelShader.ToString(); //generate PC shaders from ASM (easy) //vertex shader CompiledShader compiledShader = ShaderCompiler.AssembleFromSource(vsAsm, null, null, CompilerOptions.None, TargetPlatform.Windows); if (!compiledShader.Success) { Common.ThrowError(compiledShader.ErrorsAndWarnings, vsAsm); } this.vsBytesPc = compiledShader.GetShaderCode(); //pixel shader compiledShader = ShaderCompiler.AssembleFromSource(psAsm, null, null, CompilerOptions.None, TargetPlatform.Windows); if (!compiledShader.Success) { Common.ThrowError(compiledShader.ErrorsAndWarnings, psAsm); } this.psBytesPc = compiledShader.GetShaderCode(); } if (platform == Platform.Both || platform == Platform.Xbox) { //this is where things get tricky... HlslMethod vertexShaderMethod = source.GetMethod(hlslTechnique.VertexShaderMethodName, platform); HlslMethod pixelShaderMethod = source.GetMethod(hlslTechnique.PixelShaderMethodName, platform); //if a shader uses vfetch, it gets compiled as HLSL from the effect*, otherwise, HLSL that embeds ASM :-) //*or a stub method if it tries to use uniform inputs to the method... VFetchXboxMethodExtractor vfetchExtractor = new VFetchXboxMethodExtractor(source, hlslTechnique); if (vertexShaderMethod.UsesVFetch) { this.vsBytesXbox = vfetchExtractor.GetVertexShaderCode(); } else { //otherwise, //run the shader through a processor that try to bypasses ShaderCompiler.AssembleFromSource, //which is buggy... But it doesn't always work. //need to work out the max number of constants used RegisterSet set = asmTechnique.VertexShader.RegisterSet; int maxConstant = set.FloatRegisterCount; int maxBooleanConstants = set.BooleanRegisterCount; AsmToHlslAsmConverter converter = new AsmToHlslAsmConverter(asmTechnique.VertexShader, TargetPlatform.Xbox360, maxConstant, maxBooleanConstants, source.DebugHlslProcessXboxShader); this.vsBytesXbox = converter.GetOutput(); } //do it all again for the pixel shader if (pixelShaderMethod.UsesVFetch) { this.psBytesXbox = vfetchExtractor.GetPixelShaderCode(); } else { RegisterSet set = asmTechnique.PixelShader.RegisterSet; int maxConstant = set.FloatRegisterCount; int maxBooleanConstants = set.BooleanRegisterCount; AsmToHlslAsmConverter converter = new AsmToHlslAsmConverter(asmTechnique.PixelShader, TargetPlatform.Xbox360, maxConstant, maxBooleanConstants, source.DebugHlslProcessXboxShader); this.psBytesXbox = converter.GetOutput(); } //done! } }
private TabPage ProcessFile(string fileName, byte[] input, TreeViewWithSearchResults.TreeViewPackageTag currentPackage) { var tab = new TabPage(); var vrfGuiContext = new VrfGuiContext(fileName, currentPackage); uint magic = 0; ushort magicResourceVersion = 0; if (input != null) { if (input.Length >= 6) { magic = BitConverter.ToUInt32(input, 0); magicResourceVersion = BitConverter.ToUInt16(input, 4); } } else { var magicData = new byte[6]; using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { fs.Read(magicData, 0, 6); } magic = BitConverter.ToUInt32(magicData, 0); magicResourceVersion = BitConverter.ToUInt16(magicData, 4); } if (magic != Package.MAGIC && input == null && Regex.IsMatch(fileName, @"_[0-9]{3}\.vpk$")) { // TODO: Update tab name fileName = $"{fileName.Substring(0, fileName.Length - 8)}_dir.vpk"; magic = Package.MAGIC; } if (magic == Package.MAGIC) { var package = new Package(); if (input != null) { package.SetFileName(fileName); package.Read(new MemoryStream(input)); } else { package.Read(fileName); } // create a TreeView with search capabilities, register its events, and add it to the tab var treeViewWithSearch = new TreeViewWithSearchResults(ImageList); treeViewWithSearch.InitializeTreeViewFromPackage(fileName, new TreeViewWithSearchResults.TreeViewPackageTag { Package = package, ParentPackage = currentPackage?.Package, }); treeViewWithSearch.TreeNodeMouseDoubleClick += VPK_OpenFile; treeViewWithSearch.TreeNodeMouseClick += VPK_OnClick; treeViewWithSearch.ListViewItemDoubleClick += VPK_OpenFile; treeViewWithSearch.ListViewItemRightClick += VPK_OnClick; treeViewWithSearch.Disposed += VPK_Disposed; tab.Controls.Add(treeViewWithSearch); // since we're in a separate thread, invoke to update the UI Invoke((MethodInvoker)(() => findToolStripButton.Enabled = true)); } else if (magic == CompiledShader.MAGIC) { var shader = new CompiledShader(); var buffer = new StringWriter(); var oldOut = Console.Out; Console.SetOut(buffer); if (input != null) { shader.Read(fileName, new MemoryStream(input)); } else { shader.Read(fileName); } Console.SetOut(oldOut); var control = new TextBox(); control.Font = new Font(FontFamily.GenericMonospace, control.Font.Size); control.Text = NormalizeLineEndings(buffer.ToString()); control.Dock = DockStyle.Fill; control.Multiline = true; control.ReadOnly = true; control.ScrollBars = ScrollBars.Both; tab.Controls.Add(control); } else if (magic == ClosedCaptions.MAGIC) { var captions = new ClosedCaptions(); if (input != null) { captions.Read(fileName, new MemoryStream(input)); } else { captions.Read(fileName); } var control = new DataGridView { Dock = DockStyle.Fill, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ClosedCaption>(captions.Captions), null), ScrollBars = ScrollBars.Both, }; tab.Controls.Add(control); } else if (magic == ToolsAssetInfo.MAGIC) { var toolsAssetInfo = new ToolsAssetInfo(); if (input != null) { toolsAssetInfo.Read(new MemoryStream(input)); } else { toolsAssetInfo.Read(fileName); } var text = new TextBox { Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical, Multiline = true, ReadOnly = true, Text = NormalizeLineEndings(toolsAssetInfo.ToString()), }; tab.Controls.Add(text); } else if (magic == BinaryKV3.MAGIC || magic == BinaryKV3.MAGIC2) { var kv3 = new BinaryKV3(); Stream kv3stream; if (input != null) { kv3stream = new MemoryStream(input); } else { kv3stream = File.OpenRead(fileName); } using (var binaryReader = new BinaryReader(kv3stream)) { kv3.Size = (uint)kv3stream.Length; kv3.Read(binaryReader, null); } kv3stream.Close(); var control = new TextBox(); control.Font = new Font(FontFamily.GenericMonospace, control.Font.Size); control.Text = kv3.ToString(); control.Dock = DockStyle.Fill; control.Multiline = true; control.ReadOnly = true; control.ScrollBars = ScrollBars.Both; tab.Controls.Add(control); } else if (magicResourceVersion == Resource.KnownHeaderVersion) { var resource = new Resource(); if (input != null) { resource.Read(new MemoryStream(input)); } else { resource.Read(fileName); } var resTabs = new TabControl { Dock = DockStyle.Fill, }; switch (resource.ResourceType) { case ResourceType.Texture: var tab2 = new TabPage("TEXTURE") { AutoScroll = true, }; try { var tex = (Texture)resource.DataBlock; var control = new Forms.Texture { BackColor = Color.Black, }; control.SetImage(tex.GenerateBitmap().ToBitmap(), Path.GetFileNameWithoutExtension(fileName), tex.Width, tex.Height); tab2.Controls.Add(control); Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as an image", fileName, new ExportData { Resource = resource }); } catch (Exception e) { var control = new TextBox { Dock = DockStyle.Fill, Font = new Font(FontFamily.GenericMonospace, 8), Multiline = true, ReadOnly = true, Text = e.ToString(), }; tab2.Controls.Add(control); } resTabs.TabPages.Add(tab2); break; case ResourceType.Panorama: if (((Panorama)resource.DataBlock).Names.Count > 0) { var nameTab = new TabPage("PANORAMA NAMES"); var nameControl = new DataGridView { Dock = DockStyle.Fill, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <Panorama.NameEntry>(((Panorama)resource.DataBlock).Names), null), }; nameTab.Controls.Add(nameControl); resTabs.TabPages.Add(nameTab); } break; case ResourceType.PanoramaLayout: Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as XML", fileName, new ExportData { Resource = resource }); break; case ResourceType.PanoramaScript: Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as JS", fileName, new ExportData { Resource = resource }); break; case ResourceType.PanoramaStyle: Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as CSS", fileName, new ExportData { Resource = resource }); break; case ResourceType.Particle: var viewerControl = new GLParticleViewer(vrfGuiContext); viewerControl.Load += (_, __) => { var particleSystem = (ParticleSystem)resource.DataBlock; var particleRenderer = new ParticleRenderer(particleSystem, vrfGuiContext); viewerControl.AddRenderer(particleRenderer); }; var particleRendererTab = new TabPage("PARTICLE"); particleRendererTab.Controls.Add(viewerControl.Control); resTabs.TabPages.Add(particleRendererTab); break; case ResourceType.Sound: var soundTab = new TabPage("SOUND"); var ap = new AudioPlayer(resource, soundTab); resTabs.TabPages.Add(soundTab); Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as {((Sound)resource.DataBlock).SoundType}", fileName, new ExportData { Resource = resource }); break; case ResourceType.World: var worldmeshTab = new TabPage("MAP"); worldmeshTab.Controls.Add(new GLWorldViewer(vrfGuiContext, (World)resource.DataBlock).ViewerControl); resTabs.TabPages.Add(worldmeshTab); break; case ResourceType.WorldNode: var nodemeshTab = new TabPage("WORLD NODE"); nodemeshTab.Controls.Add(new GLWorldViewer(vrfGuiContext, (WorldNode)resource.DataBlock).ViewerControl); resTabs.TabPages.Add(nodemeshTab); break; case ResourceType.Model: var modelRendererTab = new TabPage("MODEL"); modelRendererTab.Controls.Add(new GLModelViewer(vrfGuiContext, (Model)resource.DataBlock).ViewerControl); resTabs.TabPages.Add(modelRendererTab); break; case ResourceType.Mesh: if (!resource.ContainsBlockType(BlockType.VBIB)) { Console.WriteLine("Old style model, no VBIB!"); break; } Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as OBJ", fileName, new ExportData { Resource = resource, VrfGuiContext = vrfGuiContext }); var meshRendererTab = new TabPage("MESH"); meshRendererTab.Controls.Add(new GLModelViewer(vrfGuiContext, new Mesh(resource)).ViewerControl); resTabs.TabPages.Add(meshRendererTab); break; case ResourceType.Material: var materialViewerControl = new GLMaterialViewer(); materialViewerControl.Load += (_, __) => { var material = vrfGuiContext.MaterialLoader.LoadMaterial(resource); var materialRenderer = new MaterialRenderer(material, vrfGuiContext); materialViewerControl.AddRenderer(materialRenderer); }; var materialRendererTab = new TabPage("MATERIAL"); materialRendererTab.Controls.Add(materialViewerControl.Control); resTabs.TabPages.Add(materialRendererTab); break; } foreach (var block in resource.Blocks) { if (block.Type == BlockType.RERL) { var externalRefsTab = new TabPage("External Refs"); var externalRefs = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ResourceExtRefList.ResourceReferenceInfo>(resource.ExternalReferences.ResourceRefInfoList), null), }; externalRefsTab.Controls.Add(externalRefs); resTabs.TabPages.Add(externalRefsTab); continue; } if (block.Type == BlockType.NTRO) { if (((ResourceIntrospectionManifest)block).ReferencedStructs.Count > 0) { var externalRefsTab = new TabPage("Introspection Manifest: Structs"); var externalRefs = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ResourceIntrospectionManifest.ResourceDiskStruct>(((ResourceIntrospectionManifest)block).ReferencedStructs), null), }; externalRefsTab.Controls.Add(externalRefs); resTabs.TabPages.Add(externalRefsTab); } if (((ResourceIntrospectionManifest)block).ReferencedEnums.Count > 0) { var externalRefsTab = new TabPage("Introspection Manifest: Enums"); var externalRefs2 = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ResourceIntrospectionManifest.ResourceDiskEnum>(((ResourceIntrospectionManifest)block).ReferencedEnums), null), }; externalRefsTab.Controls.Add(externalRefs2); resTabs.TabPages.Add(externalRefsTab); } //continue; } var tab2 = new TabPage(block.Type.ToString()); try { var control = new TextBox(); control.Font = new Font(FontFamily.GenericMonospace, control.Font.Size); if (block.Type == BlockType.DATA) { switch (resource.ResourceType) { case ResourceType.Sound: control.Text = NormalizeLineEndings(((Sound)block).ToString()); break; case ResourceType.Particle: case ResourceType.Mesh: if (block is BinaryKV3 blockKeyvalues) { //Wrap it around a KV3File object to get the header. control.Text = NormalizeLineEndings(blockKeyvalues.GetKV3File().ToString()); } else if (block is NTRO blockNTRO) { control.Text = NormalizeLineEndings(blockNTRO.ToString()); } break; default: control.Text = NormalizeLineEndings(block.ToString()); break; } } else { control.Text = NormalizeLineEndings(block.ToString()); } control.Dock = DockStyle.Fill; control.Multiline = true; control.ReadOnly = true; control.ScrollBars = ScrollBars.Both; tab2.Controls.Add(control); } catch (Exception e) { Console.WriteLine(e); var bv = new ByteViewer(); bv.Dock = DockStyle.Fill; tab2.Controls.Add(bv); Invoke((MethodInvoker)(() => { resource.Reader.BaseStream.Position = block.Offset; bv.SetBytes(resource.Reader.ReadBytes((int)block.Size)); })); } resTabs.TabPages.Add(tab2); } if (resource.ResourceType == ResourceType.PanoramaLayout || resource.ResourceType == ResourceType.PanoramaScript || resource.ResourceType == ResourceType.PanoramaStyle || resource.ResourceType == ResourceType.SoundEventScript || resource.ResourceType == ResourceType.SoundStackScript || resource.ResourceType == ResourceType.EntityLump) { resTabs.SelectTab(resTabs.TabCount - 1); } tab.Controls.Add(resTabs); } else { var resTabs = new TabControl { Dock = DockStyle.Fill, }; tab.Controls.Add(resTabs); var bvTab = new TabPage("Hex"); var bv = new ByteViewer { Dock = DockStyle.Fill, }; bvTab.Controls.Add(bv); resTabs.TabPages.Add(bvTab); if (input == null) { input = File.ReadAllBytes(fileName); } if (!input.Contains <byte>(0x00)) { var textTab = new TabPage("Text"); var text = new TextBox { Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical, Multiline = true, ReadOnly = true, Text = System.Text.Encoding.UTF8.GetString(input), }; textTab.Controls.Add(text); resTabs.TabPages.Add(textTab); resTabs.SelectedTab = textTab; } Invoke((MethodInvoker)(() => { bv.SetBytes(input); })); } return(tab); }
static GpuVertexShaderData() { StringBuilder vs = new StringBuilder(); vs.AppendLine("#if XBOX360"); CompiledShader vscs_0 = ShaderCompiler.CompileFromSource(vsCode, null, null, CompilerOptions.None, "VS_FRAME", ShaderProfile.VS_3_0, TargetPlatform.Xbox360); CompiledShader vscs_1 = ShaderCompiler.CompileFromSource(vsCode, null, null, CompilerOptions.None, "VS_ONCE", ShaderProfile.VS_3_0, TargetPlatform.Xbox360); CompiledShader vscs_2 = ShaderCompiler.CompileFromSource(vsCode, null, null, CompilerOptions.None, "VS_ONCE_CLONE", ShaderProfile.VS_3_0, TargetPlatform.Xbox360); byte[] bytes = vscs_0.GetShaderCode(); vs.Append("\t\tpublic static byte[] VS_FRAME = new byte[] { "); for (int i = 0; i < bytes.Length; i++) { vs.Append((int)bytes[i]); vs.Append(","); } vs.AppendLine("};"); bytes = vscs_1.GetShaderCode(); vs.Append("\t\tpublic static byte[] VS_ONCE = new byte[] { "); for (int i = 0; i < bytes.Length; i++) { vs.Append((int)bytes[i]); vs.Append(","); } vs.AppendLine("};"); bytes = vscs_2.GetShaderCode(); vs.Append("\t\tpublic static byte[] VS_ONCE_CLONE = new byte[] { "); for (int i = 0; i < bytes.Length; i++) { vs.Append((int)bytes[i]); vs.Append(","); } vs.AppendLine("};"); vs.AppendLine("#else"); //do it all again for PC vscs_0 = ShaderCompiler.CompileFromSource(vsCode, null, null, CompilerOptions.None, "VS_FRAME", ShaderProfile.VS_3_0, TargetPlatform.Windows); vscs_1 = ShaderCompiler.CompileFromSource(vsCode, null, null, CompilerOptions.None, "VS_ONCE", ShaderProfile.VS_3_0, TargetPlatform.Windows); vscs_2 = ShaderCompiler.CompileFromSource(vsCode, null, null, CompilerOptions.None, "VS_ONCE_CLONE", ShaderProfile.VS_3_0, TargetPlatform.Windows); bytes = vscs_0.GetShaderCode(); vs.Append("\t\tpublic static byte[] VS_FRAME = new byte[] { "); for (int i = 0; i < bytes.Length; i++) { vs.Append((int)bytes[i]); vs.Append(","); } vs.AppendLine("};"); bytes = vscs_1.GetShaderCode(); vs.Append("\t\tpublic static byte[] VS_ONCE = new byte[] { "); for (int i = 0; i < bytes.Length; i++) { vs.Append((int)bytes[i]); vs.Append(","); } vs.AppendLine("};"); bytes = vscs_2.GetShaderCode(); vs.Append("\t\tpublic static byte[] VS_ONCE_CLONE = new byte[] { "); for (int i = 0; i < bytes.Length; i++) { vs.Append((int)bytes[i]); vs.Append(","); } vs.AppendLine("};"); vs.AppendLine("#endif"); string vss = vs.ToString(); System.Diagnostics.Debugger.Break(); }
public static ParticleSystemCompiledShaderData BuildGpuLogicPixelShader(IEnumerable <ParticleSystemLogicStep> steps, LogicType logicType, bool useUserValues, bool useColours, bool storeLifeData, TargetPlatform targetPlatform, bool useUserDataPositionBuffer) { if (steps == null) { throw new ArgumentNullException(); } StringBuilder output = new StringBuilder(); Random random = new Random(); foreach (ParticleSystemLogicStep step in steps) { BuildStep(step, output, 1, random); } string psCode = GpuParticleShaderBuilder.BasePixelShader.Replace(GpuParticleShaderBuilder.replaceMarker, output.ToString()).Replace("_#", "#"); //build the shader header and main method. string headerPS = ""; string methodHeaderPS = ""; string methodPS = "void PS(float4 texRandIndex : TEXCOORD0"; if (logicType != LogicType.Frame) { methodPS += ", float4 lifeIndex : TEXCOORD1"; } else { methodHeaderPS += "float4 lifeIndex = 0;"; } if (logicType == LogicType.Once) { methodPS += ", float4 defaultPosition : TEXCOORD2"; methodPS += ", float4 defaultVelocity : TEXCOORD3"; methodPS += ", float4 defaultColour : TEXCOORD4"; methodPS += ", float4 defaultUserData : TEXCOORD5"; } else { methodHeaderPS += "float4 defaultPosition = 0, defaultVelocity = 0;"; methodHeaderPS += "float4 defaultColour = 1, defaultUserData = 0;"; } int colIndex = 2; methodPS += ", out float4 posOut : COLOR0, out float4 velOut : COLOR1"; if (useColours) { methodPS += string.Format(", out float4 colOut : COLOR{0}", colIndex++); } else { methodHeaderPS += "float4 colOut = 1;"; } if (useUserValues) { methodPS += string.Format(", out float4 userOut : COLOR{0}", colIndex++); } else { methodHeaderPS += "float4 userOut = 0;"; } methodPS += ")\n{\n\t" + methodHeaderPS; methodPS += "\n\t" + @"PS_Method(texRandIndex, lifeIndex, defaultPosition, defaultVelocity, defaultColour, defaultUserData, posOut, velOut, colOut, userOut);" ; methodPS += "\n}"; int colourIndex = -1, userIndex = -1, lifeIndex = -1; if (logicType != LogicType.Once) { int samplerIndex = 3; headerPS = Environment.NewLine + "#define TEXTURE_PARTICLE_METHOD" + Environment.NewLine; if (useColours) { colourIndex = samplerIndex; headerPS += Environment.NewLine + "#define USER_COLOUR_TEX" + Environment.NewLine; headerPS += Environment.NewLine + string.Format(@"sampler2D ColourSampler : register(s{0});", samplerIndex++) + Environment.NewLine; } if (useUserValues) { userIndex = samplerIndex; headerPS += Environment.NewLine + "#define USER_USER_TEX" + Environment.NewLine; headerPS += Environment.NewLine + string.Format(@"sampler2D UserSampler : register(s{0});", samplerIndex++) + Environment.NewLine; } if (storeLifeData && logicType == LogicType.Frame) { lifeIndex = samplerIndex; headerPS += Environment.NewLine + "#define USER_LIFE_TEX" + Environment.NewLine; headerPS += Environment.NewLine + string.Format(@"sampler2D LifeSampler : register(s{0});", samplerIndex++) + Environment.NewLine; } if (logicType == LogicType.Frame || logicType == LogicType.FrameMove) { headerPS += Environment.NewLine + "#define ADD_VELOCITY" + Environment.NewLine; } } if ((logicType == LogicType.OnceClone || logicType == LogicType.Once) && useUserDataPositionBuffer) { headerPS += Environment.NewLine + "#define WRITE_POS_TO_USER" + Environment.NewLine; } psCode = headerPS + Environment.NewLine + psCode + Environment.NewLine + methodPS; CompiledShader pscs = ShaderCompiler.CompileFromSource(psCode, null, null, CompilerOptions.None, "PS", ShaderProfile.PS_3_0, targetPlatform); if (!pscs.Success) { throw new InvalidOperationException("GPU Particle System Pixel Shader failed to compile:" + Environment.NewLine + pscs.ErrorsAndWarnings); } return(new ParticleSystemCompiledShaderData(pscs.GetShaderCode(), colourIndex, userIndex, lifeIndex)); }
private TabPage ProcessFile(string fileName, byte[] input, Package currentPackage) { var tab = new TabPage(); var vrfGuiContext = new VrfGuiContext { FileName = fileName, CurrentPackage = currentPackage, }; uint magic = 0; ushort magicResourceVersion = 0; if (input != null) { magic = BitConverter.ToUInt32(input, 0); magicResourceVersion = BitConverter.ToUInt16(input, 4); } else { var magicData = new byte[6]; using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { fs.Read(magicData, 0, 6); } magic = BitConverter.ToUInt32(magicData, 0); magicResourceVersion = BitConverter.ToUInt16(magicData, 4); } if (magic != Package.MAGIC && input == null && Regex.IsMatch(fileName, @"_[0-9]{3}\.vpk$")) { // TODO: Update tab name fileName = $"{fileName.Substring(0, fileName.Length - 8)}_dir.vpk"; magic = Package.MAGIC; } if (magic == Package.MAGIC || fileName.EndsWith(".vpk", StringComparison.Ordinal)) { var package = new Package(); if (input != null) { package.SetFileName(fileName); package.Read(new MemoryStream(input)); } else { package.Read(fileName); } // create a TreeView with search capabilities, register its events, and add it to the tab var treeViewWithSearch = new TreeViewWithSearchResults(ImageList) { Dock = DockStyle.Fill, }; treeViewWithSearch.InitializeTreeViewFromPackage("treeViewVpk", package); treeViewWithSearch.TreeNodeMouseDoubleClick += VPK_OpenFile; treeViewWithSearch.TreeNodeMouseClick += VPK_OnClick; treeViewWithSearch.ListViewItemDoubleClick += VPK_OpenFile; treeViewWithSearch.ListViewItemRightClick += VPK_OnClick; tab.Controls.Add(treeViewWithSearch); // since we're in a separate thread, invoke to update the UI Invoke((MethodInvoker)(() => findToolStripButton.Enabled = true)); } else if (magic == CompiledShader.MAGIC || fileName.EndsWith(".vcs", StringComparison.Ordinal)) { var shader = new CompiledShader(); var buffer = new StringWriter(); var oldOut = Console.Out; Console.SetOut(buffer); if (input != null) { shader.Read(fileName, new MemoryStream(input)); } else { shader.Read(fileName); } Console.SetOut(oldOut); var control = new TextBox(); control.Font = new Font(FontFamily.GenericMonospace, control.Font.Size); control.Text = NormalizeLineEndings(buffer.ToString()); control.Dock = DockStyle.Fill; control.Multiline = true; control.ReadOnly = true; control.ScrollBars = ScrollBars.Both; tab.Controls.Add(control); } else if (magic == ClosedCaptions.MAGIC || fileName.EndsWith(".dat", StringComparison.Ordinal)) { var captions = new ClosedCaptions(); if (input != null) { captions.Read(fileName, new MemoryStream(input)); } else { captions.Read(fileName); } var control = new DataGridView { Dock = DockStyle.Fill, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ClosedCaption>(captions.Captions), null), ScrollBars = ScrollBars.Both, }; tab.Controls.Add(control); } else if (magic == BinaryKV3.MAGIC || magic == BinaryKV3.MAGIC2) { var kv3 = new BinaryKV3(); using (var file = File.OpenRead(fileName)) using (var binaryReader = new BinaryReader(file)) { kv3.Size = (uint)file.Length; kv3.Read(binaryReader, null); } var control = new TextBox(); control.Font = new Font(FontFamily.GenericMonospace, control.Font.Size); control.Text = kv3.ToString(); control.Dock = DockStyle.Fill; control.Multiline = true; control.ReadOnly = true; control.ScrollBars = ScrollBars.Both; tab.Controls.Add(control); } else if (magicResourceVersion == Resource.KnownHeaderVersion || fileName.EndsWith("_c", StringComparison.Ordinal)) { var resource = new Resource(); if (input != null) { resource.Read(new MemoryStream(input)); } else { resource.Read(fileName); } var resTabs = new TabControl { Dock = DockStyle.Fill, }; switch (resource.ResourceType) { case ResourceType.Texture: var tab2 = new TabPage("TEXTURE") { AutoScroll = true, }; try { var tex = (Texture)resource.Blocks[BlockType.DATA]; var control = new Forms.Texture { BackColor = Color.Black, }; control.SetImage(tex.GenerateBitmap().ToBitmap(), Path.GetFileNameWithoutExtension(fileName), tex.Width, tex.Height); tab2.Controls.Add(control); Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as an image", fileName, new ExportData { Resource = resource }); } catch (Exception e) { var control = new TextBox { Dock = DockStyle.Fill, Font = new Font(FontFamily.GenericMonospace, 8), Multiline = true, ReadOnly = true, Text = e.ToString(), }; tab2.Controls.Add(control); } resTabs.TabPages.Add(tab2); break; case ResourceType.Panorama: if (((Panorama)resource.Blocks[BlockType.DATA]).Names.Count > 0) { var nameTab = new TabPage("PANORAMA NAMES"); var nameControl = new DataGridView { Dock = DockStyle.Fill, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <Panorama.NameEntry>(((Panorama)resource.Blocks[BlockType.DATA]).Names), null), }; nameTab.Controls.Add(nameControl); resTabs.TabPages.Add(nameTab); } break; case ResourceType.PanoramaLayout: Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as XML", fileName, new ExportData { Resource = resource }); break; case ResourceType.PanoramaScript: Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as JS", fileName, new ExportData { Resource = resource }); break; case ResourceType.PanoramaStyle: Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as CSS", fileName, new ExportData { Resource = resource }); break; case ResourceType.Particle: var particleGLControl = new GLRenderControl(); particleGLControl.Load += (_, __) => { particleGLControl.Camera.SetViewportSize(particleGLControl.Control.Width, particleGLControl.Control.Height); particleGLControl.Camera.SetLocation(new Vector3(200)); particleGLControl.Camera.LookAt(new Vector3(0)); var particleSystem = new ParticleSystem(resource); var particleGrid = new ParticleGrid(20, 5); var particleRenderer = new ParticleRenderer(particleSystem, vrfGuiContext); particleGLControl.Paint += (sender, args) => { particleGrid.Render(args.Camera.ProjectionMatrix, args.Camera.CameraViewMatrix); // Updating FPS-coupled dynamic step particleRenderer.Update(args.FrameTime); particleRenderer.Render(args.Camera); }; }; var particleRendererTab = new TabPage("PARTICLE"); particleRendererTab.Controls.Add(particleGLControl.Control); resTabs.TabPages.Add(particleRendererTab); break; case ResourceType.Sound: var soundTab = new TabPage("SOUND"); var ap = new AudioPlayer(resource, soundTab); resTabs.TabPages.Add(soundTab); Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as {((Sound)resource.Blocks[BlockType.DATA]).Type}", fileName, new ExportData { Resource = resource }); break; case ResourceType.World: var world = new World(resource); var renderWorld = new RenderWorld(world); var worldmv = new Renderer(mainTabs, fileName, currentPackage, RenderSubject.World); renderWorld.AddObjects(worldmv, fileName, currentPackage); var worldmeshTab = new TabPage("MAP"); var worldglControl = worldmv.CreateGL(); worldmeshTab.Controls.Add(worldglControl); resTabs.TabPages.Add(worldmeshTab); break; case ResourceType.WorldNode: var node = new RenderWorldNode(resource); var nodemv = new Renderer(mainTabs, fileName, currentPackage); node.AddMeshes(nodemv, fileName, currentPackage); var nodemeshTab = new TabPage("MAP"); var nodeglControl = nodemv.CreateGL(); nodemeshTab.Controls.Add(nodeglControl); resTabs.TabPages.Add(nodemeshTab); break; case ResourceType.Model: // Create model var model = new Model(resource); var renderModel = new RenderModel(model); // Create skeleton var skeleton = model.GetSkeleton(); // Create tab var modelmeshTab = new TabPage("MESH"); var modelmv = new Renderer(mainTabs, fileName, currentPackage, RenderSubject.Model); renderModel.LoadMeshes(modelmv, fileName, Matrix4.Identity, Vector4.One, currentPackage); // Add skeleton to renderer modelmv.SetSkeleton(skeleton); // Add animations if available var animGroupPaths = renderModel.GetAnimationGroups(); foreach (var animGroupPath in animGroupPaths) { var animGroup = FileExtensions.LoadFileByAnyMeansNecessary(animGroupPath + "_c", fileName, currentPackage); modelmv.AddAnimations(AnimationGroupLoader.LoadAnimationGroup(animGroup, fileName)); } //Initialise OpenGL var modelglControl = modelmv.CreateGL(); modelmeshTab.Controls.Add(modelglControl); resTabs.TabPages.Add(modelmeshTab); break; case ResourceType.Mesh: if (!resource.Blocks.ContainsKey(BlockType.VBIB)) { Console.WriteLine("Old style model, no VBIB!"); break; } var meshTab = new TabPage("MESH"); var mv = new Renderer(mainTabs, fileName, currentPackage, RenderSubject.Model); Invoke(new ExportDel(AddToExport), $"Export {Path.GetFileName(fileName)} as OBJ", fileName, new ExportData { Resource = resource, Renderer = mv }); mv.AddMeshObject(new MeshObject { Resource = resource }); var glControl = mv.CreateGL(); meshTab.Controls.Add(glControl); resTabs.TabPages.Add(meshTab); break; } foreach (var block in resource.Blocks) { if (block.Key == BlockType.RERL) { var externalRefsTab = new TabPage("External Refs"); var externalRefs = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ResourceExtRefList.ResourceReferenceInfo>(resource.ExternalReferences.ResourceRefInfoList), null), }; externalRefsTab.Controls.Add(externalRefs); resTabs.TabPages.Add(externalRefsTab); continue; } if (block.Key == BlockType.NTRO) { if (((ResourceIntrospectionManifest)block.Value).ReferencedStructs.Count > 0) { var externalRefsTab = new TabPage("Introspection Manifest: Structs"); var externalRefs = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ResourceIntrospectionManifest.ResourceDiskStruct>(((ResourceIntrospectionManifest)block.Value).ReferencedStructs), null), }; externalRefsTab.Controls.Add(externalRefs); resTabs.TabPages.Add(externalRefsTab); } if (((ResourceIntrospectionManifest)block.Value).ReferencedEnums.Count > 0) { var externalRefsTab = new TabPage("Introspection Manifest: Enums"); var externalRefs2 = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AutoSize = true, ReadOnly = true, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, DataSource = new BindingSource(new BindingList <ResourceIntrospectionManifest.ResourceDiskEnum>(((ResourceIntrospectionManifest)block.Value).ReferencedEnums), null), }; externalRefsTab.Controls.Add(externalRefs2); resTabs.TabPages.Add(externalRefsTab); } //continue; } var tab2 = new TabPage(block.Key.ToString()); try { var control = new TextBox(); control.Font = new Font(FontFamily.GenericMonospace, control.Font.Size); if (block.Key == BlockType.DATA) { switch (resource.ResourceType) { case ResourceType.Particle: case ResourceType.Mesh: //Wrap it around a KV3File object to get the header. control.Text = NormalizeLineEndings(((BinaryKV3)block.Value).GetKV3File().ToString()); break; default: control.Text = NormalizeLineEndings(block.Value.ToString()); break; } } else { control.Text = NormalizeLineEndings(block.Value.ToString()); } control.Dock = DockStyle.Fill; control.Multiline = true; control.ReadOnly = true; control.ScrollBars = ScrollBars.Both; tab2.Controls.Add(control); } catch (Exception e) { Console.WriteLine(e); var bv = new ByteViewer(); bv.Dock = DockStyle.Fill; tab2.Controls.Add(bv); Invoke((MethodInvoker)(() => { resource.Reader.BaseStream.Position = block.Value.Offset; bv.SetBytes(resource.Reader.ReadBytes((int)block.Value.Size)); })); } resTabs.TabPages.Add(tab2); } tab.Controls.Add(resTabs); } else { var resTabs = new TabControl { Dock = DockStyle.Fill, }; tab.Controls.Add(resTabs); var bvTab = new TabPage("Hex"); var bv = new ByteViewer { Dock = DockStyle.Fill, }; bvTab.Controls.Add(bv); resTabs.TabPages.Add(bvTab); if (input != null && !input.Contains <byte>(0x00)) { var textTab = new TabPage("Text"); var text = new TextBox { Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical, Multiline = true, ReadOnly = true, Text = System.Text.Encoding.UTF8.GetString(input), }; textTab.Controls.Add(text); resTabs.TabPages.Add(textTab); resTabs.SelectedTab = textTab; } Invoke((MethodInvoker)(() => { if (input != null) { bv.SetBytes(input); } else { bv.SetFile(fileName); } })); } return(tab); }
public void AddLibrary(CompiledShader library, params ShaderExport[] exports) => AddLibrary(library, exports.AsMemory());
public void OnProcessShader(Shader shader, ShaderSnippetData snippet, IList <ShaderCompilerData> data) { int newVariantsForThisShader = 0; //The real variant count newVariantsForThisShader += data.Count; //Go through all the variants for (int i = 0; i < data.Count; ++i) { ShaderKeyword[] sk = data[i].shaderKeywordSet.GetShaderKeywords(); //The default variant if (sk.Length == 0) { CompiledShaderVariant scv_default = new CompiledShaderVariant(); //scv.id = id; scv_default.shaderName = shader.name; scv_default.passName = "" + snippet.passName; scv_default.passType = "" + snippet.passType.ToString(); scv_default.shaderType = "" + snippet.shaderType.ToString(); scv_default.graphicsTier = "--"; scv_default.shaderCompilerPlatform = "--"; scv_default.shaderKeywordName = "No Keyword / All Off"; scv_default.shaderKeywordType = "--"; scv_default.shaderKeywordIndex = "-1"; scv_default.isShaderKeywordValid = "--"; scv_default.isShaderKeywordEnabled = "--"; SVL.variantlist.Add(scv_default); SVL.compiledTotalCount++; } for (int k = 0; k < sk.Length; ++k) { CompiledShaderVariant scv = new CompiledShaderVariant(); //scv.id = id; scv.shaderName = shader.name; scv.passName = "" + snippet.passName; scv.passType = "" + snippet.passType.ToString(); scv.shaderType = "" + snippet.shaderType.ToString(); scv.graphicsTier = "" + data[i].graphicsTier; scv.shaderCompilerPlatform = "" + data[i].shaderCompilerPlatform; //scv.shaderRequirements = ""+data[i].shaderRequirements; //scv.platformKeywordName = ""+data[i].platformKeywordSet.ToString(); //scv.isplatformKeywordEnabled = ""+data[i].platformKeywordSet.IsEnabled(BuiltinShaderDefine.SHADER_API_DESKTOP); bool isLocal = ShaderKeyword.IsKeywordLocal(sk[k]); scv.shaderKeywordName = (isLocal? "[Local] " : "[Global] ") + ShaderKeyword.GetKeywordName(shader, sk[k]); //sk[k].GetKeywordName(); scv.shaderKeywordType = "" + ShaderKeyword.GetKeywordType(shader, sk[k]); //""+sk[k].GetKeywordType().ToString(); scv.shaderKeywordIndex = "" + sk[k].index; scv.isShaderKeywordValid = "" + sk[k].IsValid(); scv.isShaderKeywordEnabled = "" + data[i].shaderKeywordSet.IsEnabled(sk[k]); SVL.variantlist.Add(scv); SVL.compiledTotalCount++; //Just to verify API is correct string globalShaderKeywordName = ShaderKeyword.GetGlobalKeywordName(sk[k]); if (!isLocal && globalShaderKeywordName != ShaderKeyword.GetKeywordName(shader, sk[k])) { Debug.LogError("Bug. ShaderKeyword.GetGlobalKeywordName() and ShaderKeyword.GetKeywordName() is wrong"); } ShaderKeywordType globalShaderKeywordType = ShaderKeyword.GetGlobalKeywordType(sk[k]); if (!isLocal && globalShaderKeywordType != ShaderKeyword.GetKeywordType(shader, sk[k])) { Debug.LogError("Bug. ShaderKeyword.GetGlobalKeywordType() and ShaderKeyword.GetKeywordType() is wrong"); } } } //Add to shader list int compiledShaderId = SVL.shaderlist.FindIndex(o => o.name == shader.name); if (compiledShaderId == -1) { CompiledShader newCompiledShader = new CompiledShader(); newCompiledShader.name = shader.name; newCompiledShader.guiEnabled = false; newCompiledShader.noOfVariantsForThisShader = 0; SVL.shaderlist.Add(newCompiledShader); compiledShaderId = SVL.shaderlist.Count - 1; } //Add variant count to shader CompiledShader compiledShader = SVL.shaderlist[compiledShaderId]; compiledShader.noOfVariantsForThisShader += newVariantsForThisShader; SVL.shaderlist[compiledShaderId] = compiledShader; //Add to total count SVL.variantTotalCount += newVariantsForThisShader; }
public void AddLibrary(CompiledShader library, ReadOnlyMemory <ShaderExport> exports) { _libraries.Add((library, exports)); _totalNumExports += exports.Length; _totalNumSubObjects++; }