I have bmp (or jpg) file.
I need to convert it to dds file programmatically (I can use C++, C# with or without .NET; I can try any other language if I would see some clues in it)
I know that there are software that do this, but I need it to integrate into my programm, this should be a part of a longer manipulations on my application.
BTW, my question is:
1) Are there any opensource program that does this, so I can look into the code of it?
2) Are there any tutorials found somewhere in web that can help me to write this code?
I could not found any helpfull information.
Thank you!
I'm sure there are standalone converters you can use calling them via command line, if you need a programmatically solution the easiest way I may think about is to use built-in XNA classes to do the job. Because XNA handles all these file formats you can open source .bmp and then save it back to .dds (using the Texture class):
public static void ConvertToDds(
GraphicsDevice graphicsDevice, string sourcePath, string targetPath)
{
Texture.FromFile(graphicsDevice, sourcePath)
.Save(targetPath, ImageFileFormat.Dds);
}
Things changed with XNA 4.0 (these methods have been removed), try the DDSLib to write and Texture2D to read:
public static void ConvertToDds(
GraphicsDevice graphicsDevice, string sourcePath, string targetPath)
{
using (var stream = File.Open(sourcePath))
{
var texture = Texture2D.FromStream(graphicsDevice, stream);
DDSLib.DDSToFile(targetPath, true, texture, false);
}
}
See linked pages for more details and examples. By the way you can't have C# without .NET!
Related
I'm actually tryin to place SharpDX Window in Winforms Window like in the following video:
http://www.youtube.com/watch?v=g-JupOxwB-k
In SharpDX this method doesn't work.Can anyone tell me how to EASILY do this ?
don't think of it as putting a sharpDX window into a winforms window.
instead think of it as how to output SharpDX to the windows handle (sorta)
the key is in the SharpDX.DXGI.SwapChain. when creating this you will need a SwapChainDescription
I like to create mine like
SwapChainDescription scd = new SwapChainDescription()
{
//set other fields
OutputHandle = yourform.Handle,
//set other fields
};
Handle
SwapChainDescription
so when you call SwapChain.Present() it will render to the form.
this is the basic way to do it with straight SharpDX and not the toolkit stuff
EDIT 04222019 LINKS DO NOT WORK --- 01052022 Link fixed
if you want to use the toolkit's GraphicsDevice you will have to set the Presenter property. in almost the same way you set the window handle in the presentation parameters.
https://github.com/sharpdx/Toolkit/tree/master/Documentation
also the toolkit has the RenderForm which plays nice with the Game class
04222019
EDIT (DirectX Example)
here is an example using straight SharpDX (No Toolkit). for complete examples you should refer to the github examples HERE
As stated above all you need to do to render to a WindowsForm window is pass the Handle to the SwapChain
visual studio 2012
add the references: (all other references are default winforms project references)
some using statements to make things easier:
namespace YourNameSpaceHere
{
using Device = SharpDX.Direct3D11.Device;
using Buffer = SharpDX.Direct3D11.Buffer;
...the rest of the application
}
the Form class: here we make the device, swap chain, render target , and render target view a variable of the Form class we are declaring
public partial class Form1 : Form //default vs2012 declaration
{
Device d; //Direct311
SwapChain sc; //DXGI
Texture2D target; //Direct3D11
RenderTargetView targetveiw;//DIrect3D11
...the rest of the form
}
Initializing the Device and SwapChain: this is what works for me on my system. if you have problems than you need to research your specific implementation and hardware. DirectX (and by extension SharpDX) has methods by which you can detect what the hardware will support.
the main code Example:
using System;
using System.ComponentModel;//needed to overide OnClosing
//I removed useless usings
using System.Windows.Forms;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX;
namespace WindowsFormsApplication2
{
using Device = SharpDX.Direct3D11.Device;
using Buffer = SharpDX.Direct3D11.Buffer;
public partial class Form1 : Form
{
Device d;
SwapChain sc;
Texture2D target;
RenderTargetView targetveiw;
public Form1()
{
InitializeComponent();
SwapChainDescription scd = new SwapChainDescription()
{
BufferCount = 1, //how many buffers are used for writing. it's recommended to have at least 2 buffers but this is an example
Flags = SwapChainFlags.None,
IsWindowed = true, //it's windowed
ModeDescription = new ModeDescription(
this.ClientSize.Width, //windows veiwable width
this.ClientSize.Height, //windows veiwable height
new Rational(60,1), //refresh rate
Format.R8G8B8A8_UNorm), //pixel format, you should resreach this for your specific implementation
OutputHandle = this.Handle, //the magic
SampleDescription = new SampleDescription(1, 0), //the first number is how many samples to take, anything above one is multisampling.
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};
Device.CreateWithSwapChain(
SharpDX.Direct3D.DriverType.Hardware,//hardware if you have a graphics card otherwise you can use software
DeviceCreationFlags.Debug, //helps debuging don't use this for release verion
scd, //the swapchain description made above
out d, out sc //our directx objects
);
target = Texture2D.FromSwapChain<Texture2D>(sc, 0);
targetveiw = new RenderTargetView(d, target);
d.ImmediateContext.OutputMerger.SetRenderTargets(targetveiw);
}
protected override void OnClosing(CancelEventArgs e)
{
//dipose of all objects
d.Dispose();
sc.Dispose();
target.Dispose();
targetveiw.Dispose();
base.OnClosing(e);
}
protected override void OnPaint(PaintEventArgs e)
{
//I am rendering here for this example
//normally I use a seperate thread to call Draw() and Present() in a loop
d.ImmediateContext.ClearRenderTargetView(targetveiw, Color.CornflowerBlue);//Color to make it look like default XNA project output.
sc.Present(0, PresentFlags.None);
base.OnPaint(e);
}
}
}
this is meant to get you started with using DirectX using ShaprDX in a managed environment, specifically C# on Windows. there is much much more you will need to get something real off the ground. and this is meant as the gateway to rendering on a Winforms window using SharpDX. I don't explain things like vertex/index buffers or rendering Textures/Sprites. because it is out of scope for the question.
Is there any way to conditionally import libraries / code based on environment flags or target platforms in Dart? I'm trying to switch out between dart:io's ZLibDecoder / ZLibEncoder classes and zlib.js based on the target platform.
There is an article that describes how to create a unified interface, but I'm unable to visualize that technique not creating duplicate code and redundant tests to test that duplicate code. game_loop employs this technique, but uses separate classes (GameLoopHtml and GameLoopIsolate) that don't seem to share anything.
My code looks a bit like this:
class Parser {
Layer parse(String data) {
List<int> rawBytes = /* ... */;
/* stuff you don't care about */
return new Layer(_inflateBytes(rawBytes));
}
String _inflateBytes(List<int> bytes) {
// Uses ZLibEncoder on dartvm, zlib.js in browser
}
}
I'd like to avoid duplicating code by having two separate classes -- ParserHtml and ParserServer -- that implement everything identically except for _inflateBytes.
EDIT: concrete example here: https://github.com/radicaled/citadel/blob/master/lib/tilemap/parser.dart. It's a TMX (Tile Map XML) parser.
You could use mirrors (reflection) to solve this problem. The pub package path is using reflection to access dart:io on the standalone VM or dart:html in the browser.
The source is located here. The good thing is, that they use #MirrorsUsed, so only the required classes are included for the mirrors api. In my opinion the code is documented very good, it should be easy to adopt the solution for your code.
Start at the getters _io and _html (stating at line 72), they show that you can load a library without that they are available on your type of the VM. Loading just returns false if the library it isn't available.
/// If we're running in the server-side Dart VM, this will return a
/// [LibraryMirror] that gives access to the `dart:io` library.
///
/// If `dart:io` is not available, this returns null.
LibraryMirror get _io => currentMirrorSystem().libraries[Uri.parse('dart:io')];
// TODO(nweiz): when issue 6490 or 6943 are fixed, make this work under dart2js.
/// If we're running in Dartium, this will return a [LibraryMirror] that gives
/// access to the `dart:html` library.
///
/// If `dart:html` is not available, this returns null.
LibraryMirror get _html =>
currentMirrorSystem().libraries[Uri.parse('dart:html')];
Later you can use mirrors to invoke methods or getters. See the getter current (starting at line 86) for an example implementation.
/// Gets the path to the current working directory.
///
/// In the browser, this means the current URL. When using dart2js, this
/// currently returns `.` due to technical constraints. In the future, it will
/// return the current URL.
String get current {
if (_io != null) {
return _io.classes[#Directory].getField(#current).reflectee.path;
} else if (_html != null) {
return _html.getField(#window).reflectee.location.href;
} else {
return '.';
}
}
As you see in the comments, this only works in the Dart VM at the moment. After issue 6490 is solved, it should work in Dart2Js, too. This may means that this solution isn't applicable for you at the moment, but would be a solution later.
The issue 6943 could also be helpful, but describes another solution that is not implemented yet.
Conditional imports are possible based on the presence of dart:html or dart:io, see for example the import statements of resource_loader.dart in package:resource.
I'm not yet sure how to do an import conditional on being on the Flutter platform.
I'm working on a biztalk project and use a map to create the new message.
Now i want to map a datefield to a string.
I thought i can do it on this way with an Function Script with inline C#
public string convertDateTime(DateTime param)
{
return System.Xml.XmlConvert.ToString(param,ÿyyyMMdd");
}
But this doesn't work and i receive an error. How can i do the convert in the map?
It's a Biztalk 2006 project.
Without the details of the error you are seeing it is hard to be sure but I'm quite sure that your map is failing because all the parameters within the BizTalk XSLT engine are passed as strings1.
When I try to run something like the function you provided as inline C# I get the following error:
Object of type 'System.String' cannot be converted to type 'System.DateTime'
Replace your inline C# with something like the following:
public string ConvertDateTime(string param1)
{
DateTime inputDate = DateTime.Parse(param1);
return inputDate.ToString("yyyyMMdd");
}
Note that the parameter type is now string, and you can then convert that to a DateTime and perform your string format.
As other answers have suggested, it may be better to put this helper method into an external class - that way you can get your code under test to deal with edge cases, and you also get some reuse.
1 The fact that all parameters in the BizTalk XSLT are strings can be the source of a lot of gotchas - one other common one is with math calculations. If you return numeric values from your scripting functoids BizTalk will helpfully convert them to strings to map them to the outbound schema but will not so helpfully perform some very random rounding on the resulting values. Converting the return values to strings yourself within the C# will remove this risk and give you the expected results.
If you're using the mapper, you just need a Scripting Functiod (yes, using inline C#) and you should be able to do:
public string convertDateTime(DateTime param)
{
return(param.ToString("YYYYMMdd");
}
As far as I know, you don't need to call the System.Xml namespace in anyway.
I'd suggest
public static string DateToString(DateTime dateValue)
{
return String.Format("{0:yyyyMMdd}", dateValue);
}
You could also create a external Lib which would provide more flexibility and reusability:
public static string DateToString(DateTime dateValue, string formatPicture)
{
string format = formatPicture;
if (IsNullOrEmptyString(formatPicture)
{
format = "{0:yyyyMMdd}";
}
return String.Format(format, dateValue);
}
public static string DateToString(DateTime dateValue)
{
return DateToString(dateValue, null);
}
I tend to move every function I use twice inside an inline script into an external lib. Iit will give you well tested code for all edge cases your data may provide because it's eays to create tests for these external lib functions whereas it's hard to do good testing on inline scripts in maps.
This blog will solve your problem.
http://biztalkorchestration.blogspot.in/2014/07/convert-datetime-format-to-string-in.html?view=sidebar
Regards,
AboorvaRaja
Bangalore
+918123339872
Given that maps in BizTalk are implemented as XSL stylesheets, when passing data into a msxsl scripting function, note that the data will be one of types in the Equivalent .NET Framework Class (Types) from this table here. You'll note that System.DateTime isn't on the list.
For parsing of xs:dateTimes, I've generally obtained the /text() node and then parse the parameter from System.String:
<CreateDate>
<xsl:value-of select="userCSharp:GetDateyyyyMMdd(string(s0:StatusIdChangeDate/text()))" />
</CreateDate>
And then the C# script
<msxsl:script language="C#" implements-prefix="userCSharp">
<![CDATA[
public System.String GetDateyyyyMMdd(System.String p_DateTime)
{
return System.DateTime.Parse(p_DateTime).ToString("yyyyMMdd");
}
]]>
Say I want to create a source code editor for ocaml programming language, where do I start? I am looking to create an editor for the Windows platform as a hobby project. My primary skill is in web development. I have developed windows apps long time ago. I have no clue how it is done with todays available tools. I have visual studio 2008 and C# is my language of choice.
You need to know:
OCAML Syntax, Features, Keywords, Functions etc...
C# as this is your native language I guess
You need to know what features you wanna implement
...if it's using a GUI or just from a terminal like nano/vim
how syntax highlighting works
how to open and save files
how autocompletion works
etc..
You might want to take look at some open source editors like dev-c++ or gedit
Also, as you in person are more web-devvy, you might want to start creating one which runs in a web browser. This is often easier and helps you understand the basics of creating a code editor. Later you can always write one for desktops.
If you are most comfortable in Visual Studio, then you can use the Visual Studio Shell to create your own IDE based on that foundation.
Here is a podcast that gives a good overview:
http://www.code-magazine.com/codecast/index.aspx?messageid=32b9401a-140d-4acb-95bb-6accd3a3dafc
Also, as a reference, the IronPython Studio was created using the Visual Studio 2008 Shell:
http://ironpythonstudio.codeplex.com/
Browsing that source code should give you a good starting point.
a lighter-weight alternative is to use the RichEdit control
example:
http://www.codeproject.com/Messages/3401956/NET-Richedit-Control.aspx
// http://www.codeproject.com/Messages/3401956/NET-Richedit-Control.aspx
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace RichEditor
{
public class RichTextBoxEx : RichTextBox
{
IntPtr mHandle = IntPtr.Zero;
protected override CreateParams CreateParams
{
get
{
// Prevent module being loaded multiple times.
if (this.mHandle == IntPtr.Zero)
{
// load the library to obtain an instance of the RichEdit50 class.
this.mHandle = LoadLibrary("msftedit.dll");
}
// If module loaded, reset ClassName.
if (this.mHandle != IntPtr.Zero)
{
CreateParams cParams = base.CreateParams;
// Check Unicode or ANSI system and set appropriate ClassName.
if (Marshal.SystemDefaultCharSize == 1)
{
cParams.ClassName = "RichEdit50A";
}
else
{
cParams.ClassName = "RichEdit50W";
}
return cParams;
}
else // Module wasnt loaded, return default .NET RichEdit20 CreateParams.
{
return base.CreateParams;
}
}
}
~RichTextBoxEx()
{
//Free loaded Library.
if (mHandle != IntPtr.Zero)
{
FreeLibrary(mHandle);
}
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LoadLibrary(String lpFileName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr hModule);
}
}
You could use Scintilla. It has syntax highlighting and some other features. Also, it has a .NET Version available here.
Another good tool is Alsing Syntax Box:
Powerful Syntax Highlight Windows
Forms Control for the Microsoft.NET
Platform. Written in 100% managed C#.
Supports syntax highlighting and code
folding for just about any programming
language.
With Alsing Syntax Box, you can define a syntax file (just like this one for C#) and later have a intellisense like feature.
You can start with one of them for your editor.
I found the folliwing code sample in BlackBerry Java Development, Best Practices. Could somebody explain what the below same code means? What is the this in the code sample poining to?
Avoiding StringBuffer.append (StringBuffer)
To append a String buffer to another, a BlackBerry® Java Application should use net.rim.device.api.util.StringUtilities.append( StringBuffer dst, StringBuffer src[, int offset, int length ] ).
Code sample
public synchronized StringBuffer append(Object obj) {
if (obj instanceof StringBuffer) {
StringBuffer sb = (StringBuffer)obj;
net.rim.device.api.util.StringUtilities.append( this, sb, 0, sb )
return this;
}
return append(String.valueOf(obj));
}
StringBuffer does not offer an overload for the append() method that takes another StringBuffer. This means developers are likely to use StringBuffer.append(String str) and call .toString() on the second StringBuffer. This requires the second buffer to be turned into a string, which is immutable, and then the characters from the string are appended to the first StringBuffer. Thus every character in the second buffer is touched twice, and there is the unnecessary allocation of the String just to transfer the characters to the first StringBuffer.
The efficient way of doing this would copy each character from the second buffer onto the end of the first. However, StringBuffer does not provide any easy way of doing this. Thus the recommendation is to use StringUtilities.append(StringBuffer, StringBuffer) which is able to directly read the characters from the second buffer without copying them into an intermediate collection.
This saves the runtime of the extra copying, the runtime needed to allocate a temporary String, and the memory needed to allocate a temporary string.
It means that the StringBuffer class is not implemented efficiently. Java Strings are supposed to be immutable, that's what StringBuffer is used for. However, the StringBuffer class you're using is not efficient when using StringBuffer.append() so you need to use net.rim.device.api.util.StringUtilities. That's what the code is doing, encapsulating the use of that class in a new append() method.