forked from 0xC0000054/pdn-ddsfiletype-plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DdsFile.cs
383 lines (315 loc) · 12.7 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
////////////////////////////////////////////////////////////////////////
//
// 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 System;
using System.IO;
using System.Runtime.InteropServices;
namespace DdsFileTypePlus
{
internal 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 DdsProgressCallback(UIntPtr done, UIntPtr total);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReadDelegate(IntPtr buffer, uint count);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint WriteDelegate(IntPtr buffer, uint count);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate long SeekDelegate(long offset, int origin);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate long GetSizeDelegate();
[StructLayout(LayoutKind.Sequential)]
private sealed class IOCallbacks
{
[MarshalAs(UnmanagedType.FunctionPtr)]
public ReadDelegate Read;
[MarshalAs(UnmanagedType.FunctionPtr)]
public WriteDelegate Write;
[MarshalAs(UnmanagedType.FunctionPtr)]
public SeekDelegate Seek;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetSizeDelegate GetSize;
}
private static class DdsIO_x86
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("DdsFileTypePlusIO_x86.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern int Load([In] IOCallbacks callbacks, [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 extern int Save(
[In] ref DDSSaveInfo input,
[In] IOCallbacks callbacks,
[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 extern int Load([In] IOCallbacks callbacks, [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 extern int Save(
[In] ref DDSSaveInfo input,
[In] IOCallbacks callbacks,
[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 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);
}
DdsProgressCallback ddsProgress = null;
if (progressCallback != null)
{
ddsProgress = (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, output, ddsProgress);
}
private static void LoadDdsFile(Stream stream, ref DDSLoadInfo info)
{
StreamIOCallbacks streamIO = new StreamIOCallbacks(stream);
IOCallbacks callbacks = new IOCallbacks
{
Read = streamIO.Read,
Write = streamIO.Write,
Seek = streamIO.Seek,
GetSize = streamIO.GetSize
};
int hr;
if (IntPtr.Size == 8)
{
hr = DdsIO_x64.Load(callbacks, ref info);
}
else
{
hr = DdsIO_x86.Load(callbacks, ref info);
}
GC.KeepAlive(streamIO);
GC.KeepAlive(callbacks);
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 void SaveDdsFile(
Surface surface,
DdsFileFormat format,
DdsErrorMetric errorMetric,
BC7CompressionMode compressionMode,
bool generateMipmaps,
MipMapSampling mipMapSampling,
Stream output,
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
};
StreamIOCallbacks streamIO = new StreamIOCallbacks(output);
IOCallbacks callbacks = new IOCallbacks
{
Read = streamIO.Read,
Write = streamIO.Write,
Seek = streamIO.Seek,
GetSize = streamIO.GetSize
};
int hr;
if (IntPtr.Size == 8)
{
hr = DdsIO_x64.Save(ref info, callbacks, progressCallback);
}
else
{
hr = DdsIO_x86.Save(ref info, callbacks, progressCallback);
}
GC.KeepAlive(streamIO);
GC.KeepAlive(callbacks);
GC.KeepAlive(progressCallback);
if (FAILED(hr))
{
Marshal.ThrowExceptionForHR(hr);
}
}
private sealed class StreamIOCallbacks
{
private readonly Stream stream;
// 81920 is the largest multiple of 4096 that is below the large object heap threshold.
private const int MaxBufferSize = 81920;
public StreamIOCallbacks(Stream stream)
{
this.stream = stream;
}
public uint Read(IntPtr buffer, uint count)
{
if (count == 0)
{
return 0;
}
int bufferSize = (int)Math.Min(MaxBufferSize, count);
byte[] bytes = new byte[bufferSize];
long totalBytesRead = 0;
long remaining = count;
do
{
int bytesRead = stream.Read(bytes, 0, (int)Math.Min(MaxBufferSize, remaining));
if (bytesRead == 0)
{
break;
}
Marshal.Copy(bytes, 0, new IntPtr(buffer.ToInt64() + totalBytesRead), bytesRead);
totalBytesRead += bytesRead;
remaining -= bytesRead;
} while (remaining > 0);
return (uint)totalBytesRead;
}
public uint Write(IntPtr buffer, uint count)
{
if (count > 0)
{
int bufferSize = (int)Math.Min(MaxBufferSize, count);
byte[] bytes = new byte[bufferSize];
long offset = 0;
long remaining = count;
do
{
int copySize = (int)Math.Min(MaxBufferSize, remaining);
Marshal.Copy(new IntPtr(buffer.ToInt64() + offset), bytes, 0, copySize);
stream.Write(bytes, 0, copySize);
offset += copySize;
remaining -= copySize;
} while (remaining > 0);
}
return count;
}
public long Seek(long offset, int origin)
{
return stream.Seek(offset, (SeekOrigin)origin);
}
public long GetSize()
{
return stream.Length;
}
}
}
}