forked from 0xC0000054/pdn-ddsfiletype-plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DdsFile.cs
291 lines (244 loc) · 10.4 KB
/
DdsFile.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
////////////////////////////////////////////////////////////////////////
//
// This file is part of pdn-ddsfiletype-plus, a DDS FileType plugin
// for Paint.NET that adds support for the DX10 and later formats.
//
// Copyright (c) 2017, 2018 Nicholas Hayes
//
// This file is licensed under the MIT License.
// See LICENSE.txt for complete licensing and attribution information.
//
////////////////////////////////////////////////////////////////////////
using PaintDotNet;
using PaintDotNet.IO;
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace DdsFileTypePlus
{
static class DdsFile
{
[StructLayout(LayoutKind.Sequential)]
private struct DDSLoadInfo
{
public int width;
public int height;
public int stride;
public IntPtr scan0;
}
[StructLayout(LayoutKind.Sequential)]
private struct DDSSaveInfo
{
public int width;
public int height;
public int stride;
public DdsFileFormat format;
public DdsErrorMetric errorMetric;
public BC7CompressionMode compressionMode;
[MarshalAs(UnmanagedType.U1)]
public bool generateMipmaps;
public MipMapSampling mipmapSampling;
public IntPtr scan0;
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void DdsWriteImageCallback(IntPtr image, UIntPtr imageSize);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void DdsProgressCallback(UIntPtr done, UIntPtr total);
private static class DdsIO_x86
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("DdsFileTypePlusIO_x86.dll", CallingConvention = CallingConvention.StdCall)]
internal static unsafe extern int Load([In] byte* input, [In] UIntPtr inputSize, [In, Out] ref DDSLoadInfo info);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("DdsFileTypePlusIO_x86.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern void FreeLoadInfo([In, Out] ref DDSLoadInfo info);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("DdsFileTypePlusIO_x86.dll", CallingConvention = CallingConvention.StdCall)]
internal static unsafe extern int Save(
[In] ref DDSSaveInfo input,
[In, MarshalAs(UnmanagedType.FunctionPtr)] DdsWriteImageCallback writeImageCallback,
[In, MarshalAs(UnmanagedType.FunctionPtr)] DdsProgressCallback progressCallback);
}
private static class DdsIO_x64
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("DdsFileTypePlusIO_x64.dll", CallingConvention = CallingConvention.StdCall)]
internal static unsafe extern int Load([In] byte* input, [In] UIntPtr inputSize, [In, Out] ref DDSLoadInfo info);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("DdsFileTypePlusIO_x64.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern void FreeLoadInfo([In, Out] ref DDSLoadInfo info);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("DdsFileTypePlusIO_x64.dll", CallingConvention = CallingConvention.StdCall)]
internal static unsafe extern int Save(
[In] ref DDSSaveInfo input,
[In, MarshalAs(UnmanagedType.FunctionPtr)] DdsWriteImageCallback writeImageCallback,
[In, MarshalAs(UnmanagedType.FunctionPtr)] DdsProgressCallback progressCallback);
}
private static class HResult
{
public const int NotSupported = unchecked((int)0x80070032); // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)
public const int InvalidData = unchecked((int)0x8007000D); // HRESULT_FROM_WIN32(ERROR_INVALID_DATA)
}
private static bool FAILED(int hr)
{
return hr < 0;
}
public static unsafe Document Load(Stream input)
{
DDSLoadInfo info = new DDSLoadInfo();
LoadDdsFile(input, ref info);
Document doc = null;
try
{
doc = new Document(info.width, info.height);
BitmapLayer layer = Layer.CreateBackgroundLayer(info.width, info.height);
Surface surface = layer.Surface;
for (int y = 0; y < surface.Height; y++)
{
byte* src = (byte*)info.scan0 + (y * info.stride);
ColorBgra* dst = surface.GetRowAddressUnchecked(y);
for (int x = 0; x < surface.Width; x++)
{
dst->R = src[0];
dst->G = src[1];
dst->B = src[2];
dst->A = src[3];
src += 4;
dst++;
}
}
doc.Layers.Add(layer);
}
finally
{
FreeLoadInfo(ref info);
}
return doc;
}
public static unsafe void Save(
Document input,
Stream output,
DdsFileFormat format,
DdsErrorMetric errorMetric,
BC7CompressionMode compressionMode,
bool generateMipmaps,
MipMapSampling sampling,
Surface scratchSurface,
ProgressEventHandler progressCallback)
{
using (RenderArgs args = new RenderArgs(scratchSurface))
{
input.Render(args, true);
}
DdsWriteImageCallback ddsWriteImage = delegate (IntPtr image, UIntPtr imageSize)
{
ulong size = imageSize.ToUInt64();
if (image != IntPtr.Zero && size > 0)
{
const int MaxBufferSize = 65536;
ulong streamBufferSize = Math.Min(MaxBufferSize, size);
byte[] streamBuffer = new byte[streamBufferSize];
output.SetLength(checked((long)size));
ulong offset = 0;
ulong remaining = size;
fixed (byte* destPtr = streamBuffer)
{
byte* srcPtr = (byte*)image.ToPointer();
while (remaining > 0)
{
ulong copySize = Math.Min(MaxBufferSize, remaining);
Buffer.MemoryCopy(srcPtr + offset, destPtr, streamBufferSize, copySize);
output.Write(streamBuffer, 0, (int)copySize);
offset += copySize;
remaining -= copySize;
}
}
}
};
DdsProgressCallback ddsProgress = delegate (UIntPtr done, UIntPtr total)
{
double progress = (double)done.ToUInt64() / (double)total.ToUInt64();
progressCallback(null, new ProgressEventArgs(progress * 100.0, true));
};
SaveDdsFile(scratchSurface, format, errorMetric, compressionMode, generateMipmaps, sampling, ddsWriteImage, ddsProgress);
GC.KeepAlive(ddsWriteImage);
}
private static unsafe void LoadDdsFile(Stream stream, ref DDSLoadInfo info)
{
byte[] buffer = new byte[stream.Length];
stream.ProperRead(buffer, 0, buffer.Length);
int hr;
fixed (byte* pBytes = buffer)
{
if (IntPtr.Size == 8)
{
hr = DdsIO_x64.Load(pBytes, new UIntPtr((ulong)buffer.Length), ref info);
}
else
{
hr = DdsIO_x86.Load(pBytes, new UIntPtr((ulong)buffer.Length), ref info);
}
}
if (FAILED(hr))
{
switch (hr)
{
case HResult.InvalidData:
throw new FormatException("The DDS file is invalid.");
case HResult.NotSupported:
throw new FormatException("The file is not a supported DDS format.");
default:
Marshal.ThrowExceptionForHR(hr);
break;
}
}
}
private static void FreeLoadInfo(ref DDSLoadInfo info)
{
if (IntPtr.Size == 8)
{
DdsIO_x64.FreeLoadInfo(ref info);
}
else
{
DdsIO_x86.FreeLoadInfo(ref info);
}
}
private static unsafe void SaveDdsFile(
Surface surface,
DdsFileFormat format,
DdsErrorMetric errorMetric,
BC7CompressionMode compressionMode,
bool generateMipmaps,
MipMapSampling mipMapSampling,
DdsWriteImageCallback writeImageCallback,
DdsProgressCallback progressCallback)
{
DDSSaveInfo info = new DDSSaveInfo
{
width = surface.Width,
height = surface.Height,
stride = surface.Stride,
format = format,
errorMetric = errorMetric,
compressionMode = compressionMode,
generateMipmaps = generateMipmaps,
mipmapSampling = mipMapSampling,
scan0 = surface.Scan0.Pointer
};
int hr;
if (IntPtr.Size == 8)
{
hr = DdsIO_x64.Save(ref info, writeImageCallback, progressCallback);
}
else
{
hr = DdsIO_x86.Save(ref info, writeImageCallback, progressCallback);
}
if (FAILED(hr))
{
Marshal.ThrowExceptionForHR(hr);
}
}
}
}