forked from OpenEmu/PPSSPP-Core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PPSSPPGameCore.mm
359 lines (280 loc) · 11.8 KB
/
PPSSPPGameCore.mm
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
/*
Copyright (c) 2013, OpenEmu Team
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the OpenEmu Team nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY OpenEmu Team ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL OpenEmu Team BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "PPSSPPGameCore.h"
#import <OpenEmuBase/OERingBuffer.h>
#import <OpenGL/gl.h>
#include "gfx/OpenEmuGLContext.h"
#include "base/NativeApp.h"
#include "base/timeutil.h"
#include "Core/Core.h"
#include "Core/Config.h"
#include "Core/ConfigValues.h"
#include "Core/CoreParameter.h"
#include "Core/CoreTiming.h"
#include "Core/HLE/sceCtrl.h"
#include "Core/Host.h"
#include "Core/SaveState.h"
#include "Core/System.h"
#include "Common/GraphicsContext.h"
#include "Common/LogManager.h"
#include "thin3d/thin3d_create.h"
#include "thin3d/GLRenderManager.h"
#include "thin3d/DataFormatGL.h"
#define AUDIO_FREQ 44100
#define AUDIO_CHANNELS 2
#define AUDIO_SAMPLESIZE sizeof(int16_t)
#define GRAPHIC_ORIG_W 480
#define GRAPHIC_ORIG_H 272
#define GRAPHIC_DOUBLE_W 960
#define GRAPHIC_DOUBLE_H 544
#define GRAPHIC_TRIPLE_W 1440
#define GRAPHIC_TRIPLE_H 816
#define GRAPHIC_FULLHD_W 1920
#define GRAPHIC_FULLHD_H 1088
namespace SaveState {
struct SaveStart {
void DoState(PointerWrap &p);
};
} // namespace SaveState
namespace OpenEmuCoreThread {
enum class EmuThreadState {
DISABLED,
START_REQUESTED,
RUNNING,
PAUSE_REQUESTED,
PAUSED,
QUIT_REQUESTED,
STOPPED,
};
} //namespace OpenEmuThreadCore
void NativeSetThreadState(OpenEmuCoreThread::EmuThreadState threadState);
@interface PPSSPPGameCore () <OEPSPSystemResponderClient, OEAudioBuffer>
{
CoreParameter _coreParam;
bool _isInitialized;
bool _shouldReset;
OpenEmuGLContext *OEgraphicsContext;
}
@end
PPSSPPGameCore *_current = 0;
@implementation PPSSPPGameCore
- (instancetype)init
{
(self = [super init]);
_current = self;
return self;
}
# pragma mark - Execution
- (BOOL)loadFileAtPath:(NSString *)path error:(NSError **)error
{
NSURL *romURL = [NSURL fileURLWithPath:path];
NSURL *resourceURL = self.owner.bundle.resourceURL;
NSURL *supportDirectoryURL = [NSURL fileURLWithPath:self.supportDirectoryPath isDirectory:YES];
// Copy over font files if needed
NSFileManager *fileManager = NSFileManager.defaultManager;
NSURL *fontSourceDirectory = [resourceURL URLByAppendingPathComponent:@"flash0/font" isDirectory:YES];
NSURL *fontDestinationDirectory = [supportDirectoryURL URLByAppendingPathComponent:@"font" isDirectory:YES];
NSArray *fontFiles = [fileManager contentsOfDirectoryAtURL:fontSourceDirectory includingPropertiesForKeys:@[NSURLNameKey] options:0 error:nil];
[fileManager createDirectoryAtURL:fontDestinationDirectory withIntermediateDirectories:YES attributes:nil error:nil];
for(NSURL *fontURL in fontFiles)
{
NSURL *destinationFontURL = [fontDestinationDirectory URLByAppendingPathComponent:fontURL.lastPathComponent];
[fileManager copyItemAtURL:fontURL toURL:destinationFontURL error:nil];
}
LogManager::Init();
g_Config.Load("");
// Force a trailing forward slash that PPSSPP requires
NSString *directoryString = [supportDirectoryURL.path stringByAppendingString:@"/"];
//NSURL *directoryURL3 = [supportDirectoryURL URLByAppendingPathComponent:@"/" isDirectory:YES];
g_Config.currentDirectory = directoryString.fileSystemRepresentation;
g_Config.externalDirectory = directoryString.fileSystemRepresentation;
g_Config.memStickDirectory = directoryString.fileSystemRepresentation;
g_Config.flash0Directory = directoryString.fileSystemRepresentation;
g_Config.internalDataDirectory = directoryString.fileSystemRepresentation;
g_Config.iGPUBackend = (int)GPUBackend::OPENGL;
g_Config.bHideStateWarnings = false;
_coreParam.cpuCore = CPUCore::JIT;
_coreParam.gpuCore = GPUCORE_GLES;
_coreParam.enableSound = true;
_coreParam.fileToStart = romURL.fileSystemRepresentation;
_coreParam.mountIso = "";
_coreParam.startBreak = false;
_coreParam.printfEmuLog = false;
_coreParam.headLess = false;
_coreParam.renderWidth = GRAPHIC_FULLHD_W;
_coreParam.renderHeight = GRAPHIC_FULLHD_H;
_coreParam.pixelWidth = GRAPHIC_FULLHD_W;
_coreParam.pixelHeight = GRAPHIC_FULLHD_H;
coreState = CORE_POWERUP;
return true;
}
- (void)stopEmulation
{
NativeSetThreadState(OpenEmuCoreThread::EmuThreadState::PAUSE_REQUESTED);
PSP_Shutdown();
NativeShutdownGraphics();
NativeShutdown();
[super stopEmulation];
}
- (void)resetEmulation
{
_shouldReset = YES;
}
- (void)executeFrame
{
if(!_isInitialized)
{
// This is where PPSSPP will look for ppge_atlas.zim, requires trailing forward slash
NSString *resourcePath = [self.owner.bundle.resourcePath stringByAppendingString:@"/"];
OEgraphicsContext = OpenEmuGLContext::CreateGraphicsContext();
NativeInit(0, nil, nil, resourcePath.fileSystemRepresentation, nil);
OEgraphicsContext->InitFromRenderThread(nullptr);
_coreParam.graphicsContext = OEgraphicsContext;
_coreParam.thin3d = OEgraphicsContext ? OEgraphicsContext->GetDrawContext() : nullptr;
NativeInitGraphics(OEgraphicsContext);
}
if(_shouldReset)
{
NativeSetThreadState(OpenEmuCoreThread::EmuThreadState::PAUSE_REQUESTED);
PSP_Shutdown();
}
if(!_isInitialized || _shouldReset)
{
_isInitialized = YES;
_shouldReset = NO;
std::string error_string;
if(!PSP_Init(_coreParam, &error_string))
NSLog(@"[PPSSPP] ERROR: %s", error_string.c_str());
host->BootDone();
host->UpdateDisassembly();
//Start the Emulator Thread
NativeSetThreadState(OpenEmuCoreThread::EmuThreadState::START_REQUESTED);
} else {
//If Fast forward rate is detected, unthrottle the rndering
PSP_CoreParameter().unthrottle = (self.rate > 1) ? true : false;
//Let PPSSPP Core run a loop and return
UpdateRunLoop();
}
}
# pragma mark - Video
- (OEGameCoreRendering)gameCoreRendering
{
return OEGameCoreRenderingOpenGL2Video;
}
- (OEIntSize)bufferSize
{
return OEIntSizeMake(GRAPHIC_FULLHD_W, GRAPHIC_FULLHD_H);
}
- (OEIntSize)aspectSize
{
return OEIntSizeMake(16, 9);
}
- (NSTimeInterval)frameInterval
{
return 59.94;
}
# pragma mark - Audio
- (NSUInteger)channelCount
{
return AUDIO_CHANNELS;
}
- (double)audioSampleRate
{
return AUDIO_FREQ;
}
- (id<OEAudioBuffer>)audioBufferAtIndex:(NSUInteger)index
{
return self;
}
- (NSUInteger)read:(void *)buffer maxLength:(NSUInteger)len
{
NativeMix((short *)buffer, (int)(len / (AUDIO_CHANNELS * sizeof(uint16_t))));
return len;
}
- (NSUInteger)write:(const void *)buffer maxLength:(NSUInteger)length
{
return 0;
}
- (NSUInteger)length
{
return AUDIO_FREQ / 15;
}
# pragma mark - Save States
static void _OESaveStateCallback(SaveState::Status status, std::string message, void *cbUserData)
{
void (^block)(BOOL, NSError *) = (__bridge_transfer void(^)(BOOL, NSError *))cbUserData;
[_current endPausedExecution];
block((status != SaveState::Status::FAILURE), nil);
}
static void _OELoadStateCallback(SaveState::Status status, std::string message, void *cbUserData)
{
void (^block)(BOOL, NSError *) = (__bridge_transfer void(^)(BOOL, NSError *))cbUserData;
//Unpause the EmuThread by requesting it to start again
NativeSetThreadState(OpenEmuCoreThread::EmuThreadState::START_REQUESTED);
NSError *error = nil;
if(status == SaveState::Status::WARNING) {
error = [NSError errorWithDomain:OEGameCoreErrorDomain code:OEGameCoreCouldNotLoadStateError userInfo:@{
NSLocalizedDescriptionKey : NSLocalizedString(@"PPSSPP Save State Warning", @"PPSSPP Save State Warning description."),
NSLocalizedRecoverySuggestionErrorKey : [NSString stringWithFormat:NSLocalizedString(@"This save state was created from a previous version of PPSSPP, or simulates over 4 hours of time played.\n\nSave states preserve bugs from old PPSSPP versions and states from long sessions can also expose bugs rarely seen on a real PSP.\n\nIt is recommended to \"clean load\" for less bugs:\n\n1. Save in-game (memory stick, not save state), then stop emulation.\n2. Go to OpenEmu > Preferences > Library, click \"Reset warnings\".\n3. Reopen your game and click \"No\" when prompted to \"Continue where you left off\".", @"PPSSPP Save State Warning.")]
}];
} else if(status == SaveState::Status::FAILURE) {
error = [NSError errorWithDomain:OEGameCoreErrorDomain code:OEGameCoreCouldNotLoadStateError userInfo:@{
NSLocalizedDescriptionKey : NSLocalizedString(@"The Save State failed to Load", @"PPSSPP Save State Failure description."),
NSLocalizedRecoverySuggestionErrorKey : [NSString stringWithFormat:NSLocalizedString(@"Could not load Save State.", @"PPSSPP Save State Failure.")]
}];
}
block((status == SaveState::Status::SUCCESS), error);
}
- (void)saveStateToFileAtPath:(NSString *)fileName completionHandler:(void (^)(BOOL, NSError *))block
{
[self beginPausedExecution];
SaveState::Save(fileName.fileSystemRepresentation, _OESaveStateCallback, (__bridge_retained void *)[block copy]);
}
- (void)loadStateFromFileAtPath:(NSString *)fileName completionHandler:(void (^)(BOOL, NSError *))block
{
SaveState::Load(fileName.fileSystemRepresentation, _OELoadStateCallback, (__bridge_retained void *)[block copy]);
if(_isInitialized){
//We need to pause our EmuThread so we don't try to process the save state in the middle of a Frame Render
NativeSetThreadState(OpenEmuCoreThread::EmuThreadState::PAUSE_REQUESTED);
SaveState::Process();
}
}
# pragma mark - Input
const int buttonMap[] = { CTRL_UP, CTRL_DOWN, CTRL_LEFT, CTRL_RIGHT, 0, 0, 0, 0, CTRL_TRIANGLE, CTRL_CIRCLE, CTRL_CROSS, CTRL_SQUARE, CTRL_LTRIGGER, CTRL_RTRIGGER, CTRL_START, CTRL_SELECT };
- (oneway void)didMovePSPJoystickDirection:(OEPSPButton)button withValue:(CGFloat)value forPlayer:(NSUInteger)player
{
if(button == OEPSPAnalogUp || button == OEPSPAnalogDown)
__CtrlSetAnalogY(button == OEPSPAnalogUp ? value : -value);
else
__CtrlSetAnalogX(button == OEPSPAnalogRight ? value : -value);
}
- (oneway void)didPushPSPButton:(OEPSPButton)button forPlayer:(NSUInteger)player
{
__CtrlButtonDown(buttonMap[button]);
}
- (oneway void)didReleasePSPButton:(OEPSPButton)button forPlayer:(NSUInteger)player
{
__CtrlButtonUp(buttonMap[button]);
}
@end