fix conflicts

This commit is contained in:
muddmaker
2015-03-21 18:15:41 -07:00
481 changed files with 58747 additions and 67796 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -23
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -177,28 +177,6 @@ void Matrix::shear(float kx, float ky)
this->operator *=(t);
}
// | x |
// | y |
// | 0 |
// | 1 |
// | e0 e4 e8 e12 |
// | e1 e5 e9 e13 |
// | e2 e6 e10 e14 |
// | e3 e7 e11 e15 |
void Matrix::transform(Vertex *dst, const Vertex *src, int size) const
{
for (int i = 0; i<size; i++)
{
// Store in temp variables in case src = dst
float x = (e[0]*src[i].x) + (e[4]*src[i].y) + (0) + (e[12]);
float y = (e[1]*src[i].x) + (e[5]*src[i].y) + (0) + (e[13]);
dst[i].x = x;
dst[i].y = y;
}
}
Matrix Matrix::ortho(float left, float right, float bottom, float top)
{
Matrix m;
+26 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -153,7 +153,8 @@ public:
* @param src The source vertices.
* @param size The number of vertices.
**/
void transform(Vertex *dst, const Vertex *src, int size) const;
template <typename V>
void transform(V *dst, const V *src, int size) const;
/**
* Creates a new orthographic projection matrix with depth in the range of
@@ -173,6 +174,29 @@ private:
}; // Matrix
// | x |
// | y |
// | 0 |
// | 1 |
// | e0 e4 e8 e12 |
// | e1 e5 e9 e13 |
// | e2 e6 e10 e14 |
// | e3 e7 e11 e15 |
template <typename V>
void Matrix::transform(V *dst, const V *src, int size) const
{
for (int i = 0; i < size; i++)
{
// Store in temp variables in case src = dst
float x = (e[0]*src[i].x) + (e[4]*src[i].y) + (0) + (e[12]);
float y = (e[1]*src[i].x) + (e[5]*src[i].y) + (0) + (e[13]);
dst[i].x = x;
dst[i].y = y;
}
}
} //love
#endif// LOVE_MATRIX_H
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+2 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -51,6 +51,7 @@ public:
M_SYSTEM,
M_THREAD,
M_TIMER,
M_TOUCH,
M_WINDOW,
M_MAX_ENUM
};
+53
View File
@@ -0,0 +1,53 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_OSX_H
#define LOVE_OSX_H
#include "config.h"
#ifdef LOVE_MACOSX
#include <string>
namespace love
{
namespace osx
{
/**
* Returns the filepath of the first detected love file in the Resources folder
* in the main bundle (love.app.)
* Returns an empty string if no love file is found.
**/
std::string getLoveInResources();
/**
* Checks for drop-file events. Returns the filepath if an event occurred, or
* an empty string otherwise.
**/
std::string checkDropEvents();
} // osx
} // love
#endif // LOVE_MACOSX
#endif // LOVE_OSX_H
+75
View File
@@ -0,0 +1,75 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "OSX.h"
#ifdef LOVE_MACOSX
#import <Foundation/Foundation.h>
#include <SDL2/SDL.h>
namespace love
{
namespace osx
{
std::string getLoveInResources()
{
std::string path;
@autoreleasepool
{
// Check to see if there are any .love files in Resources.
NSString *lovepath = [[NSBundle mainBundle] pathForResource:nil ofType:@"love"];
if (lovepath != nil)
path = [lovepath UTF8String];
}
return path;
}
std::string checkDropEvents()
{
std::string dropstr;
SDL_Event event;
SDL_InitSubSystem(SDL_INIT_VIDEO);
SDL_PumpEvents();
if (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_DROPFILE, SDL_DROPFILE) > 0)
{
if (event.type == SDL_DROPFILE)
{
dropstr = std::string(event.drop.file);
SDL_free(event.drop.file);
}
}
SDL_QuitSubSystem(SDL_INIT_VIDEO);
return dropstr;
}
} // osx
} // love
#endif // LOVE_MACOSX
+12 -5
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -21,8 +21,6 @@
// LOVE
#include "Object.h"
#include <stdio.h>
namespace love
{
@@ -31,6 +29,11 @@ Object::Object()
{
}
Object::Object(const Object & /*other*/)
: count(1) // Always start with a reference count of 1.
{
}
Object::~Object()
{
}
@@ -42,13 +45,17 @@ int Object::getReferenceCount() const
void Object::retain()
{
++count;
count.fetch_add(1, std::memory_order_relaxed);
}
void Object::release()
{
if (--count <= 0)
// http://www.boost.org/doc/libs/1_56_0/doc/html/atomic/usage_examples.html
if (count.fetch_sub(1, std::memory_order_release) == 1)
{
std::atomic_thread_fence(std::memory_order_acquire);
delete this;
}
}
} // love
+65 -89
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -21,6 +21,8 @@
#ifndef LOVE_OBJECT_H
#define LOVE_OBJECT_H
#include <atomic>
namespace love
{
@@ -40,6 +42,7 @@ public:
* Constructor. Sets reference count to one.
**/
Object();
Object(const Object &other);
/**
* Destructor.
@@ -65,100 +68,73 @@ public:
**/
virtual void release();
/**
* Meant to be used as a temporary object. Facilitates safer and cleaner
* code to release objects by doing so when the AutoRelease object is
* destroyed (e.g. goes out of scope.)
**/
class AutoRelease
{
public:
AutoRelease(Object *obj)
: object(obj)
{
}
~AutoRelease()
{
if (object)
object->release();
}
private:
AutoRelease() {}
Object *object;
}; // AutoRelease
/**
* Partial re-implementation + specialization of std::shared_ptr. We can't
* use C++11's stdlib yet...
**/
template <typename T>
class StrongRef
{
public:
StrongRef()
: object(nullptr)
{
}
StrongRef(T *obj)
: object(obj)
{
if (object) object->retain();
}
StrongRef(const StrongRef &other)
: object(other.get())
{
if (object) object->retain();
}
~StrongRef()
{
if (object) object->release();
}
StrongRef &operator = (const StrongRef &other)
{
set(other.get());
return *this;
}
T *operator->() const
{
return object;
}
void set(T *obj)
{
if (obj) obj->retain();
if (object) object->release();
object = obj;
}
T *get() const
{
return object;
}
private:
T *object;
}; // StrongRef
private:
// The reference count.
int count;
std::atomic<int> count;
}; // Object
/**
* Partial re-implementation + specialization of std::shared_ptr. We can't
* use C++11's stdlib yet...
**/
template <typename T>
class StrongRef
{
public:
StrongRef()
: object(nullptr)
{
}
StrongRef(T *obj)
: object(obj)
{
if (object) object->retain();
}
StrongRef(const StrongRef &other)
: object(other.get())
{
if (object) object->retain();
}
~StrongRef()
{
if (object) object->release();
}
StrongRef &operator = (const StrongRef &other)
{
set(other.get());
return *this;
}
T *operator->() const
{
return object;
}
void set(T *obj)
{
if (obj) obj->retain();
if (object) object->release();
object = obj;
}
T *get() const
{
return object;
}
private:
T *object;
}; // StrongRef
} // love
#endif // LOVE_OBJECT_H
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+4 -9
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -101,9 +101,8 @@ Variant::Variant(love::Type udatatype, void *userdata)
if (udatatype != INVALID_ID)
{
Proxy *p = (Proxy *) userdata;
flags = p->flags;
data.userdata = p->data;
((love::Object *) data.userdata)->retain();
data.userdata = p->object;
p->object->retain();
}
else
data.userdata = userdata;
@@ -223,11 +222,7 @@ void Variant::toLua(lua_State *L)
break;
case FUSERDATA:
if (udatatype != INVALID_ID)
{
const char *name = NULL;
love::types.find(udatatype, name);
luax_pushtype(L, name, flags, (love::Object *) data.userdata);
}
luax_pushtype(L, udatatype, (love::Object *) data.userdata);
else
lua_pushlightuserdata(L, data.userdata);
// I know this is not the same
+1 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -76,7 +76,6 @@ public:
private:
love::Type udatatype;
bits flags;
}; // Variant
} // love
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+5 -5
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -216,15 +216,15 @@ inline float Vector::normalize(float length)
**/
inline Vector::Vector()
: x(0.0f)
, y(0.0f)
{
x = 1;
y = 1;
}
inline Vector::Vector(float x, float y)
: x(x)
, y(y)
{
this->x = x;
this->y = y;
}
inline Vector Vector::operator + (const Vector &v) const
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+15 -4
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -29,8 +29,12 @@
# define LOVE_LINUX 1
#endif
#if defined(__APPLE__)
# define LOVE_MACOSX 1
# include <AvailabilityMacros.h>
# include <TargetConditionals.h>
# if TARGET_OS_IPHONE
# define LOVE_IOS 1
# elif TARGET_OS_MAC
# define LOVE_MACOSX 1
# endif
#endif
// Endianness.
@@ -71,10 +75,14 @@
# define NOMINMAX
#endif
#if defined(LOVE_MACOSX)
#if defined(LOVE_MACOSX) || defined(LOVE_IOS)
# define LOVE_LEGENDARY_APP_ARGV_HACK
#endif
#if defined(LOVE_ANDROID) || defined(LOVE_IOS)
# define LOVE_LEGENDARY_ACCELEROMETER_AS_JOYSTICK_HACK
#endif
// Autotools config.h
#ifdef HAVE_CONFIG_H
# include <../config.h>
@@ -109,6 +117,7 @@
# define LOVE_ENABLE_KEYBOARD_SDL
# define LOVE_ENABLE_LOVE
# define LOVE_ENABLE_LUASOCKET
# define LOVE_ENABLE_LUAUTF8
# define LOVE_ENABLE_MATH
# define LOVE_ENABLE_MOUSE
# define LOVE_ENABLE_MOUSE_SDL
@@ -123,6 +132,8 @@
# define LOVE_ENABLE_THREAD_SDL
# define LOVE_ENABLE_TIMER
# define LOVE_ENABLE_TIMER_SDL
# define LOVE_ENABLE_TOUCH
# define LOVE_ENABLE_TOUCH_SDL
# define LOVE_ENABLE_UTF8
# define LOVE_ENABLE_WINDOW
# define LOVE_ENABLE_WINDOW_SDL
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+61
View File
@@ -0,0 +1,61 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_IOS_H
#define LOVE_IOS_H
#include "config.h"
#ifdef LOVE_IOS
#include <string>
namespace love
{
namespace ios
{
/**
* Gets the filepath of the first detected love file. The main .app Bundle is
* searched first, and then the app's Documents folder.
**/
std::string getLoveInResources(bool &fused);
/**
* Gets the directory path where files should be stored.
**/
std::string getAppdataDirectory();
/**
* Get the home directory (on iOS, this really means the app's sandbox dir.)
**/
std::string getHomeDirectory();
/**
* Opens the specified URL with the default program associated with the URL's
* scheme.
**/
bool openURL(const std::string &url);
} // ios
} // love
#endif // LOVE_IOS
#endif // LOVE_IOS_H
+320
View File
@@ -0,0 +1,320 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "iOS.h"
#ifdef LOVE_IOS
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#include <vector>
#include <SDL_events.h>
static NSArray *getLovesInDocuments();
static bool deleteFileInDocuments(NSString *filename);
@interface LOVETableViewController : UITableViewController
- (instancetype)initWithGameList:(NSArray *)list;
@property (nonatomic) NSMutableArray *gameList;
@property (nonatomic, readonly, copy) NSString *selectedGame;
@end
@implementation LOVETableViewController
- (instancetype)initWithGameList:(NSArray *)list
{
if ((self = [super init]))
{
_gameList = [[NSMutableArray alloc] initWithArray:list copyItems:YES];
self.title = @"LÖVE Games";
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
return self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#pragma unused(tableView)
#pragma unused(section)
// We want to list all games plus the no-game screen.
return self.gameList.count + 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"LOVETableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
if (indexPath.row < (NSInteger) self.gameList.count)
cell.textLabel.text = self.gameList[indexPath.row];
else
cell.textLabel.text = @"No-game screen";
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
#pragma unused(tableView)
if (indexPath.row < (NSInteger) self.gameList.count)
_selectedGame = [(NSString *)(self.gameList[indexPath.row]) copy];
else
{
// We test against nil to check if a game has been selected, so we'll
// just use an empty string instead to represent the no-game screen.
_selectedGame = @"";
}
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle != UITableViewCellEditingStyleDelete)
return;
if (indexPath.row >= (NSInteger) self.gameList.count)
return;
NSString *filename = self.gameList[indexPath.row];
// Delete the file.
if (deleteFileInDocuments(filename))
{
[self.gameList removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;
{
#pragma unused(tableView)
// The no-game screen isn't removable.
return indexPath.row < (NSInteger) self.gameList.count;
}
@end
static NSString *getDocumentsDirectory()
{
NSArray *docdirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return docdirs[0];
}
static NSArray *getLovesInDocuments()
{
NSString *documents = getDocumentsDirectory();
NSArray *filepaths = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documents error:nil];
return [filepaths pathsMatchingExtensions:@[@"love"]];
}
static bool deleteFileInDocuments(NSString *filename)
{
NSString *documents = getDocumentsDirectory();
NSString *file = [documents stringByAppendingPathComponent:filename];
bool success = [[NSFileManager defaultManager] removeItemAtPath:file error:nil];
if (success)
NSLog(@"Deleted file %@ in Documents folder.", filename);
return success;
}
static int dropFileEventFilter(void *userdata, SDL_Event *event)
{
if (event->type != SDL_DROPFILE)
return 1;
NSString *fname = @(event->drop.file);
NSFileManager *fmanager = [NSFileManager defaultManager];
if ([fmanager fileExistsAtPath:fname] && [fname.pathExtension isEqual:@"love"])
{
NSString *documents = getDocumentsDirectory();
documents = [[documents stringByStandardizingPath] stringByResolvingSymlinksInPath];
fname = [[fname stringByStandardizingPath] stringByResolvingSymlinksInPath];
// Is the file inside the Documents directory?
if ([fname hasPrefix:documents])
{
LOVETableViewController *vc = (__bridge LOVETableViewController *) userdata;
// Update the game list.
NSArray *games = getLovesInDocuments();
vc.gameList = [[NSMutableArray alloc] initWithArray:games copyItems:YES];
[vc.tableView reloadData];
SDL_free(event->drop.file);
return 0;
}
}
return 1;
}
namespace love
{
namespace ios
{
/**
* Displays a full-screen list of available LOVE games for the user to choose.
* Returns the index of the selected game from the list. The list of games
* includes the no-game screen, and the function will return an index outside
* of the array's range if that is selected.
**/
static NSString *showGameList(NSArray *filenames)
{
// Game list view controller.
LOVETableViewController *tablecontroller = [[LOVETableViewController alloc] initWithGameList:filenames];
// Navigation view controller (only used for the header bar right now.)
// Contains the game list view/controller.
UINavigationController *navcontroller = [[UINavigationController alloc] initWithRootViewController:tablecontroller];
UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
window.rootViewController = navcontroller;
SDL_EventFilter oldfilter = nullptr;
void *oldudata = nullptr;
SDL_GetEventFilter(&oldfilter, &oldudata);
// Manually retain the table VC and use it for the event filter userdata.
// We need to set a custom event filter to update the table when .love files
// are opened by the user.
void *tableudata = (void *) CFBridgingRetain(tablecontroller);
SDL_SetEventFilter(dropFileEventFilter, tableudata);
[window makeKeyAndVisible];
// Process events until a game in the list is selected.
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
while (tablecontroller.selectedGame == nil)
{
[runloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
[runloop runMode:UITrackingRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1.0/60.0]];
}
// The window will get released and cleaned up once we go out of scope.
window.hidden = YES;
SDL_SetEventFilter(oldfilter, oldudata);
CFBridgingRelease(tableudata);
return tablecontroller.selectedGame;
}
std::string getLoveInResources(bool &fused)
{
fused = false;
std::string path;
@autoreleasepool
{
// Start by looking in the main bundle (.app) folder for .love files.
NSArray *bundlepaths = [[NSBundle mainBundle] pathsForResourcesOfType:@"love" inDirectory:nil];
if (bundlepaths.count > 0)
{
// The game should be fused if we have something here.
fused = true;
NSLog(@".love files in main Bundle: %@", bundlepaths);
return [bundlepaths[0] UTF8String];
}
// Otherwise look in the app's Documents directory. The game won't be
// fused.
NSArray *filepaths = getLovesInDocuments();
if (filepaths.count > 0)
NSLog(@".love files in Documents: %@", filepaths);
// Let the user select a game from the un-fused list.
NSString *selectedfile = showGameList(filepaths);
// The string length might be 0 if the no-game screen was selected.
if (selectedfile != nil && selectedfile.length > 0)
{
NSString *documents = getDocumentsDirectory();
path = [[documents stringByAppendingPathComponent:selectedfile] UTF8String];
NSLog(@"Using unfused .love file: %@", selectedfile);
}
}
return path;
}
std::string getAppdataDirectory()
{
NSSearchPathDirectory searchdir = NSApplicationSupportDirectory;
std::string path;
@autoreleasepool
{
NSArray *dirs = NSSearchPathForDirectoriesInDomains(searchdir, NSUserDomainMask, YES);
if (dirs.count > 0)
path = [dirs[0] UTF8String];
}
return path;
}
std::string getHomeDirectory()
{
std::string path;
@autoreleasepool
{
path = [NSHomeDirectory() UTF8String];
}
return path;
}
bool openURL(const std::string &url)
{
bool success = false;
@autoreleasepool
{
NSURL *nsurl = [NSURL URLWithString:@(url.c_str())];
if ([[UIApplication sharedApplication] canOpenURL:nsurl])
success = [[UIApplication sharedApplication] openURL:nsurl];
}
return success;
}
} // ios
} // love
#endif // LOVE_IOS
+22 -3
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -22,8 +22,6 @@
#define LOVE_INT_H
// C standard sized integer types.
// This header was added to Visual studio in VS 2012, which is LOVE's current
// minimum supported VS version (as of this comment's commit date.)
#include <stdint.h>
#define LOVE_INT8_MAX 0x7F
@@ -47,6 +45,27 @@ typedef uint32_t uint32;
typedef int64_t int64;
typedef uint64_t uint64;
static inline uint16 swap16(uint16 x)
{
return (x >> 8) | (x << 8);
}
static inline uint32 swap32(uint32 x)
{
return ((x & 0x000000FF) << 24) |
((x & 0x0000FF00) << 8) |
((x & 0x00FF0000) >> 8) |
((x & 0xFF000000) >> 24);
}
static inline uint64 swap64(uint64 x)
{
return ((x << 56) & 0xFF00000000000000ULL) | ((x << 40) & 0x00FF000000000000ULL) |
((x << 24) & 0x0000FF0000000000ULL) | ((x << 8) & 0x000000FF00000000ULL) |
((x >> 8) & 0x00000000FF000000ULL) | ((x >> 24) & 0x0000000000FF0000ULL) |
((x >> 40) & 0x000000000000FF00ULL) | ((x >> 56) & 0x00000000000000FFULL);
}
} // love
#endif // LOVE_INT_H
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+31 -130
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -26,7 +26,6 @@
#include "Object.h"
#include "Reference.h"
#include "StringMap.h"
#include <thread/threads.h>
// C++
#include <algorithm>
@@ -36,24 +35,14 @@
namespace love
{
static thread::Mutex *gcmutex = nullptr;
/**
* Called when an object is collected. The object is released
* once in this function, possibly deleting it.
**/
static int w__gc(lua_State *L)
{
if (!gcmutex)
gcmutex = thread::newMutex();
Proxy *p = (Proxy *) lua_touserdata(L, 1);
Object *object = (Object *) p->data;
thread::Lock lock(gcmutex);
object->release();
p->object->release();
return 0;
}
@@ -67,7 +56,7 @@ static int w__typeOf(lua_State *L)
{
Proxy *p = (Proxy *)lua_touserdata(L, 1);
Type t = luax_type(L, 2);
luax_pushboolean(L, p->flags[t]);
luax_pushboolean(L, typeFlags[p->type][t]);
return 1;
}
@@ -75,7 +64,7 @@ static int w__eq(lua_State *L)
{
Proxy *p1 = (Proxy *)lua_touserdata(L, 1);
Proxy *p2 = (Proxy *)lua_touserdata(L, 2);
luax_pushboolean(L, p1->data == p2->data);
luax_pushboolean(L, p1->object == p2->object);
return 1;
}
@@ -217,8 +206,8 @@ int luax_register_module(lua_State *L, const WrappedModule &m)
luax_insistregistry(L, REGISTRY_MODULES);
Proxy *p = (Proxy *)lua_newuserdata(L, sizeof(Proxy));
p->data = m.module;
p->flags = m.flags;
p->object = m.module;
p->type = m.type;
luaL_newmetatable(L, m.module->getName());
lua_pushvalue(L, -1);
@@ -265,12 +254,12 @@ int luax_preload(lua_State *L, lua_CFunction f, const char *name)
return 0;
}
int luax_register_type(lua_State *L, const char *tname, const luaL_Reg *f)
int luax_register_type(lua_State *L, love::Type type, const luaL_Reg *f)
{
// Verify that this type name has a matching Type ID and type name mapping.
love::Type ltype;
if (!love::getType(tname, ltype))
printf("Missing type entry for type name: %s\n", tname);
const char *tname = "Invalid";
if (!love::getType(type, tname))
printf("Missing type name entry for type ID %d\n", type);
// Get the place for storing and re-using instantiated love types.
luax_getregistry(L, REGISTRY_TYPES);
@@ -338,19 +327,22 @@ int luax_table_insert(lua_State *L, int tindex, int vindex, int pos)
tindex = lua_gettop(L)+1+tindex;
if (vindex < 0)
vindex = lua_gettop(L)+1+vindex;
if (pos == -1)
{
lua_pushvalue(L, vindex);
lua_rawseti(L, tindex, lua_objlen(L, tindex)+1);
lua_rawseti(L, tindex, (int) lua_objlen(L, tindex)+1);
return 0;
}
else if (pos < 0)
pos = lua_objlen(L, tindex)+1+pos;
for (int i = lua_objlen(L, tindex)+1; i > pos; i--)
pos = (int) lua_objlen(L, tindex)+1+pos;
for (int i = (int) lua_objlen(L, tindex)+1; i > pos; i--)
{
lua_rawgeti(L, tindex, i-1);
lua_rawseti(L, tindex, i);
}
lua_pushvalue(L, vindex);
lua_rawseti(L, tindex, pos);
return 0;
@@ -382,20 +374,23 @@ int luax_register_searcher(lua_State *L, lua_CFunction f, int pos)
return 0;
}
void luax_rawnewtype(lua_State *L, const char *name, bits flags, love::Object *object)
void luax_rawnewtype(lua_State *L, love::Type type, love::Object *object)
{
Proxy *u = (Proxy *)lua_newuserdata(L, sizeof(Proxy));
object->retain();
u->data = (void *) object;
u->flags = flags;
u->object = object;
u->type = type;
const char *name = "Invalid";
getType(type, name);
luaL_newmetatable(L, name);
lua_setmetatable(L, -2);
}
void luax_pushtype(lua_State *L, const char *name, bits flags, love::Object *object)
void luax_pushtype(lua_State *L, love::Type type, love::Object *object)
{
if (object == nullptr)
{
@@ -410,11 +405,11 @@ void luax_pushtype(lua_State *L, const char *name, bits flags, love::Object *obj
if (!lua_istable(L, -1))
{
lua_pop(L, 1);
return luax_rawnewtype(L, name, flags, object);
return luax_rawnewtype(L, type, object);
}
// Get the value of lovetypes[object] on the stack.
lua_pushlightuserdata(L, (void *) object);
lua_pushlightuserdata(L, object);
lua_gettable(L, -2);
// If the Proxy userdata isn't in the instantiated types table yet, add it.
@@ -422,9 +417,9 @@ void luax_pushtype(lua_State *L, const char *name, bits flags, love::Object *obj
{
lua_pop(L, 1);
luax_rawnewtype(L, name, flags, object);
luax_rawnewtype(L, type, object);
lua_pushlightuserdata(L, (void *) object);
lua_pushlightuserdata(L, object);
lua_pushvalue(L, -2);
// lovetypes[object] = Proxy.
@@ -437,12 +432,13 @@ void luax_pushtype(lua_State *L, const char *name, bits flags, love::Object *obj
// Keep the Proxy userdata on the stack.
}
bool luax_istype(lua_State *L, int idx, love::bits type)
bool luax_istype(lua_State *L, int idx, love::Type type)
{
if (lua_type(L, idx) != LUA_TUSERDATA)
return false;
return ((((Proxy *)lua_touserdata(L, idx))->flags & type) == type);
Proxy *p = (Proxy *) lua_touserdata(L, idx);
return typeFlags[p->type][type];
}
int luax_getfunction(lua_State *L, const char *mod, const char *fn)
@@ -632,105 +628,10 @@ extern "C" int luax_typerror(lua_State *L, int narg, const char *tname)
return luaL_argerror(L, narg, msg);
}
StringMap<Type, TYPE_MAX_ENUM>::Entry typeEntries[] =
{
{"Invalid", INVALID_ID},
{"Object", OBJECT_ID},
{"Data", DATA_ID},
{"Module", MODULE_ID},
// Filesystem
{"File", FILESYSTEM_FILE_ID},
{"FileData", FILESYSTEM_FILE_DATA_ID},
// Font
{"GlyphData", FONT_GLYPH_DATA_ID},
{"Rasterizer", FONT_RASTERIZER_ID},
// Graphics
{"Drawable", GRAPHICS_DRAWABLE_ID},
{"Texture", GRAPHICS_TEXTURE_ID},
{"Image", GRAPHICS_IMAGE_ID},
{"Quad", GRAPHICS_QUAD_ID},
{"Font", GRAPHICS_FONT_ID},
{"ParticleSystem", GRAPHICS_PARTICLE_SYSTEM_ID},
{"SpriteBatch", GRAPHICS_SPRITE_BATCH_ID},
{"Canvas", GRAPHICS_CANVAS_ID},
{"Shader", GRAPHICS_SHADER_ID},
{"Mesh", GRAPHICS_MESH_ID},
// Image
{"ImageData", IMAGE_IMAGE_DATA_ID},
{"CompressedData", IMAGE_COMPRESSED_DATA_ID},
// Joystick
{"Joystick", JOYSTICK_JOYSTICK_ID},
// Math
{"RandomGenerator", MATH_RANDOM_GENERATOR_ID},
{"BezierCurve", MATH_BEZIER_CURVE_ID},
// Audio
{"Source", AUDIO_SOURCE_ID},
// Sound
{"SoundData", SOUND_SOUND_DATA_ID},
{"Decoder", SOUND_DECODER_ID},
// Mouse
{"Cursor", MOUSE_CURSOR_ID},
// Physics
{"World", PHYSICS_WORLD_ID},
{"Contact", PHYSICS_CONTACT_ID},
{"Body", PHYSICS_BODY_ID},
{"Fixture", PHYSICS_FIXTURE_ID},
{"Shape", PHYSICS_SHAPE_ID},
{"CircleShape", PHYSICS_CIRCLE_SHAPE_ID},
{"PolygonShape", PHYSICS_POLYGON_SHAPE_ID},
{"EdgeShape", PHYSICS_EDGE_SHAPE_ID},
{"ChainShape", PHYSICS_CHAIN_SHAPE_ID},
{"Joint", PHYSICS_JOINT_ID},
{"MouseJoint", PHYSICS_MOUSE_JOINT_ID},
{"DistanceJoint", PHYSICS_DISTANCE_JOINT_ID},
{"PrismaticJoint", PHYSICS_PRISMATIC_JOINT_ID},
{"RevoluteJoint", PHYSICS_REVOLUTE_JOINT_ID},
{"PulleyJoint", PHYSICS_PULLEY_JOINT_ID},
{"GearJoint", PHYSICS_GEAR_JOINT_ID},
{"FrictionJoint", PHYSICS_FRICTION_JOINT_ID},
{"WeldJoint", PHYSICS_WELD_JOINT_ID},
{"RopeJoint", PHYSICS_ROPE_JOINT_ID},
{"WheelJoint", PHYSICS_WHEEL_JOINT_ID},
{"MotorJoint", PHYSICS_MOTOR_JOINT_ID},
// Thread
{"Thread", THREAD_THREAD_ID},
{"Channel", THREAD_CHANNEL_ID},
// The modules themselves. Only add abstracted modules here.
{"filesystem", MODULE_FILESYSTEM_ID},
{"graphics", MODULE_GRAPHICS_ID},
{"image", MODULE_IMAGE_ID},
{"sound", MODULE_SOUND_ID},
};
StringMap<Type, TYPE_MAX_ENUM> types(typeEntries, sizeof(typeEntries));
bool getType(const char *in, love::Type &out)
{
return types.find(in, out);
}
bool getType(love::Type in, const char *&out)
{
return types.find(in, out);
}
Type luax_type(lua_State *L, int idx)
{
Type t = INVALID_ID;
types.find(luaL_checkstring(L, idx), t);
getType(luaL_checkstring(L, idx), t);
return t;
}
+45 -34
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -23,7 +23,6 @@
// LOVE
#include "types.h"
#include "Object.h"
// Lua
extern "C" {
@@ -40,6 +39,7 @@ namespace love
{
// Forward declarations.
class Object;
class Module;
class Reference;
@@ -63,10 +63,10 @@ enum Registry
struct Proxy
{
// Holds type information (see types.h).
bits flags;
Type type;
// The light userdata (pointer to the love::Object).
void *data;
// Pointer to the actual object.
Object *object;
};
/**
@@ -80,15 +80,14 @@ struct WrappedModule
// The name for the table to put the functions in, without the 'love'-prefix.
const char *name;
// The type flags of this module.
love::bits flags;
// The type of this module.
love::Type type;
// The functions of the module (last element {0,0}).
const luaL_Reg *functions;
// A list of functions which expose the types of the modules (last element 0).
const lua_CFunction *types;
};
/**
@@ -241,11 +240,10 @@ int luax_preload(lua_State *L, lua_CFunction f, const char *name);
/**
* Register a new type.
* @param tname The name of the type. This must not conflict with other type names,
* even from other modules.
* @param type The type.
* @param f The list of member functions for the type.
**/
int luax_register_type(lua_State *L, const char *tname, const luaL_Reg *f = 0);
int luax_register_type(lua_State *L, love::Type type, const luaL_Reg *f = 0);
/**
* Do a table.insert from C
@@ -271,10 +269,10 @@ int luax_register_searcher(lua_State *L, lua_CFunction f, int pos = -1);
* NOTE: The object will be retained by Lua and released upon garbage collection.
* @param L The Lua state.
* @param name The name of the type. This must match the name used with luax_register_type.
* @param flags The type information of the object.
* @param type The type information of the object.
* @param object The pointer to the actual object.
**/
void luax_pushtype(lua_State *L, const char *name, bits flags, love::Object *object);
void luax_pushtype(lua_State *L, const love::Type type, love::Object *object);
/**
* Creates a new Lua representation of the given object *without* checking if it
@@ -285,10 +283,10 @@ void luax_pushtype(lua_State *L, const char *name, bits flags, love::Object *obj
* NOTE: The object will be retained by Lua and released upon garbage collection.
* @param L The Lua state.
* @param name The name of the type. This must match the name used with luax_register_type.
* @param flags The type information of the object.
* @param type The type information of the object.
* @param object The pointer to the actual object.
**/
void luax_rawnewtype(lua_State *L, const char *name, bits flags, love::Object *object);
void luax_rawnewtype(lua_State *L, love::Type type, love::Object *object);
/**
* Checks whether the value at idx is a certain type.
@@ -297,7 +295,7 @@ void luax_rawnewtype(lua_State *L, const char *name, bits flags, love::Object *o
* @param type The type to check for.
* @return True if the value is Proxy of the specified type, false otherwise.
**/
bool luax_istype(lua_State *L, int idx, love::bits type);
bool luax_istype(lua_State *L, int idx, love::Type type);
/**
* Gets the function love.module.function and puts it on top of the stack (alone). If the
@@ -399,43 +397,57 @@ extern "C" { // Also called from luasocket
* @param type The type bit.
**/
template <typename T>
T *luax_checktype(lua_State *L, int idx, const char *name, love::bits type)
T *luax_checktype(lua_State *L, int idx, love::Type type)
{
if (lua_type(L, idx) != LUA_TUSERDATA)
{
const char *name = "Invalid";
getType(type, name);
luax_typerror(L, idx, name);
}
Proxy *u = (Proxy *)lua_touserdata(L, idx);
if ((u->flags & type) != type)
if (!typeFlags[u->type][type])
{
const char *name = "Invalid";
getType(type, name);
luax_typerror(L, idx, name);
}
return (T *)u->data;
return (T *)u->object;
}
template <typename T>
T *luax_getmodule(lua_State *L, const char *k, love::bits type)
T *luax_getmodule(lua_State *L, love::Type type)
{
const char *name = "Invalid";
getType(type, name);
luax_insistregistry(L, REGISTRY_MODULES);
lua_getfield(L, -1, k);
lua_getfield(L, -1, name);
if (!lua_isuserdata(L, -1))
luaL_error(L, "Tried to get nonexistant module %s.", k);
luaL_error(L, "Tried to get nonexistant module %s.", name);
Proxy *u = (Proxy *)lua_touserdata(L, -1);
if ((u->flags & type) != type)
luaL_error(L, "Incorrect module %s", k);
if (!typeFlags[u->type][type])
luaL_error(L, "Incorrect module %s", name);
lua_pop(L, 2);
return (T *)u->data;
return (T *)u->object;
}
template <typename T>
T *luax_optmodule(lua_State *L, const char *k, love::bits type)
T *luax_optmodule(lua_State *L, love::Type type)
{
const char *name = "Invalid";
getType(type, name);
luax_insistregistry(L, REGISTRY_MODULES);
lua_getfield(L, -1, k);
lua_getfield(L, -1, name);
if (!lua_isuserdata(L, -1))
{
@@ -445,12 +457,12 @@ T *luax_optmodule(lua_State *L, const char *k, love::bits type)
Proxy *u = (Proxy *)lua_touserdata(L, -1);
if ((u->flags & type) != type)
luaL_error(L, "Incorrect module %s", k);
if (!typeFlags[u->type][type])
luaL_error(L, "Incorrect module %s", name);
lua_pop(L, 2);
return (T *) u->data;
return (T *) u->object;
}
/**
@@ -459,13 +471,12 @@ T *luax_optmodule(lua_State *L, const char *k, love::bits type)
* luax_istype, then this can be safely used. Otherwise, use luax_checktype.
* @param L The Lua state.
* @param idx The index on the stack.
* @param name The name of the type.
* @param type The type bit.
* @param type The type of the object.
**/
template <typename T>
T *luax_totype(lua_State *L, int idx, const char * /* name */, love::bits /* type */)
T *luax_totype(lua_State *L, int idx, love::Type /*type*/)
{
return (T *)(((Proxy *)lua_touserdata(L, idx))->data);
return (T *)(((Proxy *)lua_touserdata(L, idx))->object);
}
Type luax_type(lua_State *L, int idx);
+217
View File
@@ -0,0 +1,217 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "types.h"
#include "StringMap.h"
namespace love
{
static const TypeBits *createTypeFlags()
{
static TypeBits b[TYPE_MAX_ENUM];
TypeBits one = TypeBits(1);
b[INVALID_ID] = one << INVALID_ID;
b[OBJECT_ID] = one << OBJECT_ID;
b[DATA_ID] = (one << DATA_ID) | b[OBJECT_ID];
b[MODULE_ID] = (one << MODULE_ID) | b[OBJECT_ID];
// Filesystem.
b[FILESYSTEM_FILE_ID] = (one << FILESYSTEM_FILE_ID) | b[OBJECT_ID];
b[FILESYSTEM_DROPPED_FILE_ID] = (one << FILESYSTEM_DROPPED_FILE_ID) | b[FILESYSTEM_FILE_ID];
b[FILESYSTEM_FILE_DATA_ID] = (one << FILESYSTEM_FILE_DATA_ID) | b[DATA_ID];
b[FONT_GLYPH_DATA_ID] = (one << FONT_GLYPH_DATA_ID) | b[DATA_ID];
b[FONT_RASTERIZER_ID] = (one << FONT_RASTERIZER_ID) | b[OBJECT_ID];
// Graphics.
b[GRAPHICS_DRAWABLE_ID] = (one << GRAPHICS_DRAWABLE_ID) | b[OBJECT_ID];
b[GRAPHICS_TEXTURE_ID] = (one << GRAPHICS_TEXTURE_ID) | b[GRAPHICS_DRAWABLE_ID];
b[GRAPHICS_IMAGE_ID] = (one << GRAPHICS_IMAGE_ID) | b[GRAPHICS_TEXTURE_ID];
b[GRAPHICS_QUAD_ID] = (one << GRAPHICS_QUAD_ID) | b[OBJECT_ID];
b[GRAPHICS_FONT_ID] = (one << GRAPHICS_FONT_ID) | b[OBJECT_ID];
b[GRAPHICS_PARTICLE_SYSTEM_ID] = (one << GRAPHICS_PARTICLE_SYSTEM_ID) | b[GRAPHICS_DRAWABLE_ID];
b[GRAPHICS_SPRITE_BATCH_ID] = (one << GRAPHICS_SPRITE_BATCH_ID) | b[GRAPHICS_DRAWABLE_ID];
b[GRAPHICS_CANVAS_ID] = (one << GRAPHICS_CANVAS_ID) | b[GRAPHICS_TEXTURE_ID];
b[GRAPHICS_SHADER_ID] = (one << GRAPHICS_SHADER_ID) | b[OBJECT_ID];
b[GRAPHICS_MESH_ID] = (one << GRAPHICS_MESH_ID) | b[GRAPHICS_DRAWABLE_ID];
b[GRAPHICS_TEXT_ID] = (one << GRAPHICS_TEXT_ID) | b[GRAPHICS_DRAWABLE_ID];
// Image.
b[IMAGE_IMAGE_DATA_ID] = (one << IMAGE_IMAGE_DATA_ID) | b[DATA_ID];
b[IMAGE_COMPRESSED_DATA_ID] = (one << IMAGE_COMPRESSED_DATA_ID) | b[DATA_ID];
// Joystick.
b[JOYSTICK_JOYSTICK_ID] = (one << JOYSTICK_JOYSTICK_ID) | b[OBJECT_ID];
// Math.
b[MATH_RANDOM_GENERATOR_ID] = (one << MATH_RANDOM_GENERATOR_ID) | b[OBJECT_ID];
b[MATH_BEZIER_CURVE_ID] = (one << MATH_BEZIER_CURVE_ID) | b[OBJECT_ID];
// Audio.
b[AUDIO_SOURCE_ID] = (one << AUDIO_SOURCE_ID) | b[OBJECT_ID];
// Sound.
b[SOUND_SOUND_DATA_ID] = (one << SOUND_SOUND_DATA_ID) | b[DATA_ID];
b[SOUND_DECODER_ID] = one << SOUND_DECODER_ID;
// Mouse.
b[MOUSE_CURSOR_ID] = (one << MOUSE_CURSOR_ID) | b[OBJECT_ID];
// Physics.
b[PHYSICS_WORLD_ID] = (one << PHYSICS_WORLD_ID) | b[OBJECT_ID];
b[PHYSICS_CONTACT_ID] = (one << PHYSICS_CONTACT_ID) | b[OBJECT_ID];
b[PHYSICS_BODY_ID] = (one << PHYSICS_BODY_ID) | b[OBJECT_ID];
b[PHYSICS_FIXTURE_ID] = (one << PHYSICS_FIXTURE_ID) | b[OBJECT_ID];
b[PHYSICS_SHAPE_ID] = (one << PHYSICS_SHAPE_ID) | b[OBJECT_ID];
b[PHYSICS_CIRCLE_SHAPE_ID] = (one << PHYSICS_CIRCLE_SHAPE_ID) | b[PHYSICS_SHAPE_ID];
b[PHYSICS_POLYGON_SHAPE_ID] = (one << PHYSICS_POLYGON_SHAPE_ID) | b[PHYSICS_SHAPE_ID];
b[PHYSICS_EDGE_SHAPE_ID] = (one << PHYSICS_EDGE_SHAPE_ID) | b[PHYSICS_SHAPE_ID];
b[PHYSICS_CHAIN_SHAPE_ID] = (one << PHYSICS_CHAIN_SHAPE_ID) | b[PHYSICS_SHAPE_ID];
b[PHYSICS_JOINT_ID] = (one << PHYSICS_JOINT_ID) | b[OBJECT_ID];
b[PHYSICS_MOUSE_JOINT_ID] = (one << PHYSICS_MOUSE_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_DISTANCE_JOINT_ID] = (one << PHYSICS_DISTANCE_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_PRISMATIC_JOINT_ID] = (one << PHYSICS_PRISMATIC_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_REVOLUTE_JOINT_ID] = (one << PHYSICS_REVOLUTE_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_PULLEY_JOINT_ID] = (one << PHYSICS_PULLEY_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_GEAR_JOINT_ID] = (one << PHYSICS_GEAR_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_FRICTION_JOINT_ID] = (one << PHYSICS_FRICTION_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_WELD_JOINT_ID] = (one << PHYSICS_WELD_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_ROPE_JOINT_ID] = (one << PHYSICS_ROPE_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_WHEEL_JOINT_ID] = (one << PHYSICS_WHEEL_JOINT_ID) | b[PHYSICS_JOINT_ID];
b[PHYSICS_MOTOR_JOINT_ID] = (one << PHYSICS_MOTOR_JOINT_ID) | b[PHYSICS_JOINT_ID];
// Thread.
b[THREAD_THREAD_ID] = (one << THREAD_THREAD_ID) | b[OBJECT_ID];
b[THREAD_CHANNEL_ID] = (one << THREAD_CHANNEL_ID) | b[OBJECT_ID];
// Modules.
b[MODULE_FILESYSTEM_ID] = (one << MODULE_FILESYSTEM_ID) | b[MODULE_ID];
b[MODULE_GRAPHICS_ID] = (one << MODULE_GRAPHICS_ID) | b[MODULE_ID];
b[MODULE_IMAGE_ID] = (one << MODULE_IMAGE_ID) | b[MODULE_ID];
b[MODULE_SOUND_ID] = (one << MODULE_SOUND_ID) | b[MODULE_ID];
return b;
}
const TypeBits *typeFlags = createTypeFlags();
StringMap<Type, TYPE_MAX_ENUM>::Entry typeEntries[] =
{
{"Invalid", INVALID_ID},
{"Object", OBJECT_ID},
{"Data", DATA_ID},
{"Module", MODULE_ID},
// Filesystem
{"File", FILESYSTEM_FILE_ID},
{"DroppedFile", FILESYSTEM_DROPPED_FILE_ID},
{"FileData", FILESYSTEM_FILE_DATA_ID},
// Font
{"GlyphData", FONT_GLYPH_DATA_ID},
{"Rasterizer", FONT_RASTERIZER_ID},
// Graphics
{"Drawable", GRAPHICS_DRAWABLE_ID},
{"Texture", GRAPHICS_TEXTURE_ID},
{"Image", GRAPHICS_IMAGE_ID},
{"Quad", GRAPHICS_QUAD_ID},
{"Font", GRAPHICS_FONT_ID},
{"ParticleSystem", GRAPHICS_PARTICLE_SYSTEM_ID},
{"SpriteBatch", GRAPHICS_SPRITE_BATCH_ID},
{"Canvas", GRAPHICS_CANVAS_ID},
{"Shader", GRAPHICS_SHADER_ID},
{"Mesh", GRAPHICS_MESH_ID},
{"Text", GRAPHICS_TEXT_ID},
// Image
{"ImageData", IMAGE_IMAGE_DATA_ID},
{"CompressedData", IMAGE_COMPRESSED_DATA_ID},
// Joystick
{"Joystick", JOYSTICK_JOYSTICK_ID},
// Math
{"RandomGenerator", MATH_RANDOM_GENERATOR_ID},
{"BezierCurve", MATH_BEZIER_CURVE_ID},
// Audio
{"Source", AUDIO_SOURCE_ID},
// Sound
{"SoundData", SOUND_SOUND_DATA_ID},
{"Decoder", SOUND_DECODER_ID},
// Mouse
{"Cursor", MOUSE_CURSOR_ID},
// Physics
{"World", PHYSICS_WORLD_ID},
{"Contact", PHYSICS_CONTACT_ID},
{"Body", PHYSICS_BODY_ID},
{"Fixture", PHYSICS_FIXTURE_ID},
{"Shape", PHYSICS_SHAPE_ID},
{"CircleShape", PHYSICS_CIRCLE_SHAPE_ID},
{"PolygonShape", PHYSICS_POLYGON_SHAPE_ID},
{"EdgeShape", PHYSICS_EDGE_SHAPE_ID},
{"ChainShape", PHYSICS_CHAIN_SHAPE_ID},
{"Joint", PHYSICS_JOINT_ID},
{"MouseJoint", PHYSICS_MOUSE_JOINT_ID},
{"DistanceJoint", PHYSICS_DISTANCE_JOINT_ID},
{"PrismaticJoint", PHYSICS_PRISMATIC_JOINT_ID},
{"RevoluteJoint", PHYSICS_REVOLUTE_JOINT_ID},
{"PulleyJoint", PHYSICS_PULLEY_JOINT_ID},
{"GearJoint", PHYSICS_GEAR_JOINT_ID},
{"FrictionJoint", PHYSICS_FRICTION_JOINT_ID},
{"WeldJoint", PHYSICS_WELD_JOINT_ID},
{"RopeJoint", PHYSICS_ROPE_JOINT_ID},
{"WheelJoint", PHYSICS_WHEEL_JOINT_ID},
{"MotorJoint", PHYSICS_MOTOR_JOINT_ID},
// Thread
{"Thread", THREAD_THREAD_ID},
{"Channel", THREAD_CHANNEL_ID},
// The modules themselves. Only add abstracted modules here.
{"filesystem", MODULE_FILESYSTEM_ID},
{"graphics", MODULE_GRAPHICS_ID},
{"image", MODULE_IMAGE_ID},
{"sound", MODULE_SOUND_ID},
};
StringMap<Type, TYPE_MAX_ENUM> types(typeEntries, sizeof(typeEntries));
static_assert((sizeof(typeEntries) / sizeof(typeEntries[0])) == TYPE_MAX_ENUM, "Type name array size doesn't match the total number of type IDs!");
bool getType(const char *in, love::Type &out)
{
return types.find(in, out);
}
bool getType(love::Type in, const char *&out)
{
return types.find(in, out);
}
} // love
+9 -81
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -37,6 +37,7 @@ enum Type
// Filesystem.
FILESYSTEM_FILE_ID,
FILESYSTEM_DROPPED_FILE_ID,
FILESYSTEM_FILE_DATA_ID,
// Font
@@ -54,6 +55,7 @@ enum Type
GRAPHICS_CANVAS_ID,
GRAPHICS_SHADER_ID,
GRAPHICS_MESH_ID,
GRAPHICS_TEXT_ID,
// Image
IMAGE_IMAGE_DATA_ID,
@@ -113,89 +115,15 @@ enum Type
TYPE_MAX_ENUM
};
typedef std::bitset<TYPE_MAX_ENUM> bits;
typedef std::bitset<TYPE_MAX_ENUM> TypeBits;
const bits INVALID_T = bits(1) << INVALID_ID;
const bits OBJECT_T = bits(1) << OBJECT_ID;
const bits DATA_T = (bits(1) << DATA_ID) | OBJECT_T;
const bits MODULE_T = (bits(1) << MODULE_ID) | OBJECT_T;
// Filesystem.
const bits FILESYSTEM_FILE_T = (bits(1) << FILESYSTEM_FILE_ID) | OBJECT_T;
const bits FILESYSTEM_FILE_DATA_T = (bits(1) << FILESYSTEM_FILE_DATA_ID) | DATA_T;
const bits FONT_GLYPH_DATA_T = (bits(1) << FONT_GLYPH_DATA_ID) | DATA_T;
const bits FONT_RASTERIZER_T = (bits(1) << FONT_RASTERIZER_ID) | OBJECT_T;
// Graphics.
const bits GRAPHICS_DRAWABLE_T = (bits(1) << GRAPHICS_DRAWABLE_ID) | OBJECT_T;
const bits GRAPHICS_TEXTURE_T = (bits(1) << GRAPHICS_TEXTURE_ID) | GRAPHICS_DRAWABLE_T;
const bits GRAPHICS_IMAGE_T = (bits(1) << GRAPHICS_IMAGE_ID) | GRAPHICS_TEXTURE_T;
const bits GRAPHICS_QUAD_T = (bits(1) << GRAPHICS_QUAD_ID) | OBJECT_T;
const bits GRAPHICS_FONT_T = (bits(1) << GRAPHICS_FONT_ID) | OBJECT_T;
const bits GRAPHICS_PARTICLE_SYSTEM_T = (bits(1) << GRAPHICS_PARTICLE_SYSTEM_ID) | GRAPHICS_DRAWABLE_T;
const bits GRAPHICS_SPRITE_BATCH_T = (bits(1) << GRAPHICS_SPRITE_BATCH_ID) | GRAPHICS_DRAWABLE_T;
const bits GRAPHICS_CANVAS_T = (bits(1) << GRAPHICS_CANVAS_ID) | GRAPHICS_TEXTURE_T;
const bits GRAPHICS_SHADER_T = (bits(1) << GRAPHICS_SHADER_ID) | OBJECT_T;
const bits GRAPHICS_MESH_T = (bits(1) << GRAPHICS_MESH_ID) | GRAPHICS_DRAWABLE_T;
// Image.
const bits IMAGE_IMAGE_DATA_T = (bits(1) << IMAGE_IMAGE_DATA_ID) | DATA_T;
const bits IMAGE_COMPRESSED_DATA_T = (bits(1) << IMAGE_COMPRESSED_DATA_ID) | DATA_T;
// Joystick.
const bits JOYSTICK_JOYSTICK_T = (bits(1) << JOYSTICK_JOYSTICK_ID) | OBJECT_T;
// Math.
const bits MATH_RANDOM_GENERATOR_T = (bits(1) << MATH_RANDOM_GENERATOR_ID) | OBJECT_T;
const bits MATH_BEZIER_CURVE_T = (bits(1) << MATH_BEZIER_CURVE_ID) | OBJECT_T;
// Audio.
const bits AUDIO_SOURCE_T = (bits(1) << AUDIO_SOURCE_ID) | OBJECT_T;
// Sound.
const bits SOUND_SOUND_DATA_T = (bits(1) << SOUND_SOUND_DATA_ID) | DATA_T;
const bits SOUND_DECODER_T = bits(1) << SOUND_DECODER_ID;
// Mouse.
const bits MOUSE_CURSOR_T = (bits(1) << MOUSE_CURSOR_ID) | OBJECT_T;
// Physics.
const bits PHYSICS_WORLD_T = (bits(1) << PHYSICS_WORLD_ID) | OBJECT_T;
const bits PHYSICS_CONTACT_T = (bits(1) << PHYSICS_CONTACT_ID) | OBJECT_T;
const bits PHYSICS_BODY_T = (bits(1) << PHYSICS_BODY_ID) | OBJECT_T;
const bits PHYSICS_FIXTURE_T = (bits(1) << PHYSICS_FIXTURE_ID) | OBJECT_T;
const bits PHYSICS_SHAPE_T = (bits(1) << PHYSICS_SHAPE_ID) | OBJECT_T;
const bits PHYSICS_CIRCLE_SHAPE_T = (bits(1) << PHYSICS_CIRCLE_SHAPE_ID) | PHYSICS_SHAPE_T;
const bits PHYSICS_POLYGON_SHAPE_T = (bits(1) << PHYSICS_POLYGON_SHAPE_ID) | PHYSICS_SHAPE_T;
const bits PHYSICS_EDGE_SHAPE_T = (bits(1) << PHYSICS_EDGE_SHAPE_ID) | PHYSICS_SHAPE_T;
const bits PHYSICS_CHAIN_SHAPE_T = (bits(1) << PHYSICS_CHAIN_SHAPE_ID) | PHYSICS_SHAPE_T;
const bits PHYSICS_JOINT_T = (bits(1) << PHYSICS_JOINT_ID) | OBJECT_T;
const bits PHYSICS_MOUSE_JOINT_T = (bits(1) << PHYSICS_MOUSE_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_DISTANCE_JOINT_T = (bits(1) << PHYSICS_DISTANCE_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_PRISMATIC_JOINT_T = (bits(1) << PHYSICS_PRISMATIC_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_REVOLUTE_JOINT_T = (bits(1) << PHYSICS_REVOLUTE_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_PULLEY_JOINT_T = (bits(1) << PHYSICS_PULLEY_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_GEAR_JOINT_T = (bits(1) << PHYSICS_GEAR_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_FRICTION_JOINT_T = (bits(1) << PHYSICS_FRICTION_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_WELD_JOINT_T = (bits(1) << PHYSICS_WELD_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_ROPE_JOINT_T = (bits(1) << PHYSICS_ROPE_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_WHEEL_JOINT_T = (bits(1) << PHYSICS_WHEEL_JOINT_ID) | PHYSICS_JOINT_T;
const bits PHYSICS_MOTOR_JOINT_T = (bits(1) << PHYSICS_MOTOR_JOINT_ID) | PHYSICS_JOINT_T;
// Thread.
const bits THREAD_THREAD_T = (bits(1) << THREAD_THREAD_ID) | OBJECT_T;
const bits THREAD_CHANNEL_T = (bits(1) << THREAD_CHANNEL_ID) | OBJECT_T;
// Modules.
const bits MODULE_FILESYSTEM_T = (bits(1) << MODULE_FILESYSTEM_ID) | MODULE_T;
const bits MODULE_GRAPHICS_T = (bits(1) << MODULE_GRAPHICS_ID) | MODULE_T;
const bits MODULE_IMAGE_T = (bits(1) << MODULE_IMAGE_ID) | MODULE_T;
const bits MODULE_SOUND_T = (bits(1) << MODULE_SOUND_ID) | MODULE_T;
/**
* Array of length TYPE_MAX_ENUM containing the flags for each love Type.
**/
extern const TypeBits *typeFlags;
bool getType(const char *in, Type &out);
bool getType(Type in, const char *&out);
bool getType(Type in, const char *&out);
} // love
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+8 -7
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -25,12 +25,13 @@ namespace love
{
// Version stuff.
const int VERSION_MAJOR = 0;
const int VERSION_MINOR = 9;
const int VERSION_REV = 2;
const char *VERSION = "0.9.2";
const char *VERSION_COMPATIBILITY[] = { VERSION, "0.9.1", "0.9.0", 0 };
const char *VERSION_CODENAME = "Baby Inspector";
#define LOVE_VERSION_STRING "0.10.0"
static const int VERSION_MAJOR = 0;
static const int VERSION_MINOR = 10;
static const int VERSION_REV = 0;
static const char *VERSION = LOVE_VERSION_STRING;
static const char *VERSION_COMPATIBILITY[] = { VERSION, 0 };
static const char *VERSION_CODENAME = "";
} // love
+3 -3
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -25,7 +25,7 @@ namespace love
Data *luax_checkdata(lua_State *L, int idx)
{
return luax_checktype<Data>(L, idx, "Data", DATA_T);
return luax_checktype<Data>(L, idx, DATA_ID);
}
int w_Data_getString(lua_State *L)
@@ -59,7 +59,7 @@ const luaL_Reg w_Data_functions[] =
int w_Data_open(lua_State *L)
{
luax_register_type(L, "Data", w_Data_functions);
luax_register_type(L, DATA_ID, w_Data_functions);
return 0;
}
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,7 +19,7 @@
#include <Box2D/Collision/Shapes/b2ChainShape.h>
#include <Box2D/Collision/Shapes/b2EdgeShape.h>
#include <new>
#include <memory.h>
#include <string.h>
b2ChainShape::~b2ChainShape()
{
@@ -17,7 +17,7 @@
*/
#include <Box2D/Collision/b2BroadPhase.h>
#include <memory.h>
#include <string.h>
b2BroadPhase::b2BroadPhase()
{
@@ -17,7 +17,7 @@
*/
#include <Box2D/Collision/b2DynamicTree.h>
#include <memory.h>
#include <string.h>
b2DynamicTree::b2DynamicTree()
{
@@ -18,7 +18,7 @@
#include <Box2D/Common/b2BlockAllocator.h>
#include <limits.h>
#include <memory.h>
#include <string.h>
#include <stddef.h>
int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] =
+1 -1
View File
@@ -19,7 +19,7 @@
#ifndef B2_GROWABLE_STACK_H
#define B2_GROWABLE_STACK_H
#include <Box2D/Common/b2Settings.h>
#include <memory.h>
#include <string.h>
/// This is a growable LIFO stack with an initial capacity of N.
/// If the stack size exceeds the initial capacity, the heap is used
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+45
View File
@@ -0,0 +1,45 @@
/*
** $Id: lprefix.h,v 1.2 2014/12/29 16:54:13 roberto Exp $
** Definitions for Lua code that must come before any other header file
** See Copyright Notice in lutf8lib.c
*/
#ifndef lprefix_h
#define lprefix_h
/*
** Allows POSIX/XSI stuff
*/
#if !defined(LUA_USE_C89) /* { */
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#elif _XOPEN_SOURCE == 0
#undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */
#endif
/*
** Allows manipulation of large files in gcc and some other compilers
*/
#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS)
#define _LARGEFILE_SOURCE 1
#define _FILE_OFFSET_BITS 64
#endif
#endif /* } */
/*
** Windows stuff
*/
#if defined(_WIN32) /* { */
#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */
#endif
#endif /* } */
#endif
+290
View File
@@ -0,0 +1,290 @@
/*
** $Id: lutf8lib.c,v 1.13 2014/11/02 19:19:04 roberto Exp $
** Standard library for UTF-8 manipulation
** Modified by the LOVE Development Team to work with Lua 5.1's API
*/
/******************************************************************************
* Copyright (C) 1994-2015 Lua.org, PUC-Rio, 2015 LOVE Development Team.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
#define lutf8lib_c
#include "lprefix.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "lutf8lib.h"
#include "lauxlib.h"
#include "lualib.h"
#define MAXUNICODE 0x10FFFF
#define iscont(p) ((*(p) & 0xC0) == 0x80)
/* from strlib */
/* translate a relative string position: negative means back from end */
static lua_Integer u_posrelat (lua_Integer pos, size_t len) {
if (pos >= 0) return pos;
else if (0u - (size_t)pos > len) return 0;
else return (lua_Integer)len + pos + 1;
}
/*
** Decode one UTF-8 sequence, returning NULL if byte sequence is invalid.
*/
static const char *utf8_decode (const char *o, int *val) {
static unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF};
const unsigned char *s = (const unsigned char *)o;
unsigned int c = s[0];
unsigned int res = 0; /* final result */
if (c < 0x80) /* ascii? */
res = c;
else {
int count = 0; /* to count number of continuation bytes */
while (c & 0x40) { /* still have continuation bytes? */
int cc = s[++count]; /* read next byte */
if ((cc & 0xC0) != 0x80) /* not a continuation byte? */
return NULL; /* invalid byte sequence */
res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */
c <<= 1; /* to test next bit */
}
res |= ((c & 0x7F) << (count * 5)); /* add first byte */
if (count > 3 || res > MAXUNICODE || res <= limits[count])
return NULL; /* invalid byte sequence */
s += count; /* skip continuation bytes read */
}
if (val) *val = res;
return (const char *)s + 1; /* +1 to include first byte */
}
/*
** utf8len(s [, i [, j]]) --> number of characters that start in the
** range [i,j], or nil + current position if 's' is not well formed in
** that interval
*/
static int utflen (lua_State *L) {
int n = 0;
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len);
luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,
"initial position out of string");
luaL_argcheck(L, --posj < (lua_Integer)len, 3,
"final position out of string");
while (posi <= posj) {
const char *s1 = utf8_decode(s + posi, NULL);
if (s1 == NULL) { /* conversion error? */
lua_pushnil(L); /* return nil ... */
lua_pushinteger(L, posi + 1); /* ... and current position */
return 2;
}
posi = s1 - s;
n++;
}
lua_pushinteger(L, n);
return 1;
}
/*
** codepoint(s, [i, [j]]) -> returns codepoints for all characters
** that start in the range [i,j]
*/
static int codepoint (lua_State *L) {
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len);
int n;
const char *se;
luaL_argcheck(L, posi >= 1, 2, "out of range");
luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of range");
if (posi > pose) return 0; /* empty interval; return no values */
n = (int)(pose - posi + 1);
if (posi + n <= pose) /* (lua_Integer -> int) overflow? */
return luaL_error(L, "string slice too long");
luaL_checkstack(L, n, "string slice too long");
n = 0;
se = s + pose;
for (s += posi - 1; s < se;) {
int code;
s = utf8_decode(s, &code);
if (s == NULL)
return luaL_error(L, "invalid UTF-8 code");
lua_pushinteger(L, code);
n++;
}
return n;
}
static void pushutfchar (lua_State *L, int arg) {
lua_Integer code = luaL_checkinteger(L, arg);
luaL_argcheck(L, 0 <= code && code <= MAXUNICODE, arg, "value out of range");
lua_pushfstring(L, "%U", (long)code);
}
/*
** utfchar(n1, n2, ...) -> char(n1)..char(n2)...
*/
static int utfchar (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
if (n == 1) /* optimize common case of single char */
pushutfchar(L, 1);
else {
int i;
luaL_Buffer b;
luaL_buffinit(L, &b);
for (i = 1; i <= n; i++) {
pushutfchar(L, i);
luaL_addvalue(&b);
}
luaL_pushresult(&b);
}
return 1;
}
/*
** offset(s, n, [i]) -> index where n-th character counting from
** position 'i' starts; 0 means character at 'i'.
*/
static int byteoffset (lua_State *L) {
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer n = luaL_checkinteger(L, 2);
lua_Integer posi = (n >= 0) ? 1 : len + 1;
posi = u_posrelat(luaL_optinteger(L, 3, posi), len);
luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3,
"position out of range");
if (n == 0) {
/* find beginning of current byte sequence */
while (posi > 0 && iscont(s + posi)) posi--;
}
else {
if (iscont(s + posi))
luaL_error(L, "initial position is a continuation byte");
if (n < 0) {
while (n < 0 && posi > 0) { /* move back */
do { /* find beginning of previous character */
posi--;
} while (posi > 0 && iscont(s + posi));
n++;
}
}
else {
n--; /* do not move for 1st character */
while (n > 0 && posi < (lua_Integer)len) {
do { /* find beginning of next character */
posi++;
} while (iscont(s + posi)); /* (cannot pass final '\0') */
n--;
}
}
}
if (n == 0) /* did it find given character? */
lua_pushinteger(L, posi + 1);
else /* no such character */
lua_pushnil(L);
return 1;
}
static int iter_aux (lua_State *L) {
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer n = lua_tointeger(L, 2) - 1;
if (n < 0) /* first iteration? */
n = 0; /* start from here */
else if (n < (lua_Integer)len) {
n++; /* skip current byte */
while (iscont(s + n)) n++; /* and its continuations */
}
if (n >= (lua_Integer)len)
return 0; /* no more codepoints */
else {
int code;
const char *next = utf8_decode(s + n, &code);
if (next == NULL || iscont(next))
return luaL_error(L, "invalid UTF-8 code");
lua_pushinteger(L, n + 1);
lua_pushinteger(L, code);
return 2;
}
}
static int iter_codes (lua_State *L) {
luaL_checkstring(L, 1);
lua_pushcfunction(L, iter_aux);
lua_pushvalue(L, 1);
lua_pushinteger(L, 0);
return 3;
}
/* pattern to match a single UTF-8 character */
#if LUA_VERSION_NUM >= 502
#define UTF8PATT "[\0-\x7F\xC2-\xF4][\x80-\xBF]*"
#else
/* lua 5.1 doesn't support literal null bytes in patterns */
#define UTF8PATT "[%z\x01-\x7F\xC2-\xF4][\x80-\xBF]*"
#endif
static struct luaL_Reg funcs[] = {
{"offset", byteoffset},
{"codepoint", codepoint},
{"char", utfchar},
{"len", utflen},
{"codes", iter_codes},
/* placeholders */
{"charpattern", NULL},
{NULL, NULL}
};
/* modified version of luaopen_utf8, designed to work with lua 5.1-5.3 */
int luaopen_luautf8 (lua_State *L) {
luaL_Reg *l;
lua_createtable(L, 0, (int) (sizeof(funcs) / sizeof(luaL_Reg)) - 1);
for (l = funcs; l->name != NULL; l++) {
if (l->func != NULL) {
lua_pushcfunction(L, l->func);
lua_setfield(L, -2, l->name);
}
}
lua_pushliteral(L, UTF8PATT);
lua_setfield(L, -2, "charpattern");
return 1;
}
+17
View File
@@ -0,0 +1,17 @@
#ifndef LUAUTF8_LUTF8LIB_H
#define LUAUTF8_LUTF8LIB_H
#ifdef __cplusplus
extern "C" {
#endif
#include "lua.h"
LUALIB_API int luaopen_luautf8(lua_State *L);
#ifdef __cplusplus
}
#endif
#endif /* LOVE_LUAUTF8_LUTF8LIB_H */
File diff suppressed because it is too large Load Diff
+59 -7
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -18,6 +18,7 @@
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "common/version.h"
#include "modules/love/love.h"
#include <SDL.h>
@@ -35,9 +36,24 @@ extern "C" {
#endif // LOVE_WINDOWS
#ifdef LOVE_MACOSX
#include "OSX.h"
#include "common/OSX.h"
#endif // LOVE_MACOSX
#ifdef LOVE_IOS
#include "common/iOS.h"
#endif
#ifdef LOVE_WINDOWS
extern "C"
{
// Prefer the higher performance GPU on Windows systems that use nvidia Optimus.
// http://developer.download.nvidia.com/devzone/devcenter/gamegraphics/files/OptimusRenderingPolicies.pdf
// TODO: Re-evaluate in the future when the average integrated GPU in Optimus
// systems is less mediocre?
LOVE_EXPORT DWORD NvOptimusEnablement = 0x00000001;
}
#endif // LOVE_WINDOWS
#ifdef LOVE_LEGENDARY_UTF8_ARGV_HACK
void get_utf8_arguments(int &argc, char **&argv)
@@ -89,6 +105,7 @@ static void get_app_arguments(int argc, char **argv, int &new_argc, char **&new_
temp_argv.push_back(std::string(argv[i]));
}
#ifdef LOVE_MACOSX
// Check for a drop file string.
std::string dropfilestr = love::osx::checkDropEvents();
if (!dropfilestr.empty())
@@ -96,15 +113,24 @@ static void get_app_arguments(int argc, char **argv, int &new_argc, char **&new_
temp_argv.insert(temp_argv.begin() + 1, dropfilestr);
}
else
#endif
{
// If it exists, add the love file in love.app/Contents/Resources/ to argv.
std::string loveResourcesPath = love::osx::getLoveInResources();
std::string loveResourcesPath;
bool fused = true;
#if defined(LOVE_MACOSX)
loveResourcesPath = love::osx::getLoveInResources();
#elif defined(LOVE_IOS)
loveResourcesPath = love::ios::getLoveInResources(fused);
#endif
if (!loveResourcesPath.empty())
{
// Run in pseudo-fused mode.
std::vector<std::string>::iterator it = temp_argv.begin();
it = temp_argv.insert(it + 1, loveResourcesPath);
temp_argv.insert(it + 1, std::string("--fused"));
// Run in pseudo-fused mode.
if (fused)
temp_argv.insert(it + 1, std::string("--fused"));
}
}
@@ -135,6 +161,21 @@ static int love_preload(lua_State *L, lua_CFunction f, const char *name)
int main(int argc, char **argv)
{
int retval = 0;
#ifdef LOVE_IOS
int orig_argc = argc;
char **orig_argv = argv;
// on iOS we should never programmatically exit the app, so we'll just
// "restart" when that is attempted. Games which use threads might cause
// some issues if the threads aren't cleaned up properly...
while (true)
{
argc = orig_argc;
argv = orig_argv;
#endif
#ifdef LOVE_LEGENDARY_UTF8_ARGV_HACK
int hack_argc = 0; char **hack_argv = 0;
get_utf8_arguments(hack_argc, hack_argv);
@@ -150,6 +191,13 @@ int main(int argc, char **argv)
argv = hack_argv;
#endif // LOVE_LEGENDARY_APP_ARGV_HACK
if (strcmp(LOVE_VERSION_STRING, love_version()) != 0)
{
printf("Version mismatch detected!\nLOVE binary is version %s\n"
"LOVE library is version %s\n", LOVE_VERSION_STRING, love_version());
return 1;
}
// Oh, you just want the version? Okay!
if (argc > 1 && strcmp(argv[1], "--version") == 0)
{
@@ -191,7 +239,7 @@ int main(int argc, char **argv)
lua_pushstring(L, "love");
lua_call(L, 1, 1); // leave the returned table on the stack.
// Add love.__exe = true.
// Add love._exe = true.
// This indicates that we're running the standalone version of love, and not
// the library version.
{
@@ -210,7 +258,6 @@ int main(int argc, char **argv)
// Call the returned boot function.
lua_call(L, 0, 1);
int retval = 0;
if (lua_isnumber(L, -1))
retval = (int) lua_tonumber(L, -1);
@@ -224,6 +271,11 @@ int main(int argc, char **argv)
delete [] hack_argv;
}
#endif // LOVE_LEGENDARY_UTF8_ARGV_HACK || LOVE_LEGENDARY_APP_ARGV_HACK
#ifdef LOVE_IOS
} // while (true)
#endif
return retval;
}
+4 -4
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -29,11 +29,11 @@ StringMap<Audio::DistanceModel, Audio::DISTANCE_MAX_ENUM>::Entry Audio::distance
{
{"none", Audio::DISTANCE_NONE},
{"inverse", Audio::DISTANCE_INVERSE},
{"inverse clamped", Audio::DISTANCE_INVERSE_CLAMPED},
{"inverseclamped", Audio::DISTANCE_INVERSE_CLAMPED},
{"linear", Audio::DISTANCE_LINEAR},
{"linear clamped", Audio::DISTANCE_LINEAR_CLAMPED},
{"linearclamped", Audio::DISTANCE_LINEAR_CLAMPED},
{"exponent", Audio::DISTANCE_EXPONENT},
{"exponent clamped", Audio::DISTANCE_EXPONENT_CLAMPED}
{"exponentclamped", Audio::DISTANCE_EXPONENT_CLAMPED}
};
StringMap<Audio::DistanceModel, Audio::DISTANCE_MAX_ENUM> Audio::distanceModels(Audio::distanceModelEntries, sizeof(Audio::distanceModelEntries));
+4 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -185,6 +185,9 @@ public:
**/
virtual void setVelocity(float *v) = 0;
virtual void setDopplerScale(float scale) = 0;
virtual float getDopplerScale() const = 0;
/**
* Begins recording audio input from the microphone.
**/
+6 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -34,6 +34,11 @@ Source::~Source()
{
}
Source::Type Source::getType() const
{
return type;
}
bool Source::getConstant(const char *in, Type &out)
{
return types.find(in, out);
+3 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -88,7 +88,6 @@ public:
virtual void setLooping(bool looping) = 0;
virtual bool isLooping() const = 0;
virtual bool isStatic() const = 0;
virtual void setMinVolume(float volume) = 0;
virtual float getMinVolume() const = 0;
@@ -103,6 +102,7 @@ public:
virtual float getMaxDistance() const = 0;
virtual int getChannels() const = 0;
virtual Type getType() const;
static bool getConstant(const char *in, Type &out);
static bool getConstant(Type in, const char *&out);
@@ -110,6 +110,7 @@ public:
static bool getConstant(Unit in, const char *&out);
protected:
Type type;
private:
+10 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -132,6 +132,15 @@ void Audio::setVelocity(float *)
{
}
void Audio::setDopplerScale(float)
{
}
float Audio::getDopplerScale() const
{
return 1.0f;
}
void Audio::record()
{
}
+4 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -67,6 +67,9 @@ public:
void getVelocity(float *v) const;
void setVelocity(float *v);
void setDopplerScale(float scale);
float getDopplerScale() const;
void record();
love::sound::SoundData *getRecordedData();
love::sound::SoundData *stopRecording(bool returnData);
+1 -6
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -170,11 +170,6 @@ bool Source::isLooping() const
return looping;
}
bool Source::isStatic() const
{
return (type == TYPE_STATIC);
}
void Source::setMinVolume(float volume)
{
this->minVolume = volume;
+1 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -66,7 +66,6 @@ public:
virtual bool isRelative() const;
void setLooping(bool looping);
bool isLooping() const;
bool isStatic() const;
virtual void setMinVolume(float volume);
virtual float getMinVolume() const;
virtual void setMaxVolume(float volume);
+12 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -256,6 +256,17 @@ void Audio::setVelocity(float *v)
alListenerfv(AL_VELOCITY, v);
}
void Audio::setDopplerScale(float scale)
{
if (scale >= 0.0f)
alDopplerFactor(scale);
}
float Audio::getDopplerScale() const
{
return alGetFloat(AL_DOPPLER_FACTOR);
}
void Audio::record()
{
if (!canRecord()) return;
+10 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -36,9 +36,14 @@
#include "thread/threads.h"
// OpenAL
#ifdef LOVE_MACOSX_USE_FRAMEWORKS // Frameworks have different include paths.
#ifdef LOVE_APPLE_USE_FRAMEWORKS // Frameworks have different include paths.
#ifdef LOVE_IOS
#include <OpenAL/alc.h>
#include <OpenAL/al.h>
#else
#include <OpenAL-Soft/alc.h>
#include <OpenAL-Soft/al.h>
#endif
#else
#include <AL/alc.h>
#include <AL/al.h>
@@ -85,6 +90,9 @@ public:
void getVelocity(float *v) const;
void setVelocity(float *v);
void setDopplerScale(float scale);
float getDopplerScale() const;
void record();
love::sound::SoundData *getRecordedData();
love::sound::SoundData *stopRecording(bool returnData);
+4 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -56,7 +56,9 @@ Pool::Pool()
// Create the mutex.
mutex = thread::newMutex();
#ifdef AL_SOFT_direct_channels
ALboolean hasext = alIsExtensionPresent("AL_SOFT_direct_channels");
#endif
// Make all sources available initially.
for (int i = 0; i < totalSources; i++)
@@ -126,7 +128,7 @@ void Pool::update()
int Pool::getSourceCount() const
{
return playing.size();
return (int) playing.size();
}
int Pool::getMaxSources() const
+9 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -32,10 +32,17 @@
#include "thread/threads.h"
// OpenAL
#ifdef LOVE_MACOSX_USE_FRAMEWORKS
#ifdef LOVE_APPLE_USE_FRAMEWORKS
#ifdef LOVE_IOS
#include <OpenAL/alc.h>
#include <OpenAL/al.h>
#include <OpenAL/oalMacOSX_OALExtensions.h>
#include <OpenAL/oalStaticBufferExtension.h>
#else
#include <OpenAL-Soft/alc.h>
#include <OpenAL-Soft/al.h>
#include <OpenAL-Soft/alext.h>
#endif
#else
#include <AL/alc.h>
#include <AL/al.h>
+136 -53
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -25,6 +25,7 @@
// STD
#include <iostream>
#include <float.h>
#include <algorithm>
namespace love
{
@@ -33,6 +34,36 @@ namespace audio
namespace openal
{
#ifdef LOVE_IOS
// OpenAL on iOS barfs if the max distance is +inf.
static const float MAX_ATTENUATION_DISTANCE = 1000000.0f;
#else
static const float MAX_ATTENUATION_DISTANCE = FLT_MAX;
#endif
class InvalidFormatException : public love::Exception
{
public:
InvalidFormatException(int channels, int bitdepth)
: Exception("%d-channel Sources with %d bits per sample are not supported.", channels, bitdepth)
{
}
};
class SpatialSupportException : public love::Exception
{
public:
SpatialSupportException()
: Exception("This spatial audio functionality is only available for mono Sources. \
Ensure the Source is not multi-channel before calling this function.")
{
}
};
StaticDataBuffer::StaticDataBuffer(ALenum format, const ALvoid *data, ALsizei size, ALsizei freq)
{
alGenBuffers(1, &buffer);
@@ -58,7 +89,7 @@ Source::Source(Pool *pool, love::sound::SoundData *soundData)
, maxVolume(1.0f)
, referenceDistance(1.0f)
, rolloffFactor(1.0f)
, maxDistance(FLT_MAX)
, maxDistance(MAX_ATTENUATION_DISTANCE)
, cone()
, offsetSamples(0)
, offsetSeconds(0)
@@ -68,7 +99,10 @@ Source::Source(Pool *pool, love::sound::SoundData *soundData)
, toLoop(0)
{
ALenum fmt = getFormat(soundData->getChannels(), soundData->getBitDepth());
staticBuffer.set(new StaticDataBuffer(fmt, soundData->getData(), soundData->getSize(), soundData->getSampleRate()));
if (fmt == 0)
throw InvalidFormatException(soundData->getChannels(), soundData->getBitDepth());
staticBuffer.set(new StaticDataBuffer(fmt, soundData->getData(), (ALsizei) soundData->getSize(), soundData->getSampleRate()));
// The buffer has a +2 retain count right now, but we want it to have +1.
staticBuffer->release();
@@ -94,7 +128,7 @@ Source::Source(Pool *pool, love::sound::Decoder *decoder)
, maxVolume(1.0f)
, referenceDistance(1.0f)
, rolloffFactor(1.0f)
, maxDistance(FLT_MAX)
, maxDistance(MAX_ATTENUATION_DISTANCE)
, cone()
, offsetSamples(0)
, offsetSeconds(0)
@@ -103,6 +137,9 @@ Source::Source(Pool *pool, love::sound::Decoder *decoder)
, decoder(decoder)
, toLoop(0)
{
if (getFormat(decoder->getChannels(), decoder->getBitDepth()) == 0)
throw InvalidFormatException(decoder->getChannels(), decoder->getBitDepth());
alGenBuffers(MAX_BUFFERS, streamBuffers);
float z[3] = {0, 0, 0};
@@ -228,13 +265,14 @@ bool Source::isPaused() const
bool Source::isFinished() const
{
return type == TYPE_STATIC ? isStopped() : isStopped() && !isLooping() && decoder->isFinished();
return type == TYPE_STATIC ? isStopped() : (isStopped() && !isLooping() && decoder->isFinished());
}
bool Source::update()
{
if (!valid)
return false;
if (type == TYPE_STATIC)
{
// Looping mode could have changed.
@@ -273,8 +311,10 @@ bool Source::update()
streamAtomic(buffer, decoder.get());
alSourceQueueBuffers(source, 1, &buffer);
}
return true;
}
return false;
}
@@ -302,9 +342,7 @@ float Source::getPitch() const
void Source::setVolume(float volume)
{
if (valid)
{
alSourcef(source, AL_GAIN, volume);
}
this->volume = volume;
}
@@ -337,9 +375,7 @@ void Source::seekAtomic(float offset, void *unit)
decoder->seek(offset);
}
else
{
alSourcef(source, AL_SAMPLE_OFFSET, offset);
}
break;
case Source::UNIT_SECONDS:
default:
@@ -350,9 +386,7 @@ void Source::seekAtomic(float offset, void *unit)
offsetSamples = offset * decoder->getSampleRate();
}
else
{
alSourcef(source, AL_SEC_OFFSET, offset);
}
break;
}
if (type == TYPE_STREAM)
@@ -406,6 +440,9 @@ float Source::tell(Source::Unit unit)
void Source::setPosition(float *v)
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
alSourcefv(source, AL_POSITION, v);
@@ -414,6 +451,9 @@ void Source::setPosition(float *v)
void Source::getPosition(float *v) const
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
alGetSourcefv(source, AL_POSITION, v);
else
@@ -422,6 +462,9 @@ void Source::getPosition(float *v) const
void Source::setVelocity(float *v)
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
alSourcefv(source, AL_VELOCITY, v);
@@ -430,6 +473,9 @@ void Source::setVelocity(float *v)
void Source::getVelocity(float *v) const
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
alGetSourcefv(source, AL_VELOCITY, v);
else
@@ -438,6 +484,9 @@ void Source::getVelocity(float *v) const
void Source::setDirection(float *v)
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
alSourcefv(source, AL_DIRECTION, v);
else
@@ -446,6 +495,9 @@ void Source::setDirection(float *v)
void Source::getDirection(float *v) const
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
alGetSourcefv(source, AL_DIRECTION, v);
else
@@ -454,8 +506,11 @@ void Source::getDirection(float *v) const
void Source::setCone(float innerAngle, float outerAngle, float outerVolume)
{
cone.innerAngle = (int) LOVE_TODEG(innerAngle);
cone.outerAngle = (int) LOVE_TODEG(outerAngle);
if (channels > 1)
throw SpatialSupportException();
cone.innerAngle = (int) LOVE_TODEG(innerAngle);
cone.outerAngle = (int) LOVE_TODEG(outerAngle);
cone.outerVolume = outerVolume;
if (valid)
@@ -468,13 +523,19 @@ void Source::setCone(float innerAngle, float outerAngle, float outerVolume)
void Source::getCone(float &innerAngle, float &outerAngle, float &outerVolume) const
{
innerAngle = LOVE_TORAD(cone.innerAngle);
outerAngle = LOVE_TORAD(cone.outerAngle);
if (channels > 1)
throw SpatialSupportException();
innerAngle = LOVE_TORAD(cone.innerAngle);
outerAngle = LOVE_TORAD(cone.outerAngle);
outerVolume = cone.outerVolume;
}
void Source::setRelative(bool enable)
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE);
@@ -483,15 +544,18 @@ void Source::setRelative(bool enable)
bool Source::isRelative() const
{
if (channels > 1)
throw SpatialSupportException();
return relative;
}
void Source::setLooping(bool looping)
void Source::setLooping(bool enable)
{
if (valid && type == TYPE_STATIC)
alSourcei(source, AL_LOOPING, looping ? AL_TRUE : AL_FALSE);
alSourcei(source, AL_LOOPING, enable ? AL_TRUE : AL_FALSE);
this->looping = looping;
looping = enable;
}
bool Source::isLooping() const
@@ -546,9 +610,7 @@ void Source::stopAtomic()
if (valid)
{
if (type == TYPE_STATIC)
{
alSourceStop(source);
}
else if (type == TYPE_STREAM)
{
alSourceStop(source);
@@ -561,8 +623,10 @@ void Source::stopAtomic()
alSourceUnqueueBuffers(source, 1, &buffer);
}
}
alSourcei(source, AL_BUFFER, AL_NONE);
}
toLoop = 0;
valid = false;
}
@@ -627,7 +691,7 @@ void Source::reset()
alSourcef(source, AL_REFERENCE_DISTANCE, referenceDistance);
alSourcef(source, AL_ROLLOFF_FACTOR, rolloffFactor);
alSourcef(source, AL_MAX_DISTANCE, maxDistance);
alSourcei(source, AL_LOOPING, isStatic() && isLooping() ? AL_TRUE : AL_FALSE);
alSourcei(source, AL_LOOPING, (type == TYPE_STATIC) && isLooping() ? AL_TRUE : AL_FALSE);
alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE);
alSourcei(source, AL_CONE_INNER_ANGLE, cone.innerAngle);
alSourcei(source, AL_CONE_OUTER_ANGLE, cone.outerAngle);
@@ -651,8 +715,22 @@ ALenum Source::getFormat(int channels, int bitDepth) const
return AL_FORMAT_STEREO8;
else if (channels == 2 && bitDepth == 16)
return AL_FORMAT_STEREO16;
else
return 0;
#ifdef AL_EXT_MCFORMATS
if (alIsExtensionPresent("AL_EXT_MCFORMATS"))
{
if (channels == 6 && bitDepth == 8)
return AL_FORMAT_51CHN8;
else if (channels == 6 && bitDepth == 16)
return AL_FORMAT_51CHN16;
else if (channels == 8 && bitDepth == 8)
return AL_FORMAT_71CHN8;
else if (channels == 8 && bitDepth == 16)
return AL_FORMAT_71CHN16;
}
#endif
return 0;
}
int Source::streamAtomic(ALuint buffer, love::sound::Decoder *d)
@@ -690,19 +768,12 @@ int Source::streamAtomic(ALuint buffer, love::sound::Decoder *d)
return decoded;
}
bool Source::isStatic() const
{
return (type == TYPE_STATIC);
}
void Source::setMinVolume(float volume)
{
if (valid)
{
alSourcef(source, AL_MIN_GAIN, volume);
}
this->minVolume = volume;
minVolume = volume;
}
float Source::getMinVolume() const
@@ -721,11 +792,9 @@ float Source::getMinVolume() const
void Source::setMaxVolume(float volume)
{
if (valid)
{
alSourcef(source, AL_MAX_GAIN, volume);
}
this->maxVolume = volume;
maxVolume = volume;
}
float Source::getMaxVolume() const
@@ -738,21 +807,25 @@ float Source::getMaxVolume() const
}
// In case the Source isn't playing.
return this->maxVolume;
return maxVolume;
}
void Source::setReferenceDistance(float distance)
{
if (valid)
{
alSourcef(source, AL_REFERENCE_DISTANCE, distance);
}
if (channels > 1)
throw SpatialSupportException();
this->referenceDistance = distance;
if (valid)
alSourcef(source, AL_REFERENCE_DISTANCE, distance);
referenceDistance = distance;
}
float Source::getReferenceDistance() const
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
{
ALfloat f;
@@ -761,21 +834,25 @@ float Source::getReferenceDistance() const
}
// In case the Source isn't playing.
return this->referenceDistance;
return referenceDistance;
}
void Source::setRolloffFactor(float factor)
{
if (valid)
{
alSourcef(source, AL_ROLLOFF_FACTOR, factor);
}
if (channels > 1)
throw SpatialSupportException();
this->rolloffFactor = factor;
if (valid)
alSourcef(source, AL_ROLLOFF_FACTOR, factor);
rolloffFactor = factor;
}
float Source::getRolloffFactor() const
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
{
ALfloat f;
@@ -784,21 +861,27 @@ float Source::getRolloffFactor() const
}
// In case the Source isn't playing.
return this->rolloffFactor;
return rolloffFactor;
}
void Source::setMaxDistance(float distance)
{
if (valid)
{
alSourcef(source, AL_MAX_DISTANCE, distance);
}
if (channels > 1)
throw SpatialSupportException();
this->maxDistance = distance;
distance = std::min(distance, MAX_ATTENUATION_DISTANCE);
if (valid)
alSourcef(source, AL_MAX_DISTANCE, distance);
maxDistance = distance;
}
float Source::getMaxDistance() const
{
if (channels > 1)
throw SpatialSupportException();
if (valid)
{
ALfloat f;
@@ -807,7 +890,7 @@ float Source::getMaxDistance() const
}
// In case the Source isn't playing.
return this->maxDistance;
return maxDistance;
}
int Source::getChannels() const
+12 -14
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -29,9 +29,14 @@
#include "sound/Decoder.h"
// OpenAL
#ifdef LOVE_MACOSX_USE_FRAMEWORKS
#ifdef LOVE_APPLE_USE_FRAMEWORKS
#ifdef LOVE_IOS
#include <OpenAL/alc.h>
#include <OpenAL/al.h>
#else
#include <OpenAL-Soft/alc.h>
#include <OpenAL-Soft/al.h>
#endif
#else
#include <AL/alc.h>
#include <AL/al.h>
@@ -105,7 +110,6 @@ public:
virtual bool isRelative() const;
void setLooping(bool looping);
bool isLooping() const;
bool isStatic() const;
virtual void setMinVolume(float volume);
virtual float getMinVolume() const;
virtual void setMaxVolume(float volume);
@@ -148,7 +152,7 @@ private:
static const unsigned int MAX_BUFFERS = 8;
ALuint streamBuffers[MAX_BUFFERS];
Object::StrongRef<StaticDataBuffer> staticBuffer;
StrongRef<StaticDataBuffer> staticBuffer;
float pitch;
float volume;
@@ -166,15 +170,9 @@ private:
struct Cone
{
int innerAngle; // degrees
int outerAngle; // degrees
float outerVolume;
Cone()
: innerAngle(360)
, outerAngle(360)
, outerVolume(0.0f)
{}
int innerAngle = 360; // degrees
int outerAngle = 360; // degrees
float outerVolume = 0.0f;
} cone;
float offsetSamples;
@@ -183,7 +181,7 @@ private:
int sampleRate;
int channels;
Object::StrongRef<love::sound::Decoder> decoder;
StrongRef<love::sound::Decoder> decoder;
unsigned int toLoop;
+27 -11
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -44,7 +44,7 @@ int w_getSourceCount(lua_State *L)
int w_newSource(lua_State *L)
{
if (lua_isstring(L, 1) || luax_istype(L, 1, FILESYSTEM_FILE_T) || luax_istype(L, 1, FILESYSTEM_FILE_DATA_T))
if (lua_isstring(L, 1) || luax_istype(L, 1, FILESYSTEM_FILE_ID) || luax_istype(L, 1, FILESYSTEM_FILE_DATA_ID))
luax_convobj(L, 1, "sound", "newDecoder");
Source::Type stype = Source::TYPE_STREAM;
@@ -53,19 +53,21 @@ int w_newSource(lua_State *L)
if (stypestr && !Source::getConstant(stypestr, stype))
return luaL_error(L, "Invalid source type: %s", stypestr);
if (stype == Source::TYPE_STATIC && luax_istype(L, 1, SOUND_DECODER_T))
if (stype == Source::TYPE_STATIC && luax_istype(L, 1, SOUND_DECODER_ID))
luax_convobj(L, 1, "sound", "newSoundData");
Source *t = 0;
if (luax_istype(L, 1, SOUND_SOUND_DATA_T))
t = instance()->newSource(luax_totype<love::sound::SoundData>(L, 1, "SoundData", SOUND_SOUND_DATA_T));
else if (luax_istype(L, 1, SOUND_DECODER_T))
t = instance()->newSource(luax_totype<love::sound::Decoder>(L, 1, "Decoder", SOUND_DECODER_T));
luax_catchexcept(L, [&]() {
if (luax_istype(L, 1, SOUND_SOUND_DATA_ID))
t = instance()->newSource(luax_totype<love::sound::SoundData>(L, 1, SOUND_SOUND_DATA_ID));
else if (luax_istype(L, 1, SOUND_DECODER_ID))
t = instance()->newSource(luax_totype<love::sound::Decoder>(L, 1, SOUND_DECODER_ID));
});
if (t)
{
luax_pushtype(L, "Source", AUDIO_SOURCE_T, t);
luax_pushtype(L, AUDIO_SOURCE_ID, t);
t->release();
return 1;
}
@@ -216,6 +218,18 @@ int w_getVelocity(lua_State *L)
return 3;
}
int w_setDopplerScale(lua_State *L)
{
instance()->setDopplerScale(luax_checkfloat(L, 1));
return 0;
}
int w_getDopplerScale(lua_State *L)
{
lua_pushnumber(L, instance()->getDopplerScale());
return 1;
}
int w_record(lua_State *)
{
instance()->record();
@@ -229,7 +243,7 @@ int w_getRecordedData(lua_State *L)
lua_pushnil(L);
else
{
luax_pushtype(L, "SoundData", SOUND_SOUND_DATA_T, sd);
luax_pushtype(L, SOUND_SOUND_DATA_ID, sd);
sd->release();
}
return 1;
@@ -244,7 +258,7 @@ int w_stopRecording(lua_State *L)
lua_pushnil(L);
else
{
luax_pushtype(L, "SoundData", SOUND_SOUND_DATA_T, sd);
luax_pushtype(L, SOUND_SOUND_DATA_ID, sd);
sd->release();
}
return 1;
@@ -297,6 +311,8 @@ static const luaL_Reg functions[] =
{ "getOrientation", w_getOrientation },
{ "setVelocity", w_setVelocity },
{ "getVelocity", w_getVelocity },
{ "setDopplerScale", w_setDopplerScale },
{ "getDopplerScale", w_getDopplerScale },
/*{ "record", w_record },
{ "getRecordedData", w_getRecordedData },
{ "stopRecording", w_stopRecording },*/
@@ -353,7 +369,7 @@ extern "C" int luaopen_love_audio(lua_State *L)
WrappedModule w;
w.module = instance;
w.name = "audio";
w.flags = MODULE_T;
w.type = MODULE_ID;
w.functions = functions;
w.types = types;
+3 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -47,6 +47,8 @@ int w_setOrientation(lua_State *L);
int w_getOrientation(lua_State *L);
int w_setVelocity(lua_State *L);
int w_getVelocity(lua_State *L);
int w_setDopplerScale(lua_State *L);
int w_getDopplerScale(lua_State *L);
int w_record(lua_State *L);
int w_getRecordedData(lua_State *L);
int w_stopRecording(lua_State *L);
+38 -28
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -29,7 +29,7 @@ namespace audio
Source *luax_checksource(lua_State *L, int idx)
{
return luax_checktype<Source>(L, idx, "Source", AUDIO_SOURCE_T);
return luax_checktype<Source>(L, idx, AUDIO_SOURCE_ID);
}
int w_Source_clone(lua_State *L)
@@ -37,7 +37,7 @@ int w_Source_clone(lua_State *L)
Source *t = luax_checksource(L, 1);
Source *clone = nullptr;
luax_catchexcept(L, [&](){ clone = t->clone(); });
luax_pushtype(L, "Source", AUDIO_SOURCE_T, clone);
luax_pushtype(L, AUDIO_SOURCE_ID, clone);
clone->release();
return 1;
}
@@ -147,7 +147,7 @@ int w_Source_setPosition(lua_State *L)
v[0] = (float)luaL_checknumber(L, 2);
v[1] = (float)luaL_checknumber(L, 3);
v[2] = (float)luaL_optnumber(L, 4, 0);
t->setPosition(v);
luax_catchexcept(L, [&](){ t->setPosition(v); });
return 0;
}
@@ -155,7 +155,7 @@ int w_Source_getPosition(lua_State *L)
{
Source *t = luax_checksource(L, 1);
float v[3];
t->getPosition(v);
luax_catchexcept(L, [&](){ t->getPosition(v); });
lua_pushnumber(L, v[0]);
lua_pushnumber(L, v[1]);
lua_pushnumber(L, v[2]);
@@ -169,7 +169,7 @@ int w_Source_setVelocity(lua_State *L)
v[0] = (float)luaL_checknumber(L, 2);
v[1] = (float)luaL_checknumber(L, 3);
v[2] = (float)luaL_optnumber(L, 4, 0);
t->setVelocity(v);
luax_catchexcept(L, [&](){ t->setVelocity(v); });
return 0;
}
@@ -177,7 +177,7 @@ int w_Source_getVelocity(lua_State *L)
{
Source *t = luax_checksource(L, 1);
float v[3];
t->getVelocity(v);
luax_catchexcept(L, [&](){ t->getVelocity(v); });
lua_pushnumber(L, v[0]);
lua_pushnumber(L, v[1]);
lua_pushnumber(L, v[2]);
@@ -191,7 +191,7 @@ int w_Source_setDirection(lua_State *L)
v[0] = (float)luaL_checknumber(L, 2);
v[1] = (float)luaL_checknumber(L, 3);
v[2] = (float)luaL_optnumber(L, 4, 0);
t->setDirection(v);
luax_catchexcept(L, [&](){ t->setDirection(v); });
return 0;
}
@@ -199,7 +199,7 @@ int w_Source_getDirection(lua_State *L)
{
Source *t = luax_checksource(L, 1);
float v[3];
t->getDirection(v);
luax_catchexcept(L, [&](){ t->getDirection(v); });
lua_pushnumber(L, v[0]);
lua_pushnumber(L, v[1]);
lua_pushnumber(L, v[2]);
@@ -212,7 +212,7 @@ int w_Source_setCone(lua_State *L)
float innerAngle = (float) luaL_checknumber(L, 2);
float outerAngle = (float) luaL_checknumber(L, 3);
float outerVolume = (float) luaL_optnumber(L, 4, 0.0);
t->setCone(innerAngle, outerAngle, outerVolume);
luax_catchexcept(L, [&](){ t->setCone(innerAngle, outerAngle, outerVolume); });
return 0;
}
@@ -220,7 +220,7 @@ int w_Source_getCone(lua_State *L)
{
Source *t = luax_checksource(L, 1);
float innerAngle, outerAngle, outerVolume;
t->getCone(innerAngle, outerAngle, outerVolume);
luax_catchexcept(L, [&](){ t->getCone(innerAngle, outerAngle, outerVolume); });
lua_pushnumber(L, innerAngle);
lua_pushnumber(L, outerAngle);
lua_pushnumber(L, outerVolume);
@@ -230,14 +230,14 @@ int w_Source_getCone(lua_State *L)
int w_Source_setRelative(lua_State *L)
{
Source *t = luax_checksource(L, 1);
t->setRelative(luax_toboolean(L, 2));
luax_catchexcept(L, [&](){ t->setRelative(luax_toboolean(L, 2)); });
return 0;
}
int w_Source_isRelative(lua_State *L)
{
Source *t = luax_checksource(L, 1);
luax_pushboolean(L, t->isRelative());
luax_catchexcept(L, [&](){ luax_pushboolean(L, t->isRelative()); });
return 1;
}
@@ -276,13 +276,6 @@ int w_Source_isPlaying(lua_State *L)
return 1;
}
int w_Source_isStatic(lua_State *L)
{
Source *t = luax_checksource(L, 1);
luax_pushboolean(L, t->isStatic());
return 1;
}
int w_Source_setVolumeLimits(lua_State *L)
{
Source *t = luax_checksource(L, 1);
@@ -310,16 +303,20 @@ int w_Source_setAttenuationDistances(lua_State *L)
float dmax = (float)luaL_checknumber(L, 3);
if (dref < .0f || dmax < .0f)
return luaL_error(L, "Invalid distances: %f, %f. Must be > 0", dref, dmax);
t->setReferenceDistance(dref);
t->setMaxDistance(dmax);
luax_catchexcept(L, [&]() {
t->setReferenceDistance(dref);
t->setMaxDistance(dmax);
});
return 0;
}
int w_Source_getAttenuationDistances(lua_State *L)
{
Source *t = luax_checksource(L, 1);
lua_pushnumber(L, t->getReferenceDistance());
lua_pushnumber(L, t->getMaxDistance());
luax_catchexcept(L, [&]() {
lua_pushnumber(L, t->getReferenceDistance());
lua_pushnumber(L, t->getMaxDistance());
});
return 2;
}
@@ -329,14 +326,14 @@ int w_Source_setRolloff(lua_State *L)
float rolloff = (float)luaL_checknumber(L, 2);
if (rolloff < .0f)
return luaL_error(L, "Invalid rolloff: %f. Must be > 0.", rolloff);
t->setRolloffFactor(rolloff);
luax_catchexcept(L, [&](){ t->setRolloffFactor(rolloff); });
return 0;
}
int w_Source_getRolloff(lua_State *L)
{
Source *t = luax_checksource(L, 1);
lua_pushnumber(L, t->getRolloffFactor());
luax_catchexcept(L, [&](){ lua_pushnumber(L, t->getRolloffFactor()); });
return 1;
}
@@ -347,6 +344,19 @@ int w_Source_getChannels(lua_State *L)
return 1;
}
int w_Source_getType(lua_State *L)
{
Source *t = luax_checksource(L, 1);
Source::Type type = t->getType();
const char *str = nullptr;
if (!Source::getConstant(type, str))
return luaL_error(L, "Unknown Source type.");
lua_pushstring(L, str);
return 1;
}
static const luaL_Reg functions[] =
{
{ "clone", w_Source_clone },
@@ -380,7 +390,6 @@ static const luaL_Reg functions[] =
{ "isStopped", w_Source_isStopped },
{ "isPaused", w_Source_isPaused },
{ "isPlaying", w_Source_isPlaying },
{ "isStatic", w_Source_isStatic },
{ "setVolumeLimits", w_Source_setVolumeLimits },
{ "getVolumeLimits", w_Source_getVolumeLimits },
@@ -390,13 +399,14 @@ static const luaL_Reg functions[] =
{ "getRolloff", w_Source_getRolloff},
{ "getChannels", w_Source_getChannels },
{ "getType", w_Source_getType },
{ 0, 0 }
};
extern "C" int luaopen_source(lua_State *L)
{
return luax_register_type(L, "Source", functions);
return luax_register_type(L, AUDIO_SOURCE_ID, functions);
}
} // audio
+2 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -57,7 +57,6 @@ int w_Source_isLooping(lua_State *L);
int w_Source_isStopped(lua_State *L);
int w_Source_isPaused(lua_State *L);
int w_Source_isPlaying(lua_State *L);
int w_Source_isStatic(lua_State *L);
int w_Source_setVolumeLimits(lua_State *L);
int w_Source_getVolumeLimits(lua_State *L);
int w_Source_setAttenuationDistances(lua_State *L);
@@ -65,6 +64,7 @@ int w_Source_getAttenuationDistances(lua_State *L);
int w_Source_setRolloff(lua_State *L);
int w_Source_getRolloff(lua_State *L);
int w_Source_getChannels(lua_State *L);
int w_Source_getType(lua_State *L);
extern "C" int luaopen_source(lua_State *L);
} // audio
+28 -27
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -28,56 +28,57 @@ namespace love
namespace event
{
Message::Message(const std::string &name, Variant *a, Variant *b, Variant *c, Variant *d)
Message::Message(const std::string &name, const std::vector<StrongRef<Variant>> &vargs)
: name(name)
, nargs(0)
, args(vargs)
{
args[0] = a;
args[1] = b;
args[2] = c;
args[3] = d;
for (int i = 0; i < 4; i++)
{
if (!args[i])
break;
args[i]->retain();
nargs++;
}
}
Message::~Message()
{
for (int i = 0; i < nargs; i++)
args[i]->release();
}
int Message::toLua(lua_State *L)
{
luax_pushstring(L, name);
for (int i = 0; i < nargs; i++)
args[i]->toLua(L);
return nargs+1;
for (const StrongRef<Variant> &v : args)
{
if (v.get() != nullptr)
v->toLua(L);
else
lua_pushnil(L);
}
return (int) args.size() + 1;
}
Message *Message::fromLua(lua_State *L, int n)
{
std::string name = luax_checkstring(L, n);
std::vector<StrongRef<Variant>> vargs;
int count = lua_gettop(L) - n;
n++;
Message *m = new Message(name);
for (int i = 0; i < 4; i++)
for (int i = 0; i < count; i++)
{
if (lua_isnoneornil(L, n+i))
break;
m->args[i] = Variant::fromLua(L, n+i);
if (!m->args[i])
vargs.push_back(Variant::fromLua(L, n+i));
if (!vargs.back().get())
{
delete m;
vargs.clear();
luaL_error(L, "Argument %d can't be stored safely\nExpected boolean, number, string or userdata.", n+i);
return NULL;
return nullptr;
}
m->nargs++;
vargs.back()->release(); // fromLua gave a +1 ref.
}
return m;
return new Message(name, vargs);
}
Event::Event()
+14 -9
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -30,27 +30,31 @@
#include "joystick/Joystick.h"
#include "thread/threads.h"
// STL
// C++
#include <queue>
#include <vector>
namespace love
{
namespace event
{
class Message : public Object
{
private:
std::string name;
Variant *args[4];
int nargs;
public:
Message(const std::string &name, Variant *a = NULL, Variant *b = NULL, Variant *c = NULL, Variant *d = NULL);
Message(const std::string &name, const std::vector<StrongRef<Variant>> &vargs = {});
~Message();
int toLua(lua_State *L);
static Message *fromLua(lua_State *L, int n);
};
private:
std::string name;
std::vector<StrongRef<Variant>> args;
}; // Message
class Event : public Module
{
@@ -66,6 +70,7 @@ public:
virtual void clear();
virtual void pump() = 0;
virtual Message *wait() = 0;
protected:
thread::Mutex *mutex;
+300 -159
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -20,10 +20,13 @@
#include "Event.h"
#include "keyboard/Keyboard.h"
#include "filesystem/DroppedFile.h"
#include "filesystem/Filesystem.h"
#include "keyboard/sdl/Keyboard.h"
#include "mouse/Mouse.h"
#include "joystick/JoystickModule.h"
#include "joystick/sdl/Joystick.h"
#include "touch/sdl/Touch.h"
#include "graphics/Graphics.h"
#include "window/Window.h"
#include "common/Exception.h"
@@ -40,16 +43,52 @@ namespace sdl
// SDL reports mouse coordinates in the window coordinate system in OS X, but
// we want them in pixel coordinates (may be different with high-DPI enabled.)
static void windowToPixelCoords(int *x, int *y)
static void windowToPixelCoords(double *x, double *y)
{
window::Window *window = Module::getInstance<window::Window>(Module::M_WINDOW);
if (window && x)
*x = (int) window->toPixels(*x);
if (window && y)
*y = (int) window->toPixels(*y);
if (window)
window->windowToPixelCoords(x, y);
}
#ifndef LOVE_MACOSX
static void normalizedToPixelCoords(double *x, double *y)
{
window::Window *window = Module::getInstance<window::Window>(Module::M_WINDOW);
int w = 1, h = 1;
if (window)
window->getPixelDimensions(w, h);
if (x)
*x = ((*x) * (double) w);
if (y)
*y = ((*y) * (double) h);
}
#endif
// SDL's event watch callbacks trigger when the event is actually posted inside
// SDL, unlike with SDL_PollEvents. This is useful for some events which require
// handling inside the function which triggered them on some backends.
static int SDLCALL watchAppEvents(void * /*udata*/, SDL_Event *event)
{
graphics::Graphics *gfx = Module::getInstance<graphics::Graphics>(Module::M_GRAPHICS);
switch (event->type)
{
// On iOS, calling any OpenGL ES function after the function which triggers
// SDL_APP_DIDENTERBACKGROUND is called will kill the app, so we handle it
// with an event watch callback, which will be called inside that function.
case SDL_APP_DIDENTERBACKGROUND:
case SDL_APP_WILLENTERFOREGROUND:
if (gfx)
gfx->setActive(event->type == SDL_APP_WILLENTERFOREGROUND);
break;
default:
break;
}
return 1;
}
const char *Event::getName() const
{
@@ -60,10 +99,13 @@ Event::Event()
{
if (SDL_InitSubSystem(SDL_INIT_EVENTS) < 0)
throw love::Exception("%s", SDL_GetError());
SDL_AddEventWatch(watchAppEvents, this);
}
Event::~Event()
{
SDL_DelEventWatch(watchAppEvents, this);
SDL_QuitSubSystem(SDL_INIT_EVENTS);
}
@@ -106,16 +148,31 @@ void Event::clear()
Message *Event::convert(const SDL_Event &e) const
{
Message *msg = NULL;
Message *msg = nullptr;
love::keyboard::Keyboard *kb = 0;
std::vector<StrongRef<Variant>> vargs;
vargs.reserve(4);
love::keyboard::Keyboard::Key key;
love::keyboard::Keyboard *kb = nullptr;
love::filesystem::Filesystem *filesystem = nullptr;
love::keyboard::Keyboard::Key key = love::keyboard::Keyboard::KEY_UNKNOWN;
love::keyboard::Keyboard::Scancode scancode = love::keyboard::Keyboard::SCANCODE_UNKNOWN;
love::mouse::Mouse::Button button;
Variant *arg1, *arg2, *arg3;
const char *txt;
const char *txt2;
std::map<SDL_Keycode, love::keyboard::Keyboard::Key>::const_iterator keyit;
#ifndef LOVE_MACOSX
love::touch::sdl::Touch *touchmodule = nullptr;
love::touch::Touch::TouchInfo touchinfo;
#endif
#ifdef LOVE_LINUX
static bool touchNormalizationBug = false;
#endif
switch (e.type)
{
case SDL_KEYDOWN:
@@ -129,83 +186,139 @@ Message *Event::convert(const SDL_Event &e) const
keyit = keys.find(e.key.keysym.sym);
if (keyit != keys.end())
key = keyit->second;
else
key = love::keyboard::Keyboard::KEY_UNKNOWN;
if (!love::keyboard::Keyboard::getConstant(key, txt))
txt = "unknown";
arg1 = new Variant(txt, strlen(txt));
arg2 = new Variant(e.key.repeat != 0);
msg = new Message("keypressed", arg1, arg2);
arg1->release();
arg2->release();
love::keyboard::sdl::Keyboard::getConstant(e.key.keysym.scancode, scancode);
if (!love::keyboard::Keyboard::getConstant(scancode, txt2))
txt2 = "unknown";
vargs.push_back(new Variant(txt, strlen(txt)));
vargs.push_back(new Variant(txt2, strlen(txt2)));
vargs.push_back(new Variant(e.key.repeat != 0));
msg = new Message("keypressed", vargs);
break;
case SDL_KEYUP:
keyit = keys.find(e.key.keysym.sym);
if (keyit != keys.end())
key = keyit->second;
else
key = love::keyboard::Keyboard::KEY_UNKNOWN;
if (!love::keyboard::Keyboard::getConstant(key, txt))
txt = "unknown";
arg1 = new Variant(txt, strlen(txt));
msg = new Message("keyreleased", arg1);
arg1->release();
love::keyboard::sdl::Keyboard::getConstant(e.key.keysym.scancode, scancode);
if (!love::keyboard::Keyboard::getConstant(scancode, txt2))
txt2 = "unknown";
vargs.push_back(new Variant(txt, strlen(txt)));
vargs.push_back(new Variant(txt2, strlen(txt2)));
msg = new Message("keyreleased", vargs);
break;
case SDL_TEXTINPUT:
txt = e.text.text;
arg1 = new Variant(txt, strlen(txt));
msg = new Message("textinput", arg1);
arg1->release();
vargs.push_back(new Variant(txt, strlen(txt)));
msg = new Message("textinput", vargs);
break;
case SDL_TEXTEDITING:
txt = e.edit.text;
arg1 = new Variant(txt, strlen(txt));
arg2 = new Variant((double) e.edit.start);
arg3 = new Variant((double) e.edit.length);
msg = new Message("textedit", arg1, arg2, arg3);
arg1->release();
arg2->release();
arg3->release();
vargs.push_back(new Variant(txt, strlen(txt)));
vargs.push_back(new Variant((double) e.edit.start));
vargs.push_back(new Variant((double) e.edit.length));
msg = new Message("textedit", vargs);
break;
case SDL_MOUSEMOTION:
{
double x = (double) e.motion.x;
double y = (double) e.motion.y;
double xrel = (double) e.motion.xrel;
double yrel = (double) e.motion.yrel;
windowToPixelCoords(&x, &y);
windowToPixelCoords(&xrel, &yrel);
vargs.push_back(new Variant(x));
vargs.push_back(new Variant(y));
vargs.push_back(new Variant(xrel));
vargs.push_back(new Variant(yrel));
vargs.push_back(new Variant(e.motion.which == SDL_TOUCH_MOUSEID));
msg = new Message("mousemoved", vargs);
}
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
if (buttons.find(e.button.button, button) && mouse::Mouse::getConstant(button, txt))
{
int x = e.button.x;
int y = e.button.y;
double x = (double) e.button.x;
double y = (double) e.button.y;
windowToPixelCoords(&x, &y);
arg1 = new Variant((double) x);
arg2 = new Variant((double) y);
arg3 = new Variant(txt, strlen(txt));
vargs.push_back(new Variant(x));
vargs.push_back(new Variant(y));
vargs.push_back(new Variant(txt, strlen(txt)));
vargs.push_back(new Variant(e.button.which == SDL_TOUCH_MOUSEID));
msg = new Message((e.type == SDL_MOUSEBUTTONDOWN) ?
"mousepressed" : "mousereleased",
arg1, arg2, arg3);
arg1->release();
arg2->release();
arg3->release();
vargs);
}
break;
case SDL_MOUSEWHEEL:
if (e.wheel.y != 0)
vargs.push_back(new Variant((double) e.wheel.x));
vargs.push_back(new Variant((double) e.wheel.y));
msg = new Message("wheelmoved", vargs);
break;
case SDL_FINGERDOWN:
case SDL_FINGERUP:
case SDL_FINGERMOTION:
// Touch events are disabled in OS X because we only actually want touch
// screen events, but most touch devices in OS X aren't touch screens
// (and SDL doesn't differentiate.) Non-screen touch devices like Mac
// trackpads won't give touch coords in the window's coordinate-space.
#ifndef LOVE_MACOSX
touchinfo.id = (int64) e.tfinger.fingerId;
touchinfo.x = e.tfinger.x;
touchinfo.y = e.tfinger.y;
touchinfo.dx = e.tfinger.dx;
touchinfo.dy = e.tfinger.dy;
#ifdef LOVE_LINUX
// FIXME: hacky workaround for SDL not normalizing touch coordinates in
// its X11 backend: https://bugzilla.libsdl.org/show_bug.cgi?id=2307
if (touchNormalizationBug || fabs(touchinfo.x) >= 1.5 || fabs(touchinfo.y) >= 1.5 || fabs(touchinfo.dx) >= 1.5 || fabs(touchinfo.dy) >= 1.5)
{
button = (e.wheel.y > 0) ? mouse::Mouse::BUTTON_WHEELUP : mouse::Mouse::BUTTON_WHEELDOWN;
if (!love::mouse::Mouse::getConstant(button, txt))
break;
int mx, my;
SDL_GetMouseState(&mx, &my);
windowToPixelCoords(&mx, &my);
arg1 = new Variant((double) mx);
arg2 = new Variant((double) my);
arg3 = new Variant(txt, strlen(txt));
msg = new Message("mousepressed", arg1, arg2, arg3);
arg1->release();
arg2->release();
arg3->release();
touchNormalizationBug = true;
windowToPixelCoords(&touchinfo.x, &touchinfo.y);
windowToPixelCoords(&touchinfo.dx, &touchinfo.dy);
}
else
#endif
{
// SDL's coords are normalized to [0, 1], but we want them in pixels.
normalizedToPixelCoords(&touchinfo.x, &touchinfo.y);
normalizedToPixelCoords(&touchinfo.dx, &touchinfo.dy);
}
// We need to update the love.touch.sdl internal state from here.
touchmodule = (touch::sdl::Touch *) Module::getInstance("love.touch.sdl");
if (touchmodule)
touchmodule->onEvent(e.type, touchinfo);
// This is a bit hackish and we lose the higher 32 bits of the id on
// 32-bit systems, but SDL only ever gives id's that at most use as many
// bits as can fit in a pointer (for now.)
// We use lightuserdata instead of a lua_Number (double) because doubles
// can't represent all possible id values on 64-bit systems.
vargs.push_back(new Variant((void *) (intptr_t) touchinfo.id));
vargs.push_back(new Variant(touchinfo.x));
vargs.push_back(new Variant(touchinfo.y));
vargs.push_back(new Variant(touchinfo.dx));
vargs.push_back(new Variant(touchinfo.dy));
if (e.type == SDL_FINGERDOWN)
txt = "touchpressed";
else if (e.type == SDL_FINGERUP)
txt = "touchreleased";
else
txt = "touchmoved";
msg = new Message(txt, vargs);
#endif
break;
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
@@ -223,15 +336,47 @@ Message *Event::convert(const SDL_Event &e) const
msg = convertWindowEvent(e);
break;
case SDL_DROPFILE:
filesystem = Module::getInstance<filesystem::Filesystem>(Module::M_FILESYSTEM);
if (filesystem != nullptr)
{
// Allow mounting any dropped path, so zips or dirs can be mounted.
filesystem->allowMountingForPath(e.drop.file);
if (filesystem->isRealDirectory(e.drop.file))
{
vargs.push_back(new Variant(e.drop.file, strlen(e.drop.file)));
msg = new Message("directorydropped", vargs);
}
else
{
Proxy proxy;
proxy.object = new love::filesystem::DroppedFile(e.drop.file);
proxy.type = FILESYSTEM_DROPPED_FILE_ID;
vargs.push_back(new Variant(proxy.type, &proxy));
msg = new Message("filedropped", vargs);
proxy.object->release();
}
}
SDL_free(e.drop.file);
break;
case SDL_QUIT:
case SDL_APP_TERMINATING:
msg = new Message("quit");
break;
case SDL_APP_LOWMEMORY:
msg = new Message("lowmemory");
break;
default:
break;
}
// We gave +1 refs to the StrongRef list, so we should release them.
for (const StrongRef<Variant> &v : vargs)
{
if (v.get() != nullptr)
v->release();
}
return msg;
}
@@ -239,66 +384,61 @@ Message *Event::convertJoystickEvent(const SDL_Event &e) const
{
joystick::JoystickModule *joymodule = Module::getInstance<joystick::JoystickModule>(Module::M_JOYSTICK);
if (!joymodule)
return 0;
return nullptr;
Message *msg = nullptr;
std::vector<StrongRef<Variant>> vargs;
vargs.reserve(4);
Message *msg = 0;
Proxy proxy;
love::joystick::Joystick::Hat hat;
love::joystick::Joystick::GamepadButton padbutton;
love::joystick::Joystick::GamepadAxis padaxis;
Variant *arg1, *arg2, *arg3;
const char *txt;
switch (e.type)
{
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
proxy.flags = JOYSTICK_JOYSTICK_T;
proxy.data = joymodule->getJoystickFromID(e.jbutton.which);
if (!proxy.data)
proxy.type = JOYSTICK_JOYSTICK_ID;
proxy.object = joymodule->getJoystickFromID(e.jbutton.which);
if (!proxy.object)
break;
arg1 = new Variant(JOYSTICK_JOYSTICK_ID, (void *) &proxy);
arg2 = new Variant((double)(e.jbutton.button+1));
vargs.push_back(new Variant(proxy.type, (void *) &proxy));
vargs.push_back(new Variant((double)(e.jbutton.button+1)));
msg = new Message((e.type == SDL_JOYBUTTONDOWN) ?
"joystickpressed" : "joystickreleased",
arg1, arg2);
arg1->release();
arg2->release();
vargs);
break;
case SDL_JOYAXISMOTION:
{
proxy.flags = JOYSTICK_JOYSTICK_T;
proxy.data = joymodule->getJoystickFromID(e.jaxis.which);
if (!proxy.data)
proxy.type = JOYSTICK_JOYSTICK_ID;
proxy.object = joymodule->getJoystickFromID(e.jaxis.which);
if (!proxy.object)
break;
arg1 = new Variant(JOYSTICK_JOYSTICK_ID, (void *) &proxy);
arg2 = new Variant((double)(e.jaxis.axis+1));
vargs.push_back(new Variant(proxy.type, (void *) &proxy));
vargs.push_back(new Variant((double)(e.jaxis.axis+1)));
float value = joystick::Joystick::clampval(e.jaxis.value / 32768.0f);
arg3 = new Variant((double) value);
msg = new Message("joystickaxis", arg1, arg2, arg3);
arg1->release();
arg2->release();
arg3->release();
vargs.push_back(new Variant((double) value));
msg = new Message("joystickaxis", vargs);
}
break;
case SDL_JOYHATMOTION:
if (!joystick::sdl::Joystick::getConstant(e.jhat.value, hat) || !joystick::Joystick::getConstant(hat, txt))
break;
proxy.flags = JOYSTICK_JOYSTICK_T;
proxy.data = joymodule->getJoystickFromID(e.jhat.which);
if (!proxy.data)
proxy.type = JOYSTICK_JOYSTICK_ID;
proxy.object = joymodule->getJoystickFromID(e.jhat.which);
if (!proxy.object)
break;
arg1 = new Variant(JOYSTICK_JOYSTICK_ID, (void *) &proxy);
arg2 = new Variant((double)(e.jhat.hat+1));
arg3 = new Variant(txt, strlen(txt));
msg = new Message("joystickhat", arg1, arg2, arg3);
arg1->release();
arg2->release();
arg3->release();
vargs.push_back(new Variant(proxy.type, (void *) &proxy));
vargs.push_back(new Variant((double)(e.jhat.hat+1)));
vargs.push_back(new Variant(txt, strlen(txt)));
msg = new Message("joystickhat", vargs);
break;
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
@@ -308,17 +448,15 @@ Message *Event::convertJoystickEvent(const SDL_Event &e) const
if (!joystick::Joystick::getConstant(padbutton, txt))
break;
proxy.flags = JOYSTICK_JOYSTICK_T;
proxy.data = joymodule->getJoystickFromID(e.cbutton.which);
if (!proxy.data)
proxy.type = JOYSTICK_JOYSTICK_ID;
proxy.object = joymodule->getJoystickFromID(e.cbutton.which);
if (!proxy.object)
break;
arg1 = new Variant(JOYSTICK_JOYSTICK_ID, (void *) &proxy);
arg2 = new Variant(txt, strlen(txt));
vargs.push_back(new Variant(proxy.type, (void *) &proxy));
vargs.push_back(new Variant(txt, strlen(txt)));
msg = new Message(e.type == SDL_CONTROLLERBUTTONDOWN ?
"gamepadpressed" : "gamepadreleased", arg1, arg2);
arg1->release();
arg2->release();
"gamepadpressed" : "gamepadreleased", vargs);
break;
case SDL_CONTROLLERAXISMOTION:
if (joystick::sdl::Joystick::getConstant((SDL_GameControllerAxis) e.caxis.axis, padaxis))
@@ -326,60 +464,65 @@ Message *Event::convertJoystickEvent(const SDL_Event &e) const
if (!joystick::Joystick::getConstant(padaxis, txt))
break;
proxy.flags = JOYSTICK_JOYSTICK_T;
proxy.data = joymodule->getJoystickFromID(e.caxis.which);
if (!proxy.data)
proxy.type = JOYSTICK_JOYSTICK_ID;
proxy.object = joymodule->getJoystickFromID(e.caxis.which);
if (!proxy.object)
break;
arg1 = new Variant(JOYSTICK_JOYSTICK_ID, (void *) &proxy);
vargs.push_back(new Variant(proxy.type, (void *) &proxy));
arg2 = new Variant(txt, strlen(txt));
vargs.push_back(new Variant(txt, strlen(txt)));
float value = joystick::Joystick::clampval(e.caxis.value / 32768.0f);
arg3 = new Variant((double) value);
msg = new Message("gamepadaxis", arg1, arg2, arg3);
arg1->release();
arg2->release();
arg3->release();
vargs.push_back(new Variant((double) value));
msg = new Message("gamepadaxis", vargs);
}
break;
case SDL_JOYDEVICEADDED:
// jdevice.which is the joystick device index.
proxy.data = joymodule->addJoystick(e.jdevice.which);
proxy.flags = JOYSTICK_JOYSTICK_T;
if (proxy.data)
proxy.object = joymodule->addJoystick(e.jdevice.which);
proxy.type = JOYSTICK_JOYSTICK_ID;
if (proxy.object)
{
arg1 = new Variant(JOYSTICK_JOYSTICK_ID, (void *) &proxy);
msg = new Message("joystickadded", arg1);
arg1->release();
vargs.push_back(new Variant(proxy.type, (void *) &proxy));
msg = new Message("joystickadded", vargs);
}
break;
case SDL_JOYDEVICEREMOVED:
// jdevice.which is the joystick instance ID now.
proxy.data = joymodule->getJoystickFromID(e.jdevice.which);
proxy.flags = JOYSTICK_JOYSTICK_T;
if (proxy.data)
proxy.object = joymodule->getJoystickFromID(e.jdevice.which);
proxy.type = JOYSTICK_JOYSTICK_ID;
if (proxy.object)
{
joymodule->removeJoystick((joystick::Joystick *) proxy.data);
arg1 = new Variant(JOYSTICK_JOYSTICK_ID, (void *) &proxy);
msg = new Message("joystickremoved", arg1);
arg1->release();
joymodule->removeJoystick((joystick::Joystick *) proxy.object);
vargs.push_back(new Variant(proxy.type, (void *) &proxy));
msg = new Message("joystickremoved", vargs);
}
break;
default:
break;
}
// We gave +1 refs to the StrongRef list, so we should release them.
for (const StrongRef<Variant> &v : vargs)
{
if (v.get() != nullptr)
v->release();
}
return msg;
}
Message *Event::convertWindowEvent(const SDL_Event &e) const
{
Message *msg = 0;
Variant *arg1, *arg2, *arg3, *arg4;
window::Window *win = 0;
Message *msg = nullptr;
std::vector<StrongRef<Variant>> vargs;
vargs.reserve(4);
window::Window *win = nullptr;
if (e.type != SDL_WINDOWEVENT)
return 0;
return nullptr;
switch (e.window.event)
{
@@ -391,53 +534,47 @@ Message *Event::convertWindowEvent(const SDL_Event &e) const
SDL_DisableScreenSaver();
else
SDL_EnableScreenSaver();
arg1 = new Variant(e.window.event == SDL_WINDOWEVENT_FOCUS_GAINED);
msg = new Message("focus", arg1);
arg1->release();
vargs.push_back(new Variant(e.window.event == SDL_WINDOWEVENT_FOCUS_GAINED));
msg = new Message("focus", vargs);
break;
case SDL_WINDOWEVENT_ENTER:
case SDL_WINDOWEVENT_LEAVE:
arg1 = new Variant(e.window.event == SDL_WINDOWEVENT_ENTER);
msg = new Message("mousefocus", arg1);
arg1->release();
vargs.push_back(new Variant(e.window.event == SDL_WINDOWEVENT_ENTER));
msg = new Message("mousefocus", vargs);
break;
case SDL_WINDOWEVENT_SHOWN:
case SDL_WINDOWEVENT_HIDDEN:
arg1 = new Variant(e.window.event == SDL_WINDOWEVENT_SHOWN);
msg = new Message("visible", arg1);
arg1->release();
vargs.push_back(new Variant(e.window.event == SDL_WINDOWEVENT_SHOWN));
msg = new Message("visible", vargs);
break;
case SDL_WINDOWEVENT_RESIZED:
win = Module::getInstance<window::Window>(Module::M_WINDOW);
if (win)
{
int px_w = e.window.data1;
int px_h = e.window.data2;
// FIXME: disabled in Linux for runtime SDL 2.0.0 compatibility.
#if SDL_VERSION_ATLEAST(2,0,1) && !defined(LOVE_LINUX)
SDL_Window *sdlwin = SDL_GetWindowFromID(e.window.windowID);
if (sdlwin)
SDL_GL_GetDrawableSize(sdlwin, &px_w, &px_h);
#endif
win->onWindowResize(e.window.data1, e.window.data2);
graphics::Graphics *gfx = Module::getInstance<graphics::Graphics>(Module::M_GRAPHICS);
if (gfx)
gfx->setViewportSize(px_w, px_h);
arg1 = new Variant((double) px_w);
arg2 = new Variant((double) px_h);
arg3 = new Variant((double) e.window.data1);
arg4 = new Variant((double) e.window.data2);
msg = new Message("resize", arg1, arg2, arg3, arg4);
arg1->release();
arg2->release();
arg3->release();
arg4->release();
vargs.push_back(new Variant((double) px_w));
vargs.push_back(new Variant((double) px_h));
vargs.push_back(new Variant((double) e.window.data1));
vargs.push_back(new Variant((double) e.window.data2));
msg = new Message("resize", vargs);
}
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
win = Module::getInstance<window::Window>(Module::M_WINDOW);
if (win)
win->onSizeChanged(e.window.data1, e.window.data2);
break;
}
// We gave +1 refs to the StrongRef list, so we should release them.
for (const StrongRef<Variant> &v : vargs)
{
if (v.get() != nullptr)
v->release();
}
return msg;
@@ -459,6 +596,7 @@ std::map<SDL_Keycode, love::keyboard::Keyboard::Key> Event::createKeyMap()
k[SDLK_EXCLAIM] = Keyboard::KEY_EXCLAIM;
k[SDLK_QUOTEDBL] = Keyboard::KEY_QUOTEDBL;
k[SDLK_HASH] = Keyboard::KEY_HASH;
k[SDLK_PERCENT] = Keyboard::KEY_PERCENT;
k[SDLK_DOLLAR] = Keyboard::KEY_DOLLAR;
k[SDLK_AMPERSAND] = Keyboard::KEY_AMPERSAND;
k[SDLK_QUOTE] = Keyboard::KEY_QUOTE;
@@ -660,11 +798,14 @@ std::map<SDL_Keycode, love::keyboard::Keyboard::Key> Event::keys = Event::create
EnumMap<love::mouse::Mouse::Button, Uint8, love::mouse::Mouse::BUTTON_MAX_ENUM>::Entry Event::buttonEntries[] =
{
{ love::mouse::Mouse::BUTTON_LEFT, SDL_BUTTON_LEFT},
{ love::mouse::Mouse::BUTTON_MIDDLE, SDL_BUTTON_MIDDLE},
{ love::mouse::Mouse::BUTTON_RIGHT, SDL_BUTTON_RIGHT},
{ love::mouse::Mouse::BUTTON_X1, SDL_BUTTON_X1},
{ love::mouse::Mouse::BUTTON_X2, SDL_BUTTON_X2},
{love::mouse::Mouse::BUTTON_LEFT, SDL_BUTTON_LEFT},
{love::mouse::Mouse::BUTTON_MIDDLE, SDL_BUTTON_MIDDLE},
{love::mouse::Mouse::BUTTON_RIGHT, SDL_BUTTON_RIGHT},
{love::mouse::Mouse::BUTTON_X1, SDL_BUTTON_X1},
{love::mouse::Mouse::BUTTON_X2, SDL_BUTTON_X2+0},
{love::mouse::Mouse::BUTTON_X3, SDL_BUTTON_X2+1},
{love::mouse::Mouse::BUTTON_X4, SDL_BUTTON_X2+2},
{love::mouse::Mouse::BUTTON_X5, SDL_BUTTON_X2+3},
};
EnumMap<love::mouse::Mouse::Button, Uint8, love::mouse::Mouse::BUTTON_MAX_ENUM> Event::buttons(Event::buttonEntries, sizeof(Event::buttonEntries));
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -23,15 +23,12 @@
// LOVE
#include "common/runtime.h"
// sdlevent
#include "Event.h"
#include "sdl/Event.h"
namespace love
{
namespace event
{
namespace sdl
{
#define instance() (Module::getInstance<Event>(Module::M_EVENT))
@@ -124,7 +121,7 @@ extern "C" int luaopen_love_event(lua_State *L)
Event *instance = instance();
if (instance == nullptr)
{
luax_catchexcept(L, [&](){ instance = new Event(); });
luax_catchexcept(L, [&](){ instance = new love::event::sdl::Event(); });
}
else
instance->retain();
@@ -132,13 +129,12 @@ extern "C" int luaopen_love_event(lua_State *L)
WrappedModule w;
w.module = instance;
w.name = "event";
w.flags = MODULE_T;
w.type = MODULE_ID;
w.functions = functions;
w.types = 0;
return luax_register_module(L, w);
}
} // sdl
} // event
} // love
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -18,8 +18,8 @@
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_EVENT_SDL_WRAP_EVENT_H
#define LOVE_EVENT_SDL_WRAP_EVENT_H
#ifndef LOVE_EVENT_WRAP_EVENT_H
#define LOVE_EVENT_WRAP_EVENT_H
// LOVE
#include "common/config.h"
@@ -29,8 +29,6 @@ namespace love
{
namespace event
{
namespace sdl
{
int w_pump(lua_State *L);
int w_poll(lua_State *L);
@@ -41,8 +39,7 @@ int w_quit(lua_State *L);
extern "C" LOVE_EXPORT int luaopen_love_event(lua_State *L);
} // sdl
} // event
} // love
#endif // LOVE_EVENT_SDL_WRAP_EVENT_H
#endif // LOVE_EVENT_WRAP_EVENT_H
+252
View File
@@ -0,0 +1,252 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
// LOVE
#include "DroppedFile.h"
#include "common/utf8.h"
// Assume POSIX or Visual Studio.
#include <sys/types.h>
#include <sys/stat.h>
#ifdef LOVE_WINDOWS
#include <wchar.h>
#else
#include <unistd.h> // POSIX.
#endif
namespace love
{
namespace filesystem
{
DroppedFile::DroppedFile(const std::string &filename)
: filename(filename)
, file(nullptr)
, mode(MODE_CLOSED)
, bufferMode(BUFFER_NONE)
, bufferSize(0)
{
}
DroppedFile::~DroppedFile()
{
if (mode != MODE_CLOSED)
close();
}
bool DroppedFile::open(Mode newmode)
{
if (newmode == MODE_CLOSED)
return true;
// File already open?
if (file != nullptr)
return false;
#ifdef LOVE_WINDOWS
// make sure non-ASCII filenames work.
std::wstring modestr = to_widestr(getModeString(newmode));
file = _wfopen(to_widestr(filename).c_str(), modestr.c_str());
#else
file = fopen(filename.c_str(), getModeString(newmode));
#endif
if (newmode == MODE_READ && file == nullptr)
throw love::Exception("Could not open file %s. Does not exist.", filename.c_str());
mode = newmode;
if (file != nullptr && !setBuffer(bufferMode, bufferSize))
{
// Revert to buffer defaults if we don't successfully set the buffer.
bufferMode = BUFFER_NONE;
bufferSize = 0;
}
return file != nullptr;
}
bool DroppedFile::close()
{
if (file == nullptr || fclose(file) != 0)
return false;
mode = MODE_CLOSED;
file = nullptr;
return true;
}
bool DroppedFile::isOpen() const
{
return mode != MODE_CLOSED && file != nullptr;
}
int64 DroppedFile::getSize()
{
#ifdef LOVE_WINDOWS
// make sure non-ASCII filenames work.
struct _stat buf;
if (_wstat(to_widestr(filename).c_str(), &buf) != 0)
return -1;
return (int64) buf.st_size;
#else
// Assume POSIX support...
struct stat buf;
if (stat(filename.c_str(), &buf) != 0)
return -1;
return (int64) buf.st_size;
#endif
}
int64 DroppedFile::read(void *dst, int64 size)
{
if (!file || mode != MODE_READ)
throw love::Exception("File is not opened for reading.");
if (size < 0)
throw love::Exception("Invalid read size.");
size_t read = fread(dst, 1, (size_t) size, file);
return (int64) read;
}
bool DroppedFile::write(const void *data, int64 size)
{
if (!file || (mode != MODE_WRITE && mode != MODE_APPEND))
throw love::Exception("File is not opened for writing.");
if (size < 0)
throw love::Exception("Invalid write size.");
int64 written = (int64) fwrite(data, 1, (size_t) size, file);
return written == size;
}
bool DroppedFile::flush()
{
if (!file || (mode != MODE_WRITE && mode != MODE_APPEND))
throw love::Exception("File is not opened for writing.");
return fflush(file) == 0;
}
bool DroppedFile::isEOF()
{
return file == nullptr || feof(file) != 0;
}
int64 DroppedFile::tell()
{
if (file == nullptr)
return -1;
return (int64) ftell(file);
}
bool DroppedFile::seek(uint64 pos)
{
return file != nullptr && fseek(file, (long) pos, SEEK_SET) == 0;
}
bool DroppedFile::setBuffer(BufferMode bufmode, int64 size)
{
if (size < 0)
return false;
if (bufmode == BUFFER_NONE)
size = 0;
// If the file isn't open, we'll make sure the buffer values are set in
// DroppedFile::open.
if (!isOpen())
{
bufferMode = bufmode;
bufferSize = size;
return true;
}
int vbufmode;
switch (bufmode)
{
case File::BUFFER_NONE:
default:
vbufmode = _IONBF;
break;
case File::BUFFER_LINE:
vbufmode = _IOLBF;
break;
case File::BUFFER_FULL:
vbufmode = _IOFBF;
break;
}
if (setvbuf(file, nullptr, vbufmode, (size_t) size) != 0)
return false;
bufferMode = bufmode;
bufferSize = size;
return true;
}
File::BufferMode DroppedFile::getBuffer(int64 &size) const
{
size = bufferSize;
return bufferMode;
}
const std::string &DroppedFile::getFilename() const
{
return filename;
}
File::Mode DroppedFile::getMode() const
{
return mode;
}
const char *DroppedFile::getModeString(Mode mode)
{
switch (mode)
{
case File::MODE_CLOSED:
default:
return "c";
case File::MODE_READ:
return "rb";
case File::MODE_WRITE:
return "wb";
case File::MODE_APPEND:
return "ab";
}
}
} // filesystem
} // love
+83
View File
@@ -0,0 +1,83 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_FILESYSTEM_DROPPED_FILE_H
#define LOVE_FILESYSTEM_DROPPED_FILE_H
// LOVE
#include "common/config.h"
#include "File.h"
// C
#include <cstdio>
namespace love
{
namespace filesystem
{
/**
* File which is created when a user drags and drops an actual file onto the
* LOVE game. Uses C's stdio. Filenames are system-dependent full paths.
**/
class DroppedFile : public File
{
public:
DroppedFile(const std::string &filename);
virtual ~DroppedFile();
// Implements File.
using File::read;
using File::write;
bool open(Mode mode) override;
bool close() override;
bool isOpen() const override;
int64 getSize() override;
int64 read(void *dst, int64 size) override;
bool write(const void *data, int64 size) override;
bool flush() override;
bool isEOF() override;
int64 tell() override;
bool seek(uint64 pos) override;
bool setBuffer(BufferMode bufmode, int64 size) override;
BufferMode getBuffer(int64 &size) const override;
Mode getMode() const override;
const std::string &getFilename() const override;
private:
static const char *getModeString(Mode mode);
std::string filename;
FILE *file;
Mode mode;
BufferMode bufferMode;
int64 bufferSize;
}; // DroppedFile
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_DROPPED_FILE_H
+67 -5
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -29,6 +29,68 @@ File::~File()
{
}
FileData *File::read(int64 size)
{
bool isopen = isOpen();
if (!isopen && !open(MODE_READ))
throw love::Exception("Could not read file %s.", getFilename().c_str());
int64 max = getSize();
int64 cur = tell();
size = (size == ALL) ? max : size;
if (size < 0)
throw love::Exception("Invalid read size.");
// Clamping because the file offset may be in a weird position.
if (cur < 0)
cur = 0;
else if (cur > max)
cur = max;
if (cur + size > max)
size = max - cur;
FileData *fileData = new FileData(size, getFilename());
int64 bytesRead = read(fileData->getData(), size);
if (bytesRead < 0 || (bytesRead == 0 && bytesRead != size))
{
delete fileData;
throw love::Exception("Could not read from file.");
}
if (bytesRead < size)
{
FileData *tmpFileData = new FileData(bytesRead, getFilename());
memcpy(tmpFileData->getData(), fileData->getData(), (size_t) bytesRead);
fileData->release();
fileData = tmpFileData;
}
if (!isopen)
close();
return fileData;
}
bool File::write(const Data *data, int64 size)
{
return write(data->getData(), (size == ALL) ? data->getSize() : size);
}
std::string File::getExtension() const
{
const std::string &filename = getFilename();
std::string::size_type idx = filename.rfind('.');
if (idx != std::string::npos)
return filename.substr(idx+1);
else
return std::string();
}
bool File::getConstant(const char *in, Mode &out)
{
return modes.find(in, out);
@@ -51,10 +113,10 @@ bool File::getConstant(BufferMode in, const char *&out)
StringMap<File::Mode, File::MODE_MAX_ENUM>::Entry File::modeEntries[] =
{
{"c", File::CLOSED},
{"r", File::READ},
{"w", File::WRITE},
{"a", File::APPEND},
{"c", File::MODE_CLOSED},
{"r", File::MODE_READ},
{"w", File::MODE_WRITE},
{"a", File::MODE_APPEND},
};
StringMap<File::Mode, File::MODE_MAX_ENUM> File::modes(File::modeEntries, sizeof(File::modeEntries));
+11 -11
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -49,10 +49,10 @@ public:
**/
enum Mode
{
CLOSED,
READ,
WRITE,
APPEND,
MODE_CLOSED,
MODE_READ,
MODE_WRITE,
MODE_APPEND,
MODE_MAX_ENUM
};
@@ -77,7 +77,7 @@ public:
/**
* Opens the file in a certain mode.
*
* @param mode READ, WRITE, APPEND.
* @param mode MODE_READ, MODE_WRITE, MODE_APPEND.
* @return True if successful, false otherwise.
**/
virtual bool open(Mode mode) = 0;
@@ -107,7 +107,7 @@ public:
* @param size The number of bytes to attempt reading, or -1 for EOF.
* @return A newly allocated Data object.
**/
virtual FileData *read(int64 size = ALL) = 0;
virtual FileData *read(int64 size = ALL);
/**
* Reads data into the destination buffer.
@@ -134,7 +134,7 @@ public:
* @param size The number of bytes to attempt writing, or -1 for everything.
* @return True of success, false otherwise.
**/
virtual bool write(const Data *data, int64 size = ALL) = 0;
virtual bool write(const Data *data, int64 size = ALL);
/**
* Flushes the currently buffered file data to disk. Only applicable in
@@ -147,7 +147,7 @@ public:
*
* @return True if EOF, false otherwise.
**/
virtual bool eof() = 0;
virtual bool isEOF() = 0;
/**
* Gets the current position in the File.
@@ -192,13 +192,13 @@ public:
* Gets the filename for this File, or empty string if none.
* @return The filename for this File.
**/
virtual std::string getFilename() const = 0;
virtual const std::string &getFilename() const = 0;
/**
* Gets the file extension for this File, or empty string if none.
* @return The file extension for this File (without the dot).
**/
virtual std::string getExtension() const = 0;
virtual std::string getExtension() const;
static bool getConstant(const char *in, Mode &out);
static bool getConstant(Mode in, const char *&out);
+11 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -30,10 +30,19 @@ namespace filesystem
{
FileData::FileData(uint64 size, const std::string &filename)
: data(new char[(size_t) size])
: data(nullptr)
, size((size_t) size)
, filename(filename)
{
try
{
data = new char[(size_t) size];
}
catch (std::bad_alloc &)
{
throw love::Exception("Out of memory.");
}
if (filename.rfind('.') != std::string::npos)
extension = filename.substr(filename.rfind('.')+1);
}
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+62
View File
@@ -0,0 +1,62 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
// LOVE
#include "Filesystem.h"
#include "common/utf8.h"
// Assume POSIX or Visual Studio.
#include <sys/types.h>
#include <sys/stat.h>
namespace love
{
namespace filesystem
{
Filesystem::Filesystem()
{
}
Filesystem::~Filesystem()
{
}
bool Filesystem::isRealDirectory(const std::string &path) const
{
#ifdef LOVE_WINDOWS
// make sure non-ASCII paths work.
struct _stat buf;
if (_wstat(to_widestr(path).c_str(), &buf) != 0)
return false;
return (buf.st_mode & _S_IFDIR) == _S_IFDIR;
#else
// Assume POSIX support...
struct stat buf;
if (stat(path.c_str(), &buf) != 0)
return false;
return S_ISDIR(buf.st_mode) != 0;
#endif
}
} // filesystem
} // love
+261
View File
@@ -0,0 +1,261 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_FILESYSTEM_FILESYSTEM_H
#define LOVE_FILESYSTEM_FILESYSTEM_H
// LOVE
#include "common/config.h"
#include "common/runtime.h"
#include "common/Module.h"
#include "common/int.h"
#include "FileData.h"
#include "File.h"
// C++
#include <string>
#include <vector>
// In Windows, we would like to use "LOVE" as the
// application folder, but in Linux, we like .love.
#define LOVE_APPDATA_PREFIX ""
#ifdef LOVE_WINDOWS
# define LOVE_APPDATA_FOLDER "LOVE"
# define LOVE_PATH_SEPARATOR "/"
# define LOVE_MAX_PATH _MAX_PATH
#else
# if defined(LOVE_MACOSX) || defined(LOVE_IOS)
# define LOVE_APPDATA_FOLDER "LOVE"
# elif defined(LOVE_LINUX)
# define LOVE_APPDATA_FOLDER "love"
# else
# define LOVE_APPDATA_PREFIX "."
# define LOVE_APPDATA_FOLDER "love"
# endif
# define LOVE_PATH_SEPARATOR "/"
# define LOVE_MAX_PATH MAXPATHLEN
#endif
namespace love
{
namespace filesystem
{
class Filesystem : public Module
{
public:
Filesystem();
virtual ~Filesystem();
// Implements Module.
virtual ModuleType getModuleType() const { return M_FILESYSTEM; }
virtual void init(const char *arg0) = 0;
virtual void setFused(bool fused) = 0;
virtual bool isFused() const = 0;
/**
* This sets up the save directory. If the
* it is already set up, nothing happens.
* @return True on success, false otherwise.
**/
virtual bool setupWriteDirectory() = 0;
/**
* Sets the name of the save folder.
* @param ident The name of the game. Will be used to
* to create the folder in the LOVE data folder.
**/
virtual bool setIdentity(const char *ident, bool appendToPath = false) = 0;
virtual const char *getIdentity() const = 0;
/**
* Sets the path to the game source.
* This can only be set once.
* @param source Path to a directory or a .love-file.
**/
virtual bool setSource(const char *source) = 0;
/**
* Gets the path to the game source.
* Returns a 0-length string if the source has not been set.
**/
virtual const char *getSource() const = 0;
virtual bool mount(const char *archive, const char *mountpoint, bool appendToPath = false) = 0;
virtual bool unmount(const char *archive) = 0;
/**
* Creates a new file.
**/
virtual File *newFile(const char *filename) const = 0;
/**
* Creates a new FileData object. Data will be copied.
* @param data Pointer to the data.
* @param size The size of the data.
* @param filename The full filename used to file type identification.
**/
virtual FileData *newFileData(void *data, unsigned int size, const char *filename) const = 0;
/**
* Creates a new FileData object from base64 data.
* @param b64 The base64 data.
**/
virtual FileData *newFileData(const char *b64, const char *filename) const = 0;
/**
* Gets the current working directory.
**/
virtual const char *getWorkingDirectory() = 0;
/**
* Gets the user home directory.
**/
virtual std::string getUserDirectory() = 0;
/**
* Gets the APPDATA directory. On Windows, this is the folder
* in the %APPDATA% enviroment variable. On Linux, this is the
* user home folder.
**/
virtual std::string getAppdataDirectory() = 0;
/**
* Gets the full path of the save folder.
**/
virtual const char *getSaveDirectory() = 0;
/**
* Gets the full path to the directory containing the game source.
* For example if the game source is C:\Games\mygame.love, this will return
* C:\Games.
**/
virtual std::string getSourceBaseDirectory() const = 0;
/**
* Gets the real directory path containing the file.
**/
virtual std::string getRealDirectory(const char *filename) const = 0;
/**
* Checks if a path is a directory.
* @param dir The directory name to check.
**/
virtual bool isDirectory(const char *dir) const = 0;
/**
* Checks if a filename exists.
* @param file The filename to check.
**/
virtual bool isFile(const char *file) const = 0;
/**
* Creates a directory. Write dir must be set.
* @param dir The directory to create.
**/
virtual bool createDirectory(const char *dir) = 0;
/**
* Removes a file (or directory).
* @param file The file or directory to remove.
**/
virtual bool remove(const char *file) = 0;
/**
* Reads data from a file.
* @param filename The name of the file to read from.
* @param size The size in bytes of the data to read.
**/
virtual FileData *read(const char *filename, int64 size = File::ALL) const = 0;
/**
* Write data to a file.
* @param filename The name of the file to write to.
* @param data The data to write.
* @param size The size in bytes of the data to write.
**/
virtual void write(const char *filename, const void *data, int64 size) const = 0;
/**
* Append data to a file, creating it if it doesn't exist.
* @param filename The name of the file to write to.
* @param data The data to append.
* @param size The size in bytes of the data to append.
**/
virtual void append(const char *filename, const void *data, int64 size) const = 0;
/**
* This "native" method returns a table of all
* files in a given directory.
**/
virtual int getDirectoryItems(lua_State *L) = 0;
/**
* Gets the last modification time of a file, in seconds
* since the Unix epoch.
* @param filename The name of the file.
**/
virtual int64 getLastModified(const char *filename) const = 0;
/**
* Gets the size of a file in bytes.
* @param filename The name of the file.
**/
virtual int64 getSize(const char *filename) const = 0;
/**
* Enable or disable symbolic link support in love.filesystem.
**/
virtual void setSymlinksEnabled(bool enable) = 0;
/**
* Gets whether symbolic link support is enabled.
**/
virtual bool areSymlinksEnabled() const = 0;
/**
* Gets whether a filepath is actually a symlink.
* Always returns false if symlinks are not enabled.
**/
virtual bool isSymlink(const char *filename) const = 0;
// Require path accessors
// Not const because it's R/W
virtual std::vector<std::string> &getRequirePath() = 0;
/**
* Allows a full (OS-dependent) path to be used with Filesystem::mount.
**/
virtual void allowMountingForPath(const std::string &path) = 0;
/**
* Gets whether the given full (OS-dependent) path is a directory.
**/
virtual bool isRealDirectory(const std::string &path) const;
}; // Filesystem
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_FILESYSTEM_H
+33 -100
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -39,8 +39,8 @@ namespace physfs
File::File(const std::string &filename)
: filename(filename)
, file(0)
, mode(CLOSED)
, file(nullptr)
, mode(MODE_CLOSED)
, bufferMode(BUFFER_NONE)
, bufferSize(0)
{
@@ -48,25 +48,25 @@ File::File(const std::string &filename)
File::~File()
{
if (mode != CLOSED)
if (mode != MODE_CLOSED)
close();
}
bool File::open(Mode mode)
{
if (mode == CLOSED)
if (mode == MODE_CLOSED)
return true;
// File must exist if read mode.
if ((mode == READ) && !PHYSFS_exists(filename.c_str()))
if ((mode == MODE_READ) && !PHYSFS_exists(filename.c_str()))
throw love::Exception("Could not open file %s. Does not exist.", filename.c_str());
// Check whether the write directory is set.
if ((mode == APPEND || mode == WRITE) && (PHYSFS_getWriteDir() == 0) && !hack_setupWriteDirectory())
if ((mode == MODE_APPEND || mode == MODE_WRITE) && (PHYSFS_getWriteDir() == 0) && !hack_setupWriteDirectory())
throw love::Exception("Could not set write directory.");
// File already open?
if (file != 0)
if (file != nullptr)
return false;
PHYSFS_getLastError(); // Clear the error buffer.
@@ -74,13 +74,13 @@ bool File::open(Mode mode)
switch (mode)
{
case READ:
case MODE_READ:
handle = PHYSFS_openRead(filename.c_str());
break;
case APPEND:
case MODE_APPEND:
handle = PHYSFS_openAppend(filename.c_str());
break;
case WRITE:
case MODE_WRITE:
handle = PHYSFS_openWrite(filename.c_str());
break;
default:
@@ -99,94 +99,50 @@ bool File::open(Mode mode)
this->mode = mode;
if (file != 0 && !setBuffer(bufferMode, bufferSize))
if (file != nullptr && !setBuffer(bufferMode, bufferSize))
{
// Revert to buffer defaults if we don't successfully set the buffer.
bufferMode = BUFFER_NONE;
bufferSize = 0;
}
return (file != 0);
return (file != nullptr);
}
bool File::close()
{
if (!PHYSFS_close(file))
if (file == nullptr || !PHYSFS_close(file))
return false;
mode = CLOSED;
file = 0;
mode = MODE_CLOSED;
file = nullptr;
return true;
}
bool File::isOpen() const
{
return mode != CLOSED && file != 0;
return mode != MODE_CLOSED && file != nullptr;
}
int64 File::getSize()
{
// If the file is closed, open it to
// check the size.
if (file == 0)
if (file == nullptr)
{
open(READ);
int64 size = (int64)PHYSFS_fileLength(file);
open(MODE_READ);
int64 size = (int64) PHYSFS_fileLength(file);
close();
return size;
}
return (int64)PHYSFS_fileLength(file);
}
FileData *File::read(int64 size)
{
bool isOpen = (file != 0);
if (!isOpen && !open(READ))
throw love::Exception("Could not read file %s.", filename.c_str());
int64 max = getSize();
int64 cur = tell();
size = (size == ALL) ? max : size;
if (size < 0)
throw love::Exception("Invalid read size.");
// Clamping because the file offset may be in a weird position.
if (cur < 0)
cur = 0;
else if (cur > max)
cur = max;
if (cur + size > max)
size = max - cur;
FileData *fileData = new FileData(size, getFilename());
int64 bytesRead = read(fileData->getData(), size);
if (bytesRead < 0 || (bytesRead == 0 && bytesRead != size))
{
delete fileData;
throw love::Exception("Could not read from file.");
}
if (bytesRead < size)
{
FileData *tmpFileData = new FileData(bytesRead, getFilename());
memcpy(tmpFileData->getData(), fileData->getData(), (size_t) bytesRead);
delete fileData;
fileData = tmpFileData;
}
if (!isOpen)
close();
return fileData;
return (int64) PHYSFS_fileLength(file);
}
int64 File::read(void *dst, int64 size)
{
if (!file || mode != READ)
if (!file || mode != MODE_READ)
throw love::Exception("File is not opened for reading.");
int64 max = (int64)PHYSFS_fileLength(file);
@@ -205,7 +161,7 @@ int64 File::read(void *dst, int64 size)
bool File::write(const void *data, int64 size)
{
if (!file || (mode != WRITE && mode != APPEND))
if (!file || (mode != MODE_WRITE && mode != MODE_APPEND))
throw love::Exception("File is not opened for writing.");
// Another clamp, for the time being.
@@ -215,7 +171,7 @@ bool File::write(const void *data, int64 size)
throw love::Exception("Invalid write size.");
// Try to write.
int64 written = static_cast<int64>(PHYSFS_write(file, data, 1, (PHYSFS_uint32) size));
int64 written = (int64) PHYSFS_write(file, data, 1, (PHYSFS_uint32) size);
// Check that correct amount of data was written.
if (written != size)
@@ -231,14 +187,9 @@ bool File::write(const void *data, int64 size)
return true;
}
bool File::write(const Data *data, int64 size)
{
return write(data->getData(), (size == ALL) ? data->getSize() : size);
}
bool File::flush()
{
if (!file || (mode != WRITE && mode != APPEND))
if (!file || (mode != MODE_WRITE && mode != MODE_APPEND))
throw love::Exception("File is not opened for writing.");
return PHYSFS_flush(file) != 0;
@@ -261,16 +212,14 @@ inline bool test_eof(File *, PHYSFS_File *file)
}
#endif
bool File::eof()
bool File::isEOF()
{
if (file == 0 || test_eof(this, file))
return true;
return false;
return file == nullptr || test_eof(this, file);
}
int64 File::tell()
{
if (file == 0)
if (file == nullptr)
return -1;
return (int64) PHYSFS_tell(file);
@@ -278,23 +227,17 @@ int64 File::tell()
bool File::seek(uint64 pos)
{
if (file == 0)
return false;
if (!PHYSFS_seek(file, (PHYSFS_uint64) pos))
return false;
return true;
return file != nullptr && PHYSFS_seek(file, (PHYSFS_uint64) pos) != 0;
}
bool File::setBuffer(BufferMode bufmode, int64 size)
{
// No negativity allowed!
if (size < 0)
return false;
// If the file isn't open, we'll make sure the buffer values are set in
// File::open.
if (file == 0 || mode == CLOSED)
if (!isOpen())
{
bufferMode = bufmode;
bufferSize = size;
@@ -331,21 +274,11 @@ File::BufferMode File::getBuffer(int64 &size) const
return bufferMode;
}
std::string File::getFilename() const
const std::string &File::getFilename() const
{
return filename;
}
std::string File::getExtension() const
{
std::string::size_type idx = filename.rfind('.');
if (idx != std::string::npos)
return filename.substr(idx+1);
else
return std::string();
}
filesystem::File::Mode File::getMode() const
{
return mode;
+18 -19
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -25,7 +25,7 @@
#include "filesystem/File.h"
// PhysFS
#ifdef LOVE_MACOSX_USE_FRAMEWORKS
#ifdef LOVE_APPLE_USE_FRAMEWORKS
#include <physfs/physfs.h>
#else
#include <physfs.h>
@@ -54,23 +54,22 @@ public:
virtual ~File();
// Implements love::filesystem::File.
bool open(Mode mode);
bool close();
bool isOpen() const;
int64 getSize();
FileData *read(int64 size = ALL);
int64 read(void *dst, int64 size);
bool write(const void *data, int64 size);
bool write(const Data *data, int64 size = ALL);
bool flush();
bool eof();
int64 tell();
bool seek(uint64 pos);
bool setBuffer(BufferMode bufmode, int64 size);
BufferMode getBuffer(int64 &size) const;
Mode getMode() const;
std::string getFilename() const;
std::string getExtension() const;
using love::filesystem::File::read;
using love::filesystem::File::write;
bool open(Mode mode) override;
bool close() override;
bool isOpen() const override;
int64 getSize() override;
virtual int64 read(void *dst, int64 size) override;
bool write(const void *data, int64 size) override;
bool flush() override;
bool isEOF() override;
int64 tell() override;
bool seek(uint64 pos) override;
bool setBuffer(BufferMode bufmode, int64 size) override;
BufferMode getBuffer(int64 &size) const override;
Mode getMode() const override;
const std::string &getFilename() const override;
private:
+78 -134
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -18,15 +18,37 @@
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "common/config.h"
#include <iostream>
#include <sstream>
#include <algorithm>
#include "common/utf8.h"
#include "common/b64.h"
#include "Filesystem.h"
#include "File.h"
// PhysFS
#ifdef LOVE_APPLE_USE_FRAMEWORKS
#include <physfs/physfs.h>
#else
#include <physfs.h>
#endif
// For great CWD. (Current Working Directory)
// Using this instead of boost::filesystem which totally
// cramped our style.
#ifdef LOVE_WINDOWS
# include <windows.h>
# include <direct.h>
#else
# include <sys/param.h>
# include <unistd.h>
#endif
#ifdef LOVE_IOS
# include "common/iOS.h"
#endif
namespace
{
@@ -73,15 +95,15 @@ namespace physfs
{
Filesystem::Filesystem()
: initialized(false)
, fused(false)
: fused(false)
, fusedSet(false)
{
requirePath = {"?.lua", "?/init.lua"};
}
Filesystem::~Filesystem()
{
if (initialized)
if (PHYSFS_isInit())
PHYSFS_deinit();
}
@@ -93,8 +115,14 @@ const char *Filesystem::getName() const
void Filesystem::init(const char *arg0)
{
if (!PHYSFS_init(arg0))
throw Exception(PHYSFS_getLastError());
initialized = true;
throw love::Exception("%s", PHYSFS_getLastError());
PHYSFS_Version version = {};
PHYSFS_getLinkedVersion(&version);
// FIXME: This is a workaround for a bug in PHYSFS_enumerateFiles in 2.1-alpha.
if (version.major == 2 && version.minor == 1)
PHYSFS_permitSymbolicLinks(1);
}
void Filesystem::setFused(bool fused)
@@ -114,7 +142,7 @@ bool Filesystem::isFused() const
bool Filesystem::setIdentity(const char *ident, bool appendToPath)
{
if (!initialized)
if (!PHYSFS_isInit())
return false;
std::string old_save_path = save_path_full;
@@ -146,7 +174,7 @@ bool Filesystem::setIdentity(const char *ident, bool appendToPath)
// Try to add the save directory to the search path.
// (No error on fail, it means that the path doesn't exist).
PHYSFS_addToSearchPath(save_path_full.c_str(), appendToPath);
PHYSFS_mount(save_path_full.c_str(), nullptr, appendToPath);
// HACK: This forces setupWriteDirectory to be called the next time a file
// is opened for writing - otherwise it won't be called at all if it was
@@ -163,7 +191,7 @@ const char *Filesystem::getIdentity() const
bool Filesystem::setSource(const char *source)
{
if (!initialized)
if (!PHYSFS_isInit())
return false;
// Check whether directory is already set.
@@ -171,7 +199,7 @@ bool Filesystem::setSource(const char *source)
return false;
// Add the directory.
if (!PHYSFS_addToSearchPath(source, 1))
if (!PHYSFS_mount(source, nullptr, 1))
return false;
// Save the game source.
@@ -187,7 +215,7 @@ const char *Filesystem::getSource() const
bool Filesystem::setupWriteDirectory()
{
if (!initialized)
if (!PHYSFS_isInit())
return false;
// These must all be set.
@@ -232,7 +260,7 @@ bool Filesystem::setupWriteDirectory()
return false;
// Add the directory. (Will not be readded if already present).
if (!PHYSFS_addToSearchPath(save_path_full.c_str(), 0))
if (!PHYSFS_mount(save_path_full.c_str(), nullptr, 0))
{
PHYSFS_setWriteDir(nullptr); // Clear the write directory in case of error.
return false;
@@ -243,13 +271,18 @@ bool Filesystem::setupWriteDirectory()
bool Filesystem::mount(const char *archive, const char *mountpoint, bool appendToPath)
{
if (!initialized || !archive)
if (!PHYSFS_isInit() || !archive)
return false;
std::string realPath;
std::string sourceBase = getSourceBaseDirectory();
if (isFused() && sourceBase.compare(archive) == 0)
// Check whether the given archive path is in the list of allowed full paths.
auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
if (it != allowedMountPaths.end())
realPath = *it;
else if (isFused() && sourceBase.compare(archive) == 0)
{
// Special case: if the game is fused and the archive is the source's
// base directory, mount it even though it's outside of the save dir.
@@ -284,13 +317,18 @@ bool Filesystem::mount(const char *archive, const char *mountpoint, bool appendT
bool Filesystem::unmount(const char *archive)
{
if (!initialized || !archive)
if (!PHYSFS_isInit() || !archive)
return false;
std::string realPath;
std::string sourceBase = getSourceBaseDirectory();
if (isFused() && sourceBase.compare(archive) == 0)
// Check whether the given archive path is in the list of allowed full paths.
auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
if (it != allowedMountPaths.end())
realPath = *it;
else if (isFused() && sourceBase.compare(archive) == 0)
{
// Special case: if the game is fused and the archive is the source's
// base directory, unmount it even though it's outside of the save dir.
@@ -318,7 +356,7 @@ bool Filesystem::unmount(const char *archive)
return PHYSFS_removeFromSearchPath(realPath.c_str());
}
File *Filesystem::newFile(const char *filename) const
love::filesystem::File *Filesystem::newFile(const char *filename) const
{
return new File(filename);
}
@@ -335,7 +373,7 @@ FileData *Filesystem::newFileData(void *data, unsigned int size, const char *fil
FileData *Filesystem::newFileData(const char *b64, const char *filename) const
{
int size = strlen(b64);
int size = (int) strlen(b64);
int outsize = 0;
char *dst = b64_decode(b64, size, outsize);
FileData *fd = new FileData(outsize, std::string(filename));
@@ -388,6 +426,8 @@ std::string Filesystem::getAppdataDirectory()
std::string udir = getUserDirectory();
udir.append("/Library/Application Support");
appdata = normalize(udir);
#elif defined(LOVE_IOS)
appdata = normalize(love::ios::getAppdataDirectory());
#elif defined(LOVE_LINUX)
char *xdgdatahome = getenv("XDG_DATA_HOME");
if (!xdgdatahome)
@@ -443,19 +483,14 @@ std::string Filesystem::getRealDirectory(const char *filename) const
return std::string(dir);
}
bool Filesystem::exists(const char *file) const
bool Filesystem::isDirectory(const char *dir) const
{
return PHYSFS_exists(file);
}
bool Filesystem::isDirectory(const char *file) const
{
return PHYSFS_isDirectory(file);
return PHYSFS_isDirectory(dir);
}
bool Filesystem::isFile(const char *file) const
{
return exists(file) && !isDirectory(file);
return PHYSFS_exists(file) && !PHYSFS_isDirectory(file);
}
bool Filesystem::createDirectory(const char *dir)
@@ -478,11 +513,11 @@ bool Filesystem::remove(const char *file)
return true;
}
Data *Filesystem::read(const char *filename, int64 size) const
FileData *Filesystem::read(const char *filename, int64 size) const
{
File file(filename);
file.open(File::READ);
file.open(File::MODE_READ);
// close() is called in the File destructor.
return file.read(size);
@@ -492,7 +527,7 @@ void Filesystem::write(const char *filename, const void *data, int64 size) const
{
File file(filename);
file.open(File::WRITE);
file.open(File::MODE_WRITE);
// close() is called in the File destructor.
if (!file.write(data, size))
@@ -503,7 +538,7 @@ void Filesystem::append(const char *filename, const void *data, int64 size) cons
{
File file(filename);
file.open(File::APPEND);
file.open(File::MODE_APPEND);
// close() is called in the File destructor.
if (!file.write(data, size))
@@ -542,108 +577,6 @@ int Filesystem::getDirectoryItems(lua_State *L)
return 1;
}
int Filesystem::lines_i(lua_State *L)
{
const int bufsize = 1024;
char buf[bufsize];
int linesize = 0;
bool newline = false;
File *file = luax_checktype<File>(L, lua_upvalueindex(1), "File", FILESYSTEM_FILE_T);
// Only accept read mode at this point.
if (file->getMode() != File::READ)
return luaL_error(L, "File needs to stay in read mode.");
int64 pos = file->tell();
int64 userpos = -1;
if (lua_isnoneornil(L, lua_upvalueindex(2)) == 0)
{
// User may have changed the file position.
userpos = pos;
pos = (int64) lua_tonumber(L, lua_upvalueindex(2));
if (userpos != pos)
file->seek(pos);
}
while (!newline && !file->eof())
{
// This 64-bit to 32-bit integer cast should be safe as it never exceeds bufsize.
int read = (int) file->read(buf, bufsize);
if (read < 0)
return luaL_error(L, "Could not read from file.");
linesize += read;
for (int i = 0; i < read; i++)
{
if (buf[i] == '\n')
{
linesize -= read - i;
newline = true;
break;
}
}
}
if (newline || (file->eof() && linesize > 0))
{
if (linesize < bufsize)
{
// We have the line in the buffer on the stack. No 'new' and 'read' needed.
lua_pushlstring(L, buf, linesize > 0 && buf[linesize - 1] == '\r' ? linesize - 1 : linesize);
if (userpos < 0)
file->seek(pos + linesize + 1);
}
else
{
char *str = 0;
try
{
str = new char[linesize + 1];
}
catch(std::bad_alloc &)
{
// Can't lua_error (longjmp) in exception handlers.
}
if (!str)
return luaL_error(L, "Out of memory.");
file->seek(pos);
// Read the \n anyway and save us a call to seek.
if (file->read(str, linesize + 1) == -1)
{
delete [] str;
return luaL_error(L, "Could not read from file.");
}
lua_pushlstring(L, str, str[linesize - 1] == '\r' ? linesize - 1 : linesize);
delete [] str;
}
if (userpos >= 0)
{
// Save new position in upvalue.
lua_pushnumber(L, (lua_Number)(pos + linesize + 1));
lua_replace(L, lua_upvalueindex(2));
file->seek(userpos);
}
return 1;
}
// EOF reached.
if (userpos >= 0 && luax_toboolean(L, lua_upvalueindex(3)))
file->seek(userpos);
else
file->close();
return 0;
}
int64 Filesystem::getLastModified(const char *filename) const
{
PHYSFS_sint64 time = PHYSFS_getLastModTime(filename);
@@ -676,6 +609,17 @@ bool Filesystem::isSymlink(const char *filename) const
return PHYSFS_isSymbolicLink(filename) != 0;
}
std::vector<std::string> &Filesystem::getRequirePath()
{
return requirePath;
}
void Filesystem::allowMountingForPath(const std::string &path)
{
if (std::find(allowedMountPaths.begin(), allowedMountPaths.end(), path) == allowedMountPaths.end())
allowedMountPaths.push_back(path);
}
} // physfs
} // filesystem
} // love
+13 -181
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -24,46 +24,9 @@
// STD
#include <cstdlib>
#include <cstring>
#include <string>
// LOVE
#include "common/Module.h"
#include "common/config.h"
#include "common/int.h"
#include "common/runtime.h"
#include "filesystem/FileData.h"
#include "File.h"
// For great CWD. (Current Working Directory)
// Using this instead of boost::filesystem which totally
// cramped our style.
#ifdef LOVE_WINDOWS
# include <windows.h>
# include <direct.h>
#else
# include <sys/param.h>
# include <unistd.h>
#endif
// In Windows, we would like to use "LOVE" as the
// application folder, but in Linux, we like .love.
#define LOVE_APPDATA_PREFIX ""
#ifdef LOVE_WINDOWS
# define LOVE_APPDATA_FOLDER "LOVE"
# define LOVE_PATH_SEPARATOR "/"
# define LOVE_MAX_PATH _MAX_PATH
#else
# ifdef LOVE_MACOSX
# define LOVE_APPDATA_FOLDER "LOVE"
# elif defined(LOVE_LINUX)
# define LOVE_APPDATA_FOLDER "love"
# else
# define LOVE_APPDATA_PREFIX "."
# define LOVE_APPDATA_FOLDER "love"
# endif
# define LOVE_PATH_SEPARATOR "/"
# define LOVE_MAX_PATH MAXPATHLEN
#endif
#include "filesystem/Filesystem.h"
namespace love
{
@@ -72,7 +35,7 @@ namespace filesystem
namespace physfs
{
class Filesystem : public Module
class Filesystem : public love::filesystem::Filesystem
{
public:
@@ -80,7 +43,6 @@ public:
virtual ~Filesystem();
// Implements Module.
virtual ModuleType getModuleType() const { return M_FILESYSTEM; }
const char *getName() const;
void init(const char *arg0);
@@ -88,186 +50,54 @@ public:
void setFused(bool fused);
bool isFused() const;
/**
* This sets up the save directory. If the
* it is already set up, nothing happens.
* @return True on success, false otherwise.
**/
bool setupWriteDirectory();
/**
* Sets the name of the save folder.
* @param ident The name of the game. Will be used to
* to create the folder in the LOVE data folder.
**/
bool setIdentity(const char *ident, bool appendToPath = false);
const char *getIdentity() const;
/**
* Sets the path to the game source.
* This can only be set once.
* @param source Path to a directory or a .love-file.
**/
bool setSource(const char *source);
/**
* Gets the path to the game source.
* Returns a 0-length string if the source has not been set.
**/
const char *getSource() const;
bool mount(const char *archive, const char *mountpoint, bool appendToPath = false);
bool unmount(const char *archive);
/**
* Creates a new file.
**/
File *newFile(const char *filename) const;
/**
* Creates a new FileData object. Data will be copied.
* @param data Pointer to the data.
* @param size The size of the data.
* @param filename The full filename used to file type identification.
**/
FileData *newFileData(void *data, unsigned int size, const char *filename) const;
/**
* Creates a new FileData object from base64 data.
* @param b64 The base64 data.
**/
FileData *newFileData(const char *b64, const char *filename) const;
/**
* Gets the current working directory.
**/
const char *getWorkingDirectory();
/**
* Gets the user home directory.
**/
std::string getUserDirectory();
/**
* Gets the APPDATA directory. On Windows, this is the folder
* in the %APPDATA% enviroment variable. On Linux, this is the
* user home folder.
**/
std::string getAppdataDirectory();
/**
* Gets the full path of the save folder.
**/
const char *getSaveDirectory();
/**
* Gets the full path to the directory containing the game source.
* For example if the game source is C:\Games\mygame.love, this will return
* C:\Games.
**/
std::string getSourceBaseDirectory() const;
/**
* Gets the real directory path containing the file.
**/
std::string getRealDirectory(const char *filename) const;
/**
* Checks whether a file exists in the current search path
* or not.
* @param file The filename to check.
**/
bool exists(const char *file) const;
/**
* Checks if an existing file really is a directory.
* @param file The filename to check.
**/
bool isDirectory(const char *file) const;
/**
* Checks if an existing file really is a file,
* and not a directory.
* @param file The filename to check.
**/
bool isDirectory(const char *dir) const;
bool isFile(const char *file) const;
/**
* Creates a directory. Write dir must be set.
* @param dir The directory to create.
**/
bool createDirectory(const char *dir);
/**
* Removes a file (or directory).
* @param file The file or directory to remove.
**/
bool remove(const char *file);
/**
* Reads data from a file.
* @param filename The name of the file to read from.
* @param size The size in bytes of the data to read.
**/
Data *read(const char *filename, int64 size = File::ALL) const;
/**
* Write data to a file.
* @param filename The name of the file to write to.
* @param data The data to write.
* @param size The size in bytes of the data to write.
**/
FileData *read(const char *filename, int64 size = File::ALL) const;
void write(const char *filename, const void *data, int64 size) const;
/**
* Append data to a file, creating it if it doesn't exist.
* @param filename The name of the file to write to.
* @param data The data to append.
* @param size The size in bytes of the data to append.
**/
void append(const char *filename, const void *data, int64 size) const;
/**
* This "native" method returns a table of all
* files in a given directory.
**/
int getDirectoryItems(lua_State *L);
/**
* Gets the last modification time of a file, in seconds
* since the Unix epoch.
* @param filename The name of the file.
**/
int64 getLastModified(const char *filename) const;
/**
* Gets the size of a file in bytes.
* @param filename The name of the file.
**/
int64 getSize(const char *filename) const;
/**
* Enable or disable symbolic link support in love.filesystem.
**/
void setSymlinksEnabled(bool enable);
/**
* Gets whether symbolic link support is enabled.
**/
bool areSymlinksEnabled() const;
/**
* Gets whether a filepath is actually a symlink.
* Always returns false if symlinks are not enabled.
**/
bool isSymlink(const char *filename) const;
/**
* Text file line-reading iterator function used and
* pushed on the Lua stack by love.filesystem.lines
* and File:lines.
**/
static int lines_i(lua_State *L);
std::vector<std::string> &getRequirePath();
void allowMountingForPath(const std::string &path);
private:
@@ -289,14 +119,16 @@ private:
// The full path to the source of the game.
std::string game_source;
// Workaround for machines without PhysFS 2.0
bool initialized;
// Allow saving outside of the LOVE_APPDATA_FOLDER
// for release 'builds'
bool fused;
bool fusedSet;
// Search path for require
std::vector<std::string> requirePath;
std::vector<std::string> allowedMountPaths;
}; // Filesystem
} // physfs
@@ -0,0 +1,62 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "wrap_DroppedFile.h"
#include "wrap_File.h"
namespace love
{
namespace filesystem
{
DroppedFile *luax_checkdroppedfile(lua_State *L, int idx)
{
return luax_checktype<DroppedFile>(L, idx, FILESYSTEM_DROPPED_FILE_ID);
}
static const luaL_Reg functions[] =
{
// Inherits from File.
{ "getSize", w_File_getSize },
{ "open", w_File_open },
{ "close", w_File_close },
{ "isOpen", w_File_isOpen },
{ "read", w_File_read },
{ "write", w_File_write },
{ "flush", w_File_flush },
{ "isEOF", w_File_isEOF },
{ "tell", w_File_tell },
{ "seek", w_File_seek },
{ "lines", w_File_lines },
{ "setBuffer", w_File_setBuffer },
{ "getBuffer", w_File_getBuffer },
{ "getMode", w_File_getMode },
{ "getFilename", w_File_getFilename },
{ "getExtension", w_File_getExtension },
{ 0, 0 }
};
extern "C" int luaopen_droppedfile(lua_State *L)
{
return luax_register_type(L, FILESYSTEM_DROPPED_FILE_ID, functions);
}
} // filesystem
} // love
+39
View File
@@ -0,0 +1,39 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_FILESYSTEM_WRAP_DROPPED_FILE_H
#define LOVE_FILESYSTEM_WRAP_DROPPED_FILE_H
// LOVE
#include "common/runtime.h"
#include "DroppedFile.h"
namespace love
{
namespace filesystem
{
DroppedFile *luax_checkdroppedfile(lua_State *L, int idx);
extern "C" int luaopen_droppedfile(lua_State *L);
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_WRAP_DROPPED_FILE_H
+131 -15
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -20,8 +20,6 @@
#include "wrap_File.h"
#include "physfs/Filesystem.h"
#include "common/Data.h"
#include "common/Exception.h"
#include "common/int.h"
@@ -45,7 +43,7 @@ int luax_ioError(lua_State *L, const char *fmt, ...)
File *luax_checkfile(lua_State *L, int idx)
{
return luax_checktype<File>(L, idx, "File", FILESYSTEM_FILE_T);
return luax_checktype<File>(L, idx, FILESYSTEM_FILE_ID);
}
int w_File_getSize(lua_State *L)
@@ -151,11 +149,11 @@ int w_File_write(lua_State *L)
return luax_ioError(L, "%s", e.what());
}
}
else if (luax_istype(L, 2, DATA_T))
else if (luax_istype(L, 2, DATA_ID))
{
try
{
love::Data *data = luax_totype<love::Data>(L, 2, "Data", DATA_T);
love::Data *data = luax_totype<love::Data>(L, 2, DATA_ID);
result = file->write(data, luaL_optinteger(L, 3, data->getSize()));
}
catch (love::Exception &e)
@@ -188,10 +186,10 @@ int w_File_flush(lua_State *L)
return 1;
}
int w_File_eof(lua_State *L)
int w_File_isEOF(lua_State *L)
{
File *file = luax_checkfile(L, 1);
luax_pushboolean(L, file->eof());
luax_pushboolean(L, file->isEOF());
return 1;
}
@@ -223,26 +221,128 @@ int w_File_seek(lua_State *L)
return 1;
}
int w_File_lines_i(lua_State *L)
{
const int bufsize = 1024;
char buf[bufsize];
int linesize = 0;
bool newline = false;
File *file = luax_checktype<File>(L, lua_upvalueindex(1), FILESYSTEM_FILE_ID);
// Only accept read mode at this point.
if (file->getMode() != File::MODE_READ)
return luaL_error(L, "File needs to stay in read mode.");
int64 pos = file->tell();
int64 userpos = -1;
if (lua_isnoneornil(L, lua_upvalueindex(2)) == 0)
{
// User may have changed the file position.
userpos = pos;
pos = (int64) lua_tonumber(L, lua_upvalueindex(2));
if (userpos != pos)
file->seek(pos);
}
while (!newline && !file->isEOF())
{
// This 64-bit to 32-bit integer cast should be safe as it never exceeds bufsize.
int read = (int) file->read(buf, bufsize);
if (read < 0)
return luaL_error(L, "Could not read from file.");
linesize += read;
for (int i = 0; i < read; i++)
{
if (buf[i] == '\n')
{
linesize -= read - i;
newline = true;
break;
}
}
}
if (newline || (file->isEOF() && linesize > 0))
{
if (linesize < bufsize)
{
// We have the line in the buffer on the stack. No 'new' and 'read' needed.
lua_pushlstring(L, buf, linesize > 0 && buf[linesize - 1] == '\r' ? linesize - 1 : linesize);
if (userpos < 0)
file->seek(pos + linesize + 1);
}
else
{
char *str = 0;
try
{
str = new char[linesize + 1];
}
catch(std::bad_alloc &)
{
// Can't lua_error (longjmp) in exception handlers.
}
if (!str)
return luaL_error(L, "Out of memory.");
file->seek(pos);
// Read the \n anyway and save us a call to seek.
if (file->read(str, linesize + 1) == -1)
{
delete [] str;
return luaL_error(L, "Could not read from file.");
}
lua_pushlstring(L, str, str[linesize - 1] == '\r' ? linesize - 1 : linesize);
delete [] str;
}
if (userpos >= 0)
{
// Save new position in upvalue.
lua_pushnumber(L, (lua_Number)(pos + linesize + 1));
lua_replace(L, lua_upvalueindex(2));
file->seek(userpos);
}
return 1;
}
// EOF reached.
if (userpos >= 0 && luax_toboolean(L, lua_upvalueindex(3)))
file->seek(userpos);
else
file->close();
return 0;
}
int w_File_lines(lua_State *L)
{
File *file = luax_checkfile(L, 1);
lua_pushnumber(L, 0); // File position.
luax_pushboolean(L, file->getMode() != File::CLOSED); // Save current file mode.
luax_pushboolean(L, file->getMode() != File::MODE_CLOSED); // Save current file mode.
if (file->getMode() != File::READ)
if (file->getMode() != File::MODE_READ)
{
if (file->getMode() != File::CLOSED)
if (file->getMode() != File::MODE_CLOSED)
file->close();
bool success = false;
luax_catchexcept(L, [&](){ success = file->open(File::READ); });
luax_catchexcept(L, [&](){ success = file->open(File::MODE_READ); });
if (!success)
return luaL_error(L, "Could not open file.");
}
lua_pushcclosure(L, physfs::Filesystem::lines_i, 3);
lua_pushcclosure(L, w_File_lines_i, 3);
return 1;
}
@@ -299,6 +399,20 @@ int w_File_getMode(lua_State *L)
return 1;
}
int w_File_getFilename(lua_State *L)
{
File *file = luax_checkfile(L, 1);
luax_pushstring(L, file->getFilename());
return 1;
}
int w_File_getExtension(lua_State *L)
{
File *file = luax_checkfile(L, 1);
luax_pushstring(L, file->getExtension());
return 1;
}
static const luaL_Reg functions[] =
{
{ "getSize", w_File_getSize },
@@ -308,19 +422,21 @@ static const luaL_Reg functions[] =
{ "read", w_File_read },
{ "write", w_File_write },
{ "flush", w_File_flush },
{ "eof", w_File_eof },
{ "isEOF", w_File_isEOF },
{ "tell", w_File_tell },
{ "seek", w_File_seek },
{ "lines", w_File_lines },
{ "setBuffer", w_File_setBuffer },
{ "getBuffer", w_File_getBuffer },
{ "getMode", w_File_getMode },
{ "getFilename", w_File_getFilename },
{ "getExtension", w_File_getExtension },
{ 0, 0 }
};
extern "C" int luaopen_file(lua_State *L)
{
return luax_register_type(L, "File", functions);
return luax_register_type(L, FILESYSTEM_FILE_ID, functions);
}
} // filesystem
+5 -2
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -41,13 +41,16 @@ int w_File_isOpen(lua_State *L);
int w_File_read(lua_State *L);
int w_File_write(lua_State *L);
int w_File_flush(lua_State *L);
int w_File_eof(lua_State *L);
int w_File_isEOF(lua_State *L);
int w_File_tell(lua_State *L);
int w_File_seek(lua_State *L);
int w_File_lines_i(lua_State *L);
int w_File_lines(lua_State *L);
int w_File_setBuffer(lua_State *L);
int w_File_getBuffer(lua_State *L);
int w_File_getMode(lua_State *L);
int w_File_getFilename(lua_State *L);
int w_File_getExtension(lua_State *L);
extern "C" int luaopen_file(lua_State *L);
} // filesystem
+3 -3
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -29,7 +29,7 @@ namespace filesystem
FileData *luax_checkfiledata(lua_State *L, int idx)
{
return luax_checktype<FileData>(L, idx, "FileData", FILESYSTEM_FILE_DATA_T);
return luax_checktype<FileData>(L, idx, FILESYSTEM_FILE_DATA_ID);
}
int w_FileData_getFilename(lua_State *L)
@@ -61,7 +61,7 @@ static const luaL_Reg w_FileData_functions[] =
extern "C" int luaopen_filedata(lua_State *L)
{
return luax_register_type(L, "FileData", w_FileData_functions);
return luax_register_type(L, FILESYSTEM_FILE_DATA_ID, w_FileData_functions);
}
} // filesystem
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
+90 -61
View File
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2006-2014 LOVE Development Team
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -21,6 +21,7 @@
// LOVE
#include "wrap_Filesystem.h"
#include "wrap_File.h"
#include "wrap_DroppedFile.h"
#include "wrap_FileData.h"
#include "physfs/Filesystem.h"
@@ -28,12 +29,17 @@
// SDL
#include <SDL_loadso.h>
// STL
#include <vector>
#include <string>
#include <sstream>
namespace love
{
namespace filesystem
{
#define instance() (Module::getInstance<physfs::Filesystem>(Module::M_FILESYSTEM))
#define instance() (Module::getInstance<Filesystem>(Module::M_FILESYSTEM))
bool hack_setupWriteDirectory()
{
@@ -119,7 +125,7 @@ int w_newFile(lua_State *L)
const char *filename = luaL_checkstring(L, 1);
const char *str = 0;
File::Mode mode = File::CLOSED;
File::Mode mode = File::MODE_CLOSED;
if (lua_isstring(L, 2))
{
@@ -130,7 +136,7 @@ int w_newFile(lua_State *L)
File *t = instance()->newFile(filename);
if (mode != File::CLOSED)
if (mode != File::MODE_CLOSED)
{
try
{
@@ -144,7 +150,7 @@ int w_newFile(lua_State *L)
}
}
luax_pushtype(L, "File", FILESYSTEM_FILE_T, t);
luax_pushtype(L, FILESYSTEM_FILE_ID, t);
t->release();
return 1;
}
@@ -159,12 +165,12 @@ FileData *luax_getfiledata(lua_State *L, int idx)
const char *filename = luaL_checkstring(L, idx);
file = instance()->newFile(filename);
}
else if (luax_istype(L, idx, FILESYSTEM_FILE_T))
else if (luax_istype(L, idx, FILESYSTEM_FILE_ID))
{
file = luax_checkfile(L, idx);
file->retain();
}
else if (luax_istype(L, idx, FILESYSTEM_FILE_DATA_T))
else if (luax_istype(L, idx, FILESYSTEM_FILE_DATA_ID))
{
data = luax_checkfiledata(L, idx);
data->retain();
@@ -197,7 +203,7 @@ int w_newFileData(lua_State *L)
luax_convobj(L, 1, "filesystem", "newFile");
// Get FileData from the File.
if (luax_istype(L, 1, FILESYSTEM_FILE_T))
if (luax_istype(L, 1, FILESYSTEM_FILE_ID))
{
File *file = luax_checkfile(L, 1);
@@ -210,7 +216,7 @@ int w_newFileData(lua_State *L)
{
return luax_ioError(L, "%s", e.what());
}
luax_pushtype(L, "FileData", FILESYSTEM_FILE_DATA_T, data);
luax_pushtype(L, FILESYSTEM_FILE_DATA_ID, data);
data->release();
return 1;
}
@@ -242,7 +248,7 @@ int w_newFileData(lua_State *L)
return luaL_error(L, "Invalid FileData decoder: %s", decstr);
}
luax_pushtype(L, "FileData", FILESYSTEM_FILE_DATA_T, t);
luax_pushtype(L, FILESYSTEM_FILE_DATA_ID, t);
t->release();
return 1;
}
@@ -277,10 +283,21 @@ int w_getSourceBaseDirectory(lua_State *L)
return 1;
}
int w_exists(lua_State *L)
int w_getRealDirectory(lua_State *L)
{
const char *arg = luaL_checkstring(L, 1);
luax_pushboolean(L, instance()->exists(arg));
const char *filename = luaL_checkstring(L, 1);
std::string dir;
try
{
dir = instance()->getRealDirectory(filename);
}
catch (love::Exception &e)
{
return luax_ioError(L, "%s", e.what());
}
lua_pushstring(L, dir.c_str());
return 1;
}
@@ -349,9 +366,9 @@ static int w_write_or_append(lua_State *L, File::Mode mode)
const char *input = 0;
size_t len = 0;
if (luax_istype(L, 2, DATA_T))
if (luax_istype(L, 2, DATA_ID))
{
love::Data *data = luax_totype<love::Data>(L, 2, "Data", DATA_T);
love::Data *data = luax_totype<love::Data>(L, 2, DATA_ID);
input = (const char *) data->getData();
len = data->getSize();
}
@@ -365,7 +382,7 @@ static int w_write_or_append(lua_State *L, File::Mode mode)
try
{
if (mode == File::APPEND)
if (mode == File::MODE_APPEND)
instance()->append(filename, (const void *) input, len);
else
instance()->write(filename, (const void *) input, len);
@@ -381,12 +398,12 @@ static int w_write_or_append(lua_State *L, File::Mode mode)
int w_write(lua_State *L)
{
return w_write_or_append(L, File::WRITE);
return w_write_or_append(L, File::MODE_WRITE);
}
int w_append(lua_State *L)
{
return w_write_or_append(L, File::APPEND);
return w_write_or_append(L, File::MODE_APPEND);
}
int w_getDirectoryItems(lua_State *L)
@@ -403,7 +420,7 @@ int w_lines(lua_State *L)
file = instance()->newFile(lua_tostring(L, 1));
bool success = false;
luax_catchexcept(L, [&](){ success = file->open(File::READ); });
luax_catchexcept(L, [&](){ success = file->open(File::MODE_READ); });
if (!success)
{
@@ -411,13 +428,13 @@ int w_lines(lua_State *L)
return luaL_error(L, "Could not open file.");
}
luax_pushtype(L, "File", FILESYSTEM_FILE_T, file);
luax_pushtype(L, FILESYSTEM_FILE_ID, file);
file->release();
}
else
return luaL_argerror(L, 1, "expected filename.");
lua_pushcclosure(L, physfs::Filesystem::lines_i, 1);
lua_pushcclosure(L, w_File_lines_i, 1);
return 1;
}
@@ -512,58 +529,67 @@ int w_isSymlink(lua_State *L)
return 1;
}
int w_getRequirePath(lua_State *L)
{
std::stringstream path;
bool seperator = false;
for (auto &element : instance()->getRequirePath())
{
if (seperator)
path << ";";
else
seperator = true;
path << element;
}
luax_pushstring(L, path.str());
return 1;
}
int w_setRequirePath(lua_State *L)
{
std::string element = luax_checkstring(L, 1);
auto &requirePath = instance()->getRequirePath();
requirePath.clear();
std::stringstream path;
path << element;
while(std::getline(path, element, ';'))
requirePath.push_back(element);
return 0;
}
int loader(lua_State *L)
{
const char *filename = lua_tostring(L, -1);
std::string modulename = luax_tostring(L, 1);
std::string tmp(filename);
tmp += ".lua";
int size = tmp.size();
for (int i=0; i<size-4; i++)
for (char &c : modulename)
{
if (tmp[i] == '.')
{
tmp[i] = '/';
}
if (c == '.')
c = '/';
}
// Check whether file exists.
if (instance()->exists(tmp.c_str()))
auto *inst = instance();
for (std::string element : inst->getRequirePath())
{
lua_pop(L, 1);
lua_pushstring(L, tmp.c_str());
// Ok, load it.
return w_load(L);
}
size_t pos = element.find('?');
if (pos != std::string::npos)
element.replace(pos, 1, modulename);
tmp = filename;
size = tmp.size();
for (int i=0; i<size; i++)
{
if (tmp[i] == '.')
{
tmp[i] = '/';
}
}
if (instance()->isDirectory(tmp.c_str()))
{
tmp += "/init.lua";
if (instance()->exists(tmp.c_str()))
if (inst->isFile(element.c_str()))
{
lua_pop(L, 1);
lua_pushstring(L, tmp.c_str());
// Ok, load it.
lua_pushstring(L, element.c_str());
return w_load(L);
}
}
std::string errstr = "\n\tno file '%s' in LOVE game directories.";
errstr += errstr;
std::string errstr = "\n\tno '%s' in LOVE game directories.";
lua_pushfstring(L, errstr.c_str(), (tmp + ".lua").c_str(), (tmp + "/init.lua").c_str());
lua_pushfstring(L, errstr.c_str(), modulename.c_str());
return 1;
}
@@ -658,7 +684,7 @@ static const luaL_Reg functions[] =
{ "getAppdataDirectory", w_getAppdataDirectory },
{ "getSaveDirectory", w_getSaveDirectory },
{ "getSourceBaseDirectory", w_getSourceBaseDirectory },
{ "exists", w_exists },
{ "getRealDirectory", w_getRealDirectory },
{ "isDirectory", w_isDirectory },
{ "isFile", w_isFile },
{ "createDirectory", w_createDirectory },
@@ -675,19 +701,22 @@ static const luaL_Reg functions[] =
{ "areSymlinksEnabled", w_areSymlinksEnabled },
{ "isSymlink", w_isSymlink },
{ "newFileData", w_newFileData },
{ "getRequirePath", w_getRequirePath },
{ "setRequirePath", w_setRequirePath },
{ 0, 0 }
};
static const lua_CFunction types[] =
{
luaopen_file,
luaopen_droppedfile,
luaopen_filedata,
0
};
extern "C" int luaopen_love_filesystem(lua_State *L)
{
physfs::Filesystem *instance = instance();
Filesystem *instance = instance();
if (instance == nullptr)
{
luax_catchexcept(L, [&](){ instance = new physfs::Filesystem(); });
@@ -702,7 +731,7 @@ extern "C" int luaopen_love_filesystem(lua_State *L)
WrappedModule w;
w.module = instance;
w.name = "filesystem";
w.flags = MODULE_FILESYSTEM_T;
w.type = MODULE_FILESYSTEM_ID;
w.functions = functions;
w.types = types;

Some files were not shown because too many files have changed in this diff Show More