library experiments

This commit is contained in:
Bob Omb 2015-11-03 20:26:56 -08:00
parent fbc63403ab
commit fa5fa9c980
32 changed files with 2285 additions and 1823 deletions

View File

@ -4,7 +4,7 @@ RASTERS = MODPATH .. "/rasters/"
SCHEMS = MODPATH .. "/schems/"
local realterrain = {}
realterrain.settings = {}
local magick, imlib2
local ie = minetest.request_insecure_environment()
--[[ie.require "luarocks.loader"
@ -12,12 +12,17 @@ local magick = ie.require "magick"--]]
package.path = (MODPATH.."/lua-imagesize-1.2/?.lua;"..package.path)
local imagesize = ie.require "imagesize"
--[[
package.path = (MODPATH.."/lunatic-python-bugfix-1.1.1/?.lua;"..package.path)
local python = ie.require "python"
]]
package.path = (MODPATH.."/lunatic-python-1.0/?.lua;"..package.path)
local python = ie.require "imagesize"
--ONLY RUN ONE OF MAGICK OR IMLIB2 AT ANY TIME
package.path = (MODPATH.."/magick/?.lua;"..MODPATH.."/magick/?/init.lua;"..package.path)
local magick = ie.require "magick"
local magick = ie.require "magick"--]]
--[[package.path = (MODPATH.."/lua-imlib2/?.lua;"..package.path)
local imlib2 = ie.require "imlib2"--]]
--defaults
realterrain.settings.output = "normal"
@ -285,16 +290,27 @@ function realterrain.get_idx(haystack, needle)
end
return 0
end
local imageload
if magick then imageload = magick.load_image
elseif imlib2 then imageload = imlib2.image.load
end
--@todo fail if there is no DEM?
local dem = magick.load_image(RASTERS..realterrain.settings.filedem)
local width = dem:get_width()
local length = dem:get_height()
--print("width: "..width..", height: "..length)
local dem = imageload(RASTERS..realterrain.settings.filedem)
--local dem = magick.load_image(RASTERS..realterrain.settings.filedem)
local width, height
--print("here")
if dem then
width = dem:get_width()
length = dem:get_height()
--local depth = dem:get_option("ImageProperty", "depth")-- @todo need to find correct syntax for this
--print("depth: "..depth)
--print("width: "..width..", height: "..length)
else error(RASTERS..realterrain.settings.filedem.." does not appear to be an image file. your image may need to be renamed, or you may need to manually edit the realterrain.settings file in the world folder") end
local biomeimage, waterimage, roadimage
biomeimage = magick.load_image(RASTERS..realterrain.settings.filebiome)
waterimage = magick.load_image(RASTERS..realterrain.settings.filewater)
roadimage = magick.load_image(RASTERS..realterrain.settings.fileroads)
biomeimage = imageload(RASTERS..realterrain.settings.filebiome)
waterimage = imageload(RASTERS..realterrain.settings.filewater)
roadimage = imageload(RASTERS..realterrain.settings.fileroads)
--@todo throw warning if image sizes do not match the dem size
-- Set mapgen parameters
@ -321,7 +337,7 @@ minetest.register_on_generated(function(minp, maxp, seed)
local c_gravel = minetest.get_content_id("default:gravel")
local c_stone = minetest.get_content_id("default:stone")
local c_sand = minetest.get_content_id("default:sand")
local c_water = minetest.get_content_id("default:water_source")
local c_water = minetest.get_content_id("realterrain:water_static")
local c_dirt = minetest.get_content_id("default:dirt")
local c_coal = minetest.get_content_id("default:stone_with_coal")
local c_cobble = minetest.get_content_id("default:cobble")
@ -526,18 +542,42 @@ function realterrain.get_pixel(x,z, elev_only)
--off the dem return zero for all values
if ((col < 0) or (col > width) or (row < 0) or (row > length)) then return 0,0,0,0 end
e = dem:get_pixel(col, row)
if magick then
e = math.floor(dem:get_pixel(col, row) * (2^tonumber(realterrain.settings.bits))) --@todo change when magick autodetects bit depth
elseif imlib2 then
e = dem:get_pixel(col, row).red
end
--print("raw e: "..e)
--adjust for bit depth and vscale
e = math.floor(e * (2^tonumber(realterrain.settings.bits))) --@todo change when magick autodetects bit depth
--adjust for offset and scale
e = math.floor((e / tonumber(realterrain.settings.yscale)) + tonumber(realterrain.settings.yoffset))
if elev_only then
return e
else
if biomeimage then b = math.floor(biomeimage:get_pixel(col, row) * (2^8 )) end --assume an 8-bit biome file
if waterimage then w = math.ceil(waterimage:get_pixel(col, row) ) end --any non-zero value
if roadimage then r = math.ceil(roadimage:get_pixel(col, row) ) end --any non-zero value
if biomeimage then
if magick then
--assume an 8-bit biome file
b = math.floor(biomeimage:get_pixel(col, row) * (2^8 ))
elseif imlib2 then
b = biomeimage:get_pixel(col, row).red
end
end
if waterimage then
if magick then
--any non-zero
w = math.ceil(waterimage:get_pixel(col, row) * (2^8 ))
elseif imlib2 then
w = waterimage:get_pixel(col, row).red
end
end
if roadimage then
if magick then
--any non-zero
w = math.ceil(roadimage:get_pixel(col, row) * (2^8 ))
elseif imlib2 then
w = roadimage:get_pixel(col, row).red
end
end
end

View File

@ -0,0 +1,352 @@
# `imlib2.color`
Represent colors in rgba format. Each instance of imlib2.color has the
modifiable fields red, green, blue and alpha. An error will be raised on an
attempt to set them to a value outside of the range `0 <= x <= 255`.
Non-integer values will be truncated.
## `imlib2.color.new(red, green, blue[, alpha])`
Creates a new color. An error will be raised unless red, green, blue and
alpha are in the range `0 <= x <= 255`.
## `col.red`, `col.green`, `col.blue`, `col.alpha`
Each instance of `imlib2.color` has integer fields `red`, `green`, `blue`,
and `alpha` which can be read and modified. An exception is raised if you try
to set the value outside the range `0 <= x <= 255`.
# `imlib2.border`
Represents a border. Contains left, top, right, bottom values as mutable
fields. A border is the area at the edge of an image that does not scale when
the rest of the image is resized - the borders remain constant in size.
## `imlib2.border.new(left, top, right, bottom)`
Creates a new border. `left`, `top`, `right` and `bottom` are the size of each
side of the border in pixels.
## `bd.left`, `bd.top`, `bd.right`, `bd.bottom`
Each instance of `imlib2.border` has these mutable fields.
# `imlib2.gradient`
Consists of colours and the offsets at which they occur.
## `imlib2.gradient.new()`
Creates a new gradient. Use `grad:add_color()` to add colors to it.
## `grad:add_color(offset, color)`
Add an `imlib2.color` instance at the given `offset`. `offset` is the distance
from the previous color in pixels. It has no meaning for the first color
added.
# `imlib2.polygon`
Represents a polygon object. Points are drawn in the order in which they are
added.
## `imlib2.polygon.new() `
Create a new polygon. Add points using `poly:add_point()`.
## `poly:add_point(x, y)`
Add point (x,y) to the polygon. `x` is the x coordinate in pixels, and `y` is
is the y coordinate in pixels.
## `poly:get_bounds()`
Returns the four points of the rectangular bounding area for the polygon.
Returns `x1`, `y1` `x2`, `y2`:
* `x1`: x coordinate of the upper left corner
* `y1`: y coordinate of the upper left corner
* `x2`: x coordinate of the upper right corner
* `y2`: y coordinate of the lower right corner
## `poly:contains_point(x, y)`
Returns true if the polygon contains point (x,y).
# `imlib2.font`
Instances represent a loaded font. Provides static methods for querying and
modifying the font paths used by imlib2.
## `imlib2.font.load(name)`
Load the given font from the current font path. `name` is a font path, e.g.
"Vera/10". It returns a font object for a given font name, nil plus an error
message if no such font can be found on the path.
## `imlib2.font.add_path(path)`
Add the given `path` to the list of paths Imlib2 searches when loading a font.
## `imlib2.font.remove_path(path)`
Remove the given `path` from Imlib2's font path list.
## `imlib2.font.list_paths()`
Returns a table containing all the font paths Imlib2 will search when asked to
load a font.
## `imlib2.font.list_fonts()`
Returns an array of all the font names Imlib2 can find on its font path.
## `imlib2.font.get_cache_size()`
Returns the font cache size in bytes.
## `imlib2.font.set_cache_size()`
Sets the font cache size in bytes. Whenever you set the font cache size,
Imlib2 will flush fonts from the cache until the memory used by fonts is
less than or equal to the font cache size. Setting the size to 0 frees all
speculatively cached fonts.
## `imlib2.font.set_direction(dir[, angle])`
Sets the direction that text will be drawn at. Accepts 90 degree
orientations, or an arbitrary angle. Raises an error for invalid direciton
names. Takes parameters:
* `dir` can be `"right"`, `"left"`, `"down"`, `"up"` or `"angle"` (in which
case parameter `angle` must be given)
* `angle` given in radians. Only needed if `direction` was `"angle"`.
## `imlib2.font.get_direction()`
Gives the direction that text is set to be drawn at. Returns one of the
strings `"right"`, `"left"`, `"down"`, `"up"` or `"angle"`. If `"angle"` is
returned, then the angle in radians is given as the second return value.
## `fnt:get_size(str)`
Get the width and height of the given string when drawn with `fnt`. Returns
the width and height in pixels.
## `fnt:get_advance(str)`
Get the horizontal and vertical advance of the given string when drawn with
`fnt`. The horizontal and vertical advance are the number of pixels away the
next string would need to be placed at. The advances are not adjusted for
rotation, and are calculated as if the text was drawn horizontally from left
to right.
Returns the horizontal and vertical advance in pixels.
## `fnt:get_inset(str)`
The inset in pixels of the first character of the given string.
## `fnt:get_ascent()`
Get the font's ascent in pixels.
## `fnt:get_maximum_ascent()`
Get the font's maximum ascent in pixels.
## `fnt:get_descent()`
Get the font's descent in pixels.
## `fnt:get_maximum_descent()`
Get the font's maximum descent in pixels.
# `imlib2.image`
Methods for image loading, saving and manipulation.
## `image.new(width, height)`
Create a new image. `width` and `height` are given in pixels.
## `image.load(path)`
Loads the image at the given path. Imlib2 searches its loader modules until it
finds one that can decode the file at the given path. The loader modules
available to you (and hence the range of filetypes you are able to load) will
depend on the options used when building the Imlib2 shared library. Loaders
will not decode image data until it is needed (provided this is feasible for
the given file format). This means it is perfectly sensible to load many files
in order to query their header information such as width and height. If the
image is present in Imlib2's cache, it won't check if the file has changed and
will instead just return that cached version of the image.
Returns the loaded image or else nil plus an error message
## `img:free()`
Frees the image. This does not evict the image from Imlib2's cache.
## `img:clone()`
Obtain a clone of the image.
## `img:get_width()`
Get the width of the image in pixels.
## `img:get_height()`
Get the height of the image in pixels.
## `img:get_filename()`
Returns the current image filename.
## `img:get_format()`
Get the current image format.
## `img:set_format(format)`
Sets the image format to the given string. No check is made to ensure that the
Imlib2 shared library can save in this format. If it can not, `img:save()`
will later fail.
## `img:has_alpha()`
Gives a boolean value indicating whether the image has an alpha channel.
## `img:set_alpha(bool)`
Enable or disable the image's alpha channel based on the given boolean.
## `img:get_border()`
Get the imlib2.border object for `img`.
## `img:set_border(border)`
Sets the image border to the given `imlib2.border` object.
## `img:get_pixel(x, y)`
Gives the color of the pixel at the given (x,y) coordinates. The origin -
(0,0) is at the top left.
Return an instance of imlib2.color matching the color at the given
coordinates.
## `img:crop(x, y, width, height)`
Crops the image to the given rectangle.
Takes the parameters:
* `x` the x coordinate of the top left corner
* `y` the y coordinate of the top left corner
* `width` the width of the rectangle
* `height` the height of the rectangle
## `img:crop_and_scale(source_x, source_y, source_h, source_w, dest_w, dest_h)`
Crops the image to the given rectangle and also scales it. The image will be
scaled to the given destination width and height.
Takes the parameters:
* `source_x` the x coordinate of the top left corner of the source rectangle
* `source_y` the y coordinate of the top left corner of the source rectangle
* `source_h` the height of the source rectangle
* `source_w` the width of the source rectangle
* `dest_w` the width of the destination rectangle
* `dest_h` the height of the destination rectangle
## `img:rotate(angle)`
Rotates the image by `angle` radians.
## `img:flip_horizontal()`
Flips the image horizontally
## `img:flip_vertical()`
Flips the image vertically
## `img:flip_diagonal()`
Flips the image diagonally.
## `img:orientate(n)`
Performs `n` 90 degree rotations on the image. `n` is the integer number of 90
degree rotations to perform.
## `img:blur(radius)`
Blurs the image. A radious value of `0` has no effect. `1` and above determine
the blur matrix radius that determines how much to blur the image.
## `img:sharpen(radius)`
Sharpens the image. The radius affects how much to sharpen by.
## `img:tile_horizontal()`
Modifies the image so it will tile seamlessly horizontally.
## `img:tile_vertical()`
Modifies the image so it will tile seamlessly vertically.
## `img:tile()`
Modifies the image so it will tile seamless horizontally and vertically.
## `img:clear()`
Clears the contents of the image.
## `img:draw_pixel(x, y[, color])`
Draw a pixel at the specified coordinates in the given `color` (an
`imlib2.color` object). If no color is specified then the pixel will be drawn
in the most recent color.
## `img:draw_line(x1, y1, x2, y2[, color])`
Draw a line from (x1, y1) to (x2, y2). If no color is specified, then it will
be drawn in the most recent color.
## `img:draw_rectangle(x, y, width, height[, color])`
Draws the outline of a rectangle. If no color is specified, then it will be
drawn in the most recent color.
## `img:fill_rectangle(x, y, width, height, color)`
Draws a filled rectangle. If no color is specified, then it will be drawn in
the most recent color.
## `img:scroll_rectangle(x, y, width, height, delta_x, delta_y)`
Scrolls the specified rectangle by the given displacement.
## `img:copy_rectangle(x, y, width, height, new_x, new_y)`
Copies the given rectangle to (new_x, new_y).
## `img:fill_gradient(gradient, x, y, width, height, angle)`
Fills a rectangle with the given gradient.
Takes the parameters:
* `gradient` an imlib2.gradient object
* `x` the x coordinate of the rectangle's top left corner
* `y` the y coordinate of the rectangle's top left corner
* `width` the width of the rectangle
* `height` the height of the rectangle
* `angle` the angle at which the gradient will be drawn
## `img:draw_ellipse(xc, yc, a, b[, color])`
Draws the outline of an ellipse. (xc, yc) is the centre of the ellipse, which
is described by the equation `(x-xc)^2/a^2 + (y-yc)^2/b^2 = 1`. If no color is
specified then it will be drawn in the most recent color.
Takes the parameters:
* `xc` x coordinate of the centre of the ellipse
* `yc` y coordinate of the centre of the ellipse
* `a` horizontal amplitude
* `b` vertical amplitude
* `color` (optional) an `imlib2.color` object
## `img:fill_ellipse(xc, yc, a, b[, color])`
Fills an ellipse. See `img:draw_ellipse()` for the meaning of the parameters.
## `img:draw_polygon(polygon, closed[, color])`
Draws the outline of a polygon. Points in the `imlib2.polygon` are drawn in
the order in which they were added. The final point will be connected to the
first point if `closed` is true. If no color is specified then it will be
drawn in the most recent color.
## `img:fill_polygon(polygon[, color])`
Fills a `imlib2.polygon`. If no color is specified then it will be drawn in
the most recent color.
## `img:draw_text(font, string, x, y[, color])`
Draws a string in the given font at point (x, y). If no color is specified
then it will be drawn in the most recent color.
Takes the parameters:
* `font` an imlib2.font object
* `string` the string to be drawn
* `x` the x coordinate of the point to start drawing
* `y` the y coordinate of the point to start drawing
## `img:save(path)`
Saves the image to the given path. The file extension (e.g. .png or .jpg) will
affect the output format (but will not override any format set by a call to
`img:set_format()`).
Returns `true` or `nil` plus an error message if the save fails.
# `imlib2`
Functions to modify the operation of the imlib2 library.
## `imlib2.set_anti_alias(bool)`
Enable or disable anti-aliasing for future drawing operations.
## `imlib2.get_anti_alias()`
Gives a boolean indicating whether anti-aliasing is enabled or disabled.
## `imlib2.get_cache_size()`
Gives the current size of the image cache in bytes
## `imlib2.set_cache_size(size)`
Set the size of the image cache, where `size` is the desired cache size in
bytes.
## `imlib2.flush_cache()`
Flushes the image cache.

25
lua-imlib2/LICENSE Normal file
View File

@ -0,0 +1,25 @@
Licensed under the MIT license (same as Lua), reproduced below:
---
Copyright (c) 2007-2008 A.S. Bradbury
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.

30
lua-imlib2/Makefile Normal file
View File

@ -0,0 +1,30 @@
# change these to reflect your Lua installation
LUA= /usr
LUAINC= $(LUA)/include
LUALIB= $(LUA)/lib
LUABIN= $(LUA)/bin
# no need to change anything below here
CFLAGS= $(INCS) $(DEFS) $(WARN) -O2
WARN= -Wall
INCS= -I$(LUAINC)
LIBS= -lImlib2
OBJS= limlib2.o
SOS= limlib2.so
all: limlib2.so
limlib2.so: $(OBJS)
$(CC) -o $@ -shared $(OBJS) $(LIBS)
.PHONY: clean doc test
clean:
rm -f $(OBJS) $(SOS) *.png core core.* a.out
doc:
lua doc/extract_doc.lua limlib2.c > doc/doc.html
test:
./lunit test/*

49
lua-imlib2/README.mkd Normal file
View File

@ -0,0 +1,49 @@
# lua-imlib2
Provides a mostly complete binding to the imlib2 image manipulation library.
You will need this library installed in order to use lua-imlib2 (preferably a
recent version). This release makes no effort to wrap the X11 related Imlib2
functionality, but aims to support all other features. The API is fully
[documented](http://asbradbury.org/projects/lua-imlib2/doc/). If you encounter
any problems or have any suggestions (or patches) then please contact me.
## Links
* [Home](http://asbradbury.org/projects/lua-imlib2/)
* [Download](http://luaforge.net/projects/lua-imlib2/)
* [Documentation](http://asbradbury.org/projects/lua-imlib2/doc/)
* [Source](http://github.com/asb/lua-imlib2/)
## Release history
* lua-imlib2-0.1 (2008-01-22)
* first public release
## License
lua-imlib2 is distributed under the MIT license.
Copyright (c) 2007-2008 A.S. Bradbury
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.
## Contact
Author: A.S. Bradbury
Email: <asb@asbradbury.org>
Homepage: <http://asbradbury.org/>

13
lua-imlib2/TODO Normal file
View File

@ -0,0 +1,13 @@
Support creating colors from a single integer representation, and possibly in
the other forms supported by imlib
Support im:scale(w,h) - maybe scale by percentage
Make an imlib2.color_modifier
Add new image constructors such as new_cropped(im, ...)
Write a sparkline library using imlib2
Steal interface ideas from
http://search.cpan.org/~lbrocard/Image-Imlib2-1.13/lib/Image/Imlib2.pm

View File

@ -0,0 +1,46 @@
-- Draw a checkerboard
-- Basically a translation of the imlib2-ruby example (c) 2002 Paul Duncan
require("imlib2")
local color = imlib2.color
local w, h, bw, bh = 10, 10, 48, 48 -- #squares across, #squares down, square width, square height
local fg_gradient = imlib2.gradient.new()
fg_gradient:add_color(0, color.DARKGREY)
fg_gradient:add_color(1, color.LIGHTGREY)
local im = imlib2.image.new(w * bw, h * bh)
im:fill_rectangle(0, 0, w*bw, h*bh, color.BLACK) -- Fill background
local function is_white(across, down)
return (across%2 == 0 and down%2 == 0) or (across%2 == 1 and down%2 == 1)
end
print("Generating checkerboard")
for across=0, 9 do
for down=0, 9 do
if (is_white(across,down)) then
im:fill_gradient(fg_gradient, across*bw, down*bh, bw, bh, 135)
end
end
end
print("Generating pieces")
for across=0, 9 do
for down=0, 9 do
local ellipse_args = {across*bw + bw/2, down*bh + bh/2, bw*2/5, bh*2/5}
if not (is_white(across,down)) then
-- Draw 3 rows of red checkers at the top, 3 rows of black at the bottom
if (down < 3) then
ellipse_args[#ellipse_args+1]=color.RED
im:fill_ellipse(unpack(ellipse_args))
elseif (down >= h-3) then
ellipse_args[#ellipse_args+1]=color.BLUE
im:fill_ellipse(unpack(ellipse_args))
end
end
end
end
im:save("checkerboard.png")

View File

@ -0,0 +1,25 @@
-- Draw the Sierpinski triangle, basically really not very different to the
-- lua-gd example it was copied from
require "imlib2"
local size = 250
img = imlib2.image.new(size, size)
img:fill_rectangle(0, 0, size, size, imlib2.color.WHITE)
local m = {}
m[math.floor(size/2)]=true
for i=1, size do
local n={}
for j=1, size do
if m[j] then
img:draw_pixel(j, i, imlib2.color.BLACK)
n[j+1] = not n[j+1]
n[j-1] = not n[j-1]
end
end
m=n
end
img:save("sierpinski.png")

View File

@ -0,0 +1,23 @@
-- Fun little algorithm from the first chapter of The New Turing Omnibus by
-- A.K. Dewdney. Try playing with different parameters
require("imlib2")
local corner_a, corner_b, side = ...
assert(corner_a and corner_b and side, "Please provide 3 integer parameters")
local side_length = 500
im = imlib2.image.new(side_length, side_length)
local colors = {imlib2.color.YELLOW, imlib2.color.BLACK, imlib2.color.RED}
for x=0, side_length-1 do
for y=0, side_length-1 do
local a = corner_a + x*(side/side_length)
local b = corner_b + y*(side/side_length)
local c = math.floor(a^2 + b^2)
local color_index = 1 + c % #colors
im:draw_pixel(x, y, colors[color_index])
end
end
im:save("wallpaper.png")

47
lua-imlib2/imlib2.lua Normal file
View File

@ -0,0 +1,47 @@
local M = require("limlib2")
local c = M.color
-- transformed from the color constants in ruby-imlib2
c.CLEAR = c.new(0, 0, 0, 0)
c.TRANSPARENT = c.new(0, 0, 0, 0)
c.TRANSLUCENT = c.new(0, 0, 0, 0)
c.SHADOW = c.new(0, 0, 0, 64)
c.BLACK = c.new(0, 0, 0, 255)
c.DARKGRAY = c.new(64, 64, 64, 255)
c.DARKGREY = c.new(64, 64, 64, 255)
c.GRAY = c.new(128, 128, 128, 255)
c.GREY = c.new(128, 128, 128, 255)
c.LIGHTGRAY = c.new(192, 192, 192, 255)
c.LIGHTGREY = c.new(192, 192, 192, 255)
c.WHITE = c.new(255, 255, 255, 255)
c.RED = c.new(255, 0, 0, 255)
c.GREEN = c.new(0, 255, 0, 255)
c.BLUE = c.new(0, 0, 255, 255)
c.YELLOW = c.new(255, 255, 0, 255)
c.ORANGE = c.new(255, 128, 0, 255)
c.BROWN = c.new(128, 64, 0, 255)
c.MAGENTA = c.new(255, 0, 128, 255)
c.VIOLET = c.new(255, 0, 255, 255)
c.PURPLE = c.new(128, 0, 255, 255)
c.INDIGO = c.new(128, 0, 255, 255)
c.CYAN = c.new(0, 255, 255, 255)
c.AQUA = c.new(0, 128, 255, 255)
c.AZURE = c.new(0, 128, 255, 255)
c.TEAL = c.new(0, 255, 128, 255)
c.DARKRED = c.new(128, 0, 0, 255)
c.DARKGREEN = c.new(0, 128, 0, 255)
c.DARKBLUE = c.new(0, 0, 128, 255)
c.DARKYELLOW = c.new(128, 128, 0, 255)
c.DARKORANGE = c.new(128, 64, 0, 255)
c.DARKBROWN = c.new(64, 32, 0, 255)
c.DARKMAGENTA = c.new(128, 0, 64, 255)
c.DARKVIOLET = c.new(128, 0, 128, 255)
c.DARKPURPLE = c.new(64, 0, 128, 255)
c.DARKINDIGO = c.new(64, 0, 128, 255)
c.DARKCYAN = c.new(0, 128, 128, 255)
c.DARKAQUA = c.new(0, 64, 128, 255)
c.DARKAZURE = c.new(0, 64, 128, 255)
c.DARKTEAL = c.new(0, 128, 64, 255)
return M

1287
lua-imlib2/limlib2.c Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,30 @@
package="lua-imlib2"
version="dev-1"
source = {
url = "",
}
description = {
summary = "A binding to the imlib2 image manipulation library",
homepage = "http://asbradbury.org/projects/lua-imlib2/",
license = "MIT/X11"
}
dependencies = {
"lua >= 5.1"
}
external_dependencies = {
IMLIB2 = {
header = "Imlib2.h",
}
}
build = {
type = "builtin",
modules = {
limlib2 = {
sources = {"limlib2.c"},
libraries = {"Imlib2"},
incdirs = {"$(IMLIB2_INCDIR)"},
libdirs = {"$(IMLIB2_LIBDIR)"}
},
imlib2 = "imlib2.lua"
}
}

View File

@ -0,0 +1,33 @@
require("lunit")
module("test border", lunit.testcase, package.seeall)
local imlib2 = require("imlib2")
function setup()
border = imlib2.border.new(1,2,3,4)
end
function test_left_top_right_bottom()
local b = border
assert_equal(1, b.left)
assert_equal(2, b.top)
assert_equal(3, b.right)
assert_equal(4, b.bottom)
b.left = 5
b.top = 6
b.right = 7
b.bottom = 8
assert_equal(5, b.left)
assert_equal(6, b.top)
assert_equal(7, b.right)
assert_equal(8, b.bottom)
end
function test__tostring()
assert_string(border:__tostring())
end
-- Test border creation
function test_create_fails_with_missing_sides()
assert_error(nil, function() border.new(1,2,3,nil) end)
end

View File

@ -0,0 +1,55 @@
require("lunit")
local imlib2 = require("imlib2")
local module = module
module("creating a new color", lunit.testcase)
function test_too_few_colors()
assert_error(nil, function() imlib2.color.new(255, 255, nil, nil) end)
assert_error(nil, function() imlib2.color.new(nil, nil, nil, 255) end)
end
function test_allow_missing_alpha()
assert_pass(nil, function() imlib2.color.new(255, 255, 255) end)
end
function test_allowed_range()
assert_error(nil, function() imlib2.color.new(255, 255, 255, 256) end)
assert_error(nil, function() imlib2.color.new(256, 255, 255, 255) end)
assert_error(nil, function() imlib2.color.new(0, 0, -1, 0) end)
assert_error(nil, function() imlib2.color.new(0, -1, -1, 0) end)
end
module("querying and modifying an existing color", lunit.testcase)
function setup()
col = imlib2.color.new(0, 0, 0, 255)
end
function test__tostring()
assert_string(col:__tostring())
end
function test_get_rgba()
assert_equal(0, col.red)
assert_equal(0, col.green)
assert_equal(0, col.blue)
assert_equal(255, col.alpha)
end
function test_set_rgba()
col.red=255
col.green=255
col.blue=255
col.alpha=0
assert_equal(255, col.red)
assert_equal(255, col.green)
assert_equal(255, col.blue)
assert_equal(0, col.alpha)
end
function test_set_rgba_out_of_range()
assert_error(nil, function() col.red=256 end)
assert_error(nil, function() col.alpha=-1 end)
end

View File

@ -0,0 +1,109 @@
require("lunit")
local imlib2 = require("imlib2")
local font = imlib2.font
local module = module
module("manipulating the font paths/listing fonts", lunit.testcase)
do
function test_list_paths()
assert_table(font.list_paths())
end
function test_add_path()
font.add_path("foo")
assert_equal("foo", font.list_paths()[1])
assert_error(nil, function() font.add_path(nil) end)
end
function test_remove_path()
font.add_path("foo")
font.remove_path("foo")
assert_equal(0, #font.list_paths())
assert_error(nil, function() font.remove_path(nil) end)
end
function test_list_fonts()
assert_table(font.list_fonts())
end
end
module("getting and setting the cache size", lunit.testcase)
do
function test_get_cache_size()
assert_number(font.get_cache_size())
end
function test_set_cache_size()
local orig = font.get_cache_size()
font.set_cache_size(1337)
assert_equal(1337, font.get_cache_size())
font.set_cache_size(orig)
end
end
module("loading a font", lunit.testcase)
do
function test_failing_to_load_a_font()
local s, msg = font.load("notfound")
assert_nil(s)
assert_string(msg)
end
end
module("a loaded font instance", lunit.testcase)
do
function setup()
font.add_path("resources")
local msg
a_font, msg = font.load("Vera/10")
assert(a_font, msg)
end
function teardown()
font.remove_path("resources")
end
function test__tostring()
assert_string(a_font:__tostring())
end
function test_get_size()
local w, h = a_font:get_size("this is a test of a test of a test")
assert_number(w)
assert_number(h)
assert(w >= h)
end
function test_get_advance()
local h,v = a_font:get_advance("this is a test")
assert_number(h)
assert_number(v)
assert(h > v)
end
function test_get_inset() assert_number(a_font:get_inset("foo")) end
function test_get_ascent() assert_number(a_font:get_ascent()) end
function test_get_maximum_ascent() assert_number(a_font:get_maximum_ascent()) end
function test_get_descent() assert_number(a_font:get_descent()) end
function test_get_maximum_descent() assert_number(a_font:get_maximum_descent()) end
end
module("setting/getting the text direction", lunit.testcase)
do
function test_set_direction()
assert_pass(nil, function() font.set_direction("up") end)
assert_equal("up", font.get_direction())
assert_error(nil, function() font.set_direction("invalid") end)
end
function test_set_direction_to_angle()
assert_error(nil, function() font.set_direction("angle", "bleh") end)
assert_pass(nil, function() font.set_direction("angle", 21.1) end)
local dir, angle = font.get_direction()
assert_equal("angle", dir)
assert_equal(21.1, angle)
end
end

View File

@ -0,0 +1,20 @@
require("lunit")
local imlib2 = require "imlib2"
module("a newly created gradient", lunit.testcase)
do
function setup()
a_gradient = imlib2.gradient.new()
end
function test__tostring()
assert_string(a_gradient:__tostring())
end
function test_add_color()
assert_error(nil, function() a_gradient:add_color() end)
assert_error(nil, function() a_gradient:add_color(1, {}) end)
assert_pass(nil, function() a_gradient:add_color(1, imlib2.color.new(1,1,1)) end)
end
end

View File

@ -0,0 +1,40 @@
require("lunit")
local imlib2 = require("imlib2")
local module = module
module("Anti alias setting", lunit.testcase)
do
function test_get_antialias()
assert_true(imlib2.get_anti_alias()) -- want to be true by default
end
function test_set_anti_alias()
assert_error(nil, function() imlib2.set_anti_alias() end)
imlib2.set_anti_alias(false)
assert_false(imlib2.get_anti_alias())
imlib2.set_anti_alias(true)
assert_true(imlib2.get_anti_alias())
end
end
module("Cache functions", lunit.testcase)
do
function test_get_cache_size()
assert_number(imlib2.get_cache_size())
end
function test_set_cache_size()
local orig = imlib2.get_cache_size()
imlib2.set_cache_size(50000)
assert_equal(50000, imlib2.get_cache_size())
imlib2.set_cache_size(orig)
assert_equal(orig, imlib2.get_cache_size())
end
function test_flush_cache()
local orig = imlib2.get_cache_size()
imlib2.flush_cache() -- should restore original cache size
assert_equal(orig, imlib2.get_cache_size())
end
end

View File

@ -0,0 +1,42 @@
require("lunit")
local imlib2 = require "imlib2"
local module = module
module("a new, empty polygon", lunit.testcase)
do
function setup()
a_poly = imlib2.polygon.new()
end
function test__tostring()
assert_string(a_poly:__tostring())
end
function test_bounds()
-- should have bounds of (0,0) and (0,0)
local res = {a_poly:get_bounds()}
for i=1, 4 do assert_equal(0, res[i]) end
end
end
module("a polygon with one point")
do
function setup()
a_poly = polygon.new()
a_poly:add_point(1,2)
end
function test_bounds()
local res = {a_poly:get_bounds()}
assert_equal(1, res[1])
assert_equal(2, res[2])
assert_equal(1, res[3])
assert_equal(2, res[4])
end
function test_contains()
assert_true(a_poly:contains_point(1,2))
assert_false(a_poly:contains_point(1,1))
end
end

View File

@ -1,504 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@ -1,2 +0,0 @@
recursive-include src *.c *.h
include MANIFEST.in python.lua LICENSE Makefile

View File

@ -1,25 +0,0 @@
#
# Simple wrapper for setup.py script
#
DESTDIR=/
PYTHON=python
prefix=/usr
bindir=$(prefix)/bin
all:
$(PYTHON) setup.py build
install:
$(PYTHON) setup.py install \
--root=$(DESTDIR) \
--prefix=$(prefix) \
--install-scripts=$(bindir)
dist:
$(PYTHON) setup.py sdist
rpm:
$(PYTHON) setup.py bdist_rpm

View File

@ -1,14 +0,0 @@
Metadata-Version: 1.0
Name: lunatic-python
Version: 1.0
Summary: Two-way bridge between Python and Lua
Home-page: http://labix.org/lunatic-python
Author: Gustavo Niemeyer
Author-email: gustavo@niemeyer.net
License: LGPL
Description: Lunatic Python is a two-way bridge between Python and Lua, allowing these
languages to intercommunicate. Being two-way means that it allows Lua inside
Python, Python inside Lua, Lua inside Python inside Lua, Python inside Lua
inside Python, and so on.
Platform: UNKNOWN

View File

@ -1,23 +0,0 @@
local path = os.getenv("LUA_SOPATH")
if path then
func = loadlib(path.."/lua-python.so", "luaopen_python")
if func then
func()
return
end
end
local modmask = "/usr/lib/python%d.%d/site-packages/lua-python.so"
local loaded = false
for i = 10, 2, -1 do
for j = 10, 2, -1 do
func = loadlib(string.format(modmask, i, j), "luaopen_python")
if func then
loaded = true
func()
break
end
end
end
if not loaded then
error("unable to find python module")
end

View File

@ -1,3 +0,0 @@
[bdist_rpm]
doc_files = python.lua LICENSE
use_bzip2 = 1

View File

@ -1,43 +0,0 @@
#!/usr/bin/python
from distutils.core import setup, Extension
from distutils.sysconfig import get_python_lib, get_python_version
import os
if os.path.isfile("MANIFEST"):
os.unlink("MANIFEST")
# You may have to change these
PYLIBS = ["python"+get_python_version(), "pthread", "util"]
PYLIBDIR = [get_python_lib(standard_lib=True)+"/config"]
LUALIBS = ["lua", "lualib"]
LUALIBDIR = []
setup(name="lunatic-python",
version = "1.0",
description = "Two-way bridge between Python and Lua",
author = "Gustavo Niemeyer",
author_email = "gustavo@niemeyer.net",
url = "http://labix.org/lunatic-python",
license = "LGPL",
long_description =
"""\
Lunatic Python is a two-way bridge between Python and Lua, allowing these
languages to intercommunicate. Being two-way means that it allows Lua inside
Python, Python inside Lua, Lua inside Python inside Lua, Python inside Lua
inside Python, and so on.
""",
ext_modules = [
Extension("lua-python",
["src/pythoninlua.c", "src/luainpython.c"],
library_dirs=PYLIBDIR,
libraries=PYLIBS,
extra_compile_args=["-rdynamic"],
extra_link_args=["-rdynamic"]),
Extension("lua",
["src/pythoninlua.c", "src/luainpython.c"],
library_dirs=LUALIBDIR,
libraries=LUALIBS,
extra_compile_args=["-rdynamic"],
extra_link_args=["-rdynamic"]),
],
)

View File

@ -1,500 +0,0 @@
/*
Lunatic Python
--------------
Copyright (c) 2002-2005 Gustavo Niemeyer <gustavo@niemeyer.net>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <Python.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include "pythoninlua.h"
#include "luainpython.h"
lua_State *LuaState = NULL;
static PyObject *LuaObject_New(int n);
PyObject *LuaConvert(lua_State *L, int n)
{
PyObject *ret = NULL;
switch (lua_type(L, n)) {
case LUA_TNIL:
Py_INCREF(Py_None);
ret = Py_None;
break;
case LUA_TSTRING: {
const char *s = lua_tostring(L, n);
int len = lua_strlen(L, n);
ret = PyString_FromStringAndSize(s, len);
break;
}
case LUA_TNUMBER: {
lua_Number num = lua_tonumber(L, n);
if (num != (long)num) {
ret = PyFloat_FromDouble(
(lua_Number)lua_tonumber(L, n));
} else {
ret = PyInt_FromLong((long)num);
}
break;
}
case LUA_TBOOLEAN:
if (lua_toboolean(L, n)) {
Py_INCREF(Py_True);
ret = Py_True;
} else {
Py_INCREF(Py_False);
ret = Py_False;
}
break;
case LUA_TUSERDATA: {
py_object *obj = (py_object*)
luaL_checkudata(L, n, POBJECT);
if (obj) {
Py_INCREF(obj->o);
ret = obj->o;
break;
}
/* Otherwise go on and handle as custom. */
}
default:
ret = LuaObject_New(n);
break;
}
return ret;
}
static PyObject *LuaCall(lua_State *L, PyObject *args)
{
PyObject *ret = NULL;
PyObject *arg;
int nargs, rc, i;
if (!PyTuple_Check(args)) {
PyErr_SetString(PyExc_TypeError, "tuple expected");
lua_settop(L, 0);
return NULL;
}
nargs = PyTuple_Size(args);
for (i = 0; i != nargs; i++) {
arg = PyTuple_GetItem(args, i);
if (arg == NULL) {
PyErr_Format(PyExc_TypeError,
"failed to get tuple item #%d", i);
lua_settop(L, 0);
return NULL;
}
rc = py_convert(L, arg, 0);
if (!rc) {
PyErr_Format(PyExc_TypeError,
"failed to convert argument #%d", i);
lua_settop(L, 0);
return NULL;
}
}
if (lua_pcall(L, nargs, LUA_MULTRET, 0) != 0) {
PyErr_Format(PyExc_Exception,
"error: %s", lua_tostring(L, -1));
return NULL;
}
nargs = lua_gettop(L);
if (nargs == 1) {
ret = LuaConvert(L, 1);
if (!ret) {
PyErr_SetString(PyExc_TypeError,
"failed to convert return");
lua_settop(L, 0);
Py_DECREF(ret);
return NULL;
}
} else if (nargs > 1) {
ret = PyTuple_New(nargs);
if (!ret) {
PyErr_SetString(PyExc_RuntimeError,
"failed to create return tuple");
lua_settop(L, 0);
return NULL;
}
for (i = 0; i != nargs; i++) {
arg = LuaConvert(L, i+1);
if (!arg) {
PyErr_Format(PyExc_TypeError,
"failed to convert return #%d", i);
lua_settop(L, 0);
Py_DECREF(ret);
return NULL;
}
PyTuple_SetItem(ret, i, arg);
}
} else {
Py_INCREF(Py_None);
ret = Py_None;
}
lua_settop(L, 0);
return ret;
}
#define L LuaState
static PyObject *LuaObject_New(int n)
{
LuaObject *obj = PyObject_New(LuaObject, &LuaObject_Type);
if (obj) {
lua_pushvalue(L, n);
obj->ref = luaL_ref(L, LUA_REGISTRYINDEX);
obj->refiter = 0;
}
return (PyObject*) obj;
}
static void LuaObject_dealloc(LuaObject *self)
{
luaL_unref(L, LUA_REGISTRYINDEX, self->ref);
if (self->refiter)
luaL_unref(L, LUA_REGISTRYINDEX, self->refiter);
self->ob_type->tp_free((PyObject *)self);
}
static PyObject *LuaObject_getattr(PyObject *obj, PyObject *attr)
{
PyObject *ret = NULL;
int rc;
lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
PyErr_SetString(PyExc_RuntimeError, "lost reference");
return NULL;
}
rc = py_convert(L, attr, 0);
if (rc) {
lua_gettable(L, -2);
ret = LuaConvert(L, -1);
} else {
PyErr_SetString(PyExc_ValueError, "can't convert attr/key");
}
lua_settop(L, 0);
return ret;
}
static int LuaObject_setattr(PyObject *obj, PyObject *attr, PyObject *value)
{
int ret = -1;
int rc;
lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
PyErr_SetString(PyExc_RuntimeError, "lost reference");
return -1;
}
if (!lua_istable(L, -1)) {
lua_pop(L, -1);
PyErr_SetString(PyExc_TypeError, "Lua object is not a table");
return -1;
}
rc = py_convert(L, attr, 0);
if (rc) {
rc = py_convert(L, value, 0);
if (rc) {
lua_settable(L, -3);
ret = 0;
} else {
PyErr_SetString(PyExc_ValueError,
"can't convert value");
}
} else {
PyErr_SetString(PyExc_ValueError, "can't convert key/attr");
}
lua_settop(L, 0);
return ret;
}
static PyObject *LuaObject_str(PyObject *obj)
{
PyObject *ret = NULL;
const char *s;
lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
if (luaL_callmeta(L, -1, "__tostring")) {
s = lua_tostring(L, -1);
lua_pop(L, 1);
if (s) ret = PyString_FromString(s);
}
if (!ret) {
int type = lua_type(L, -1);
switch (type) {
case LUA_TTABLE:
case LUA_TFUNCTION:
ret = PyString_FromFormat("<Lua %s at %p>",
lua_typename(L, type),
lua_topointer(L, -1));
break;
case LUA_TUSERDATA:
case LUA_TLIGHTUSERDATA:
ret = PyString_FromFormat("<Lua %s at %p>",
lua_typename(L, type),
lua_touserdata(L, -1));
break;
case LUA_TTHREAD:
ret = PyString_FromFormat("<Lua %s at %p>",
lua_typename(L, type),
(void*)lua_tothread(L, -1));
break;
default:
ret = PyString_FromFormat("<Lua %s>",
lua_typename(L, type));
break;
}
}
lua_pop(L, 1);
return ret;
}
static PyObject *LuaObject_call(PyObject *obj, PyObject *args)
{
lua_settop(L, 0);
lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
return LuaCall(L, args);
}
static PyObject *LuaObject_iternext(LuaObject *obj)
{
PyObject *ret = NULL;
lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
if (obj->refiter == 0)
lua_pushnil(L);
else
lua_rawgeti(L, LUA_REGISTRYINDEX, obj->refiter);
if (lua_next(L, -2) != 0) {
/* Remove value. */
lua_pop(L, 1);
ret = LuaConvert(L, -1);
/* Save key for next iteration. */
if (!obj->refiter)
obj->refiter = luaL_ref(L, LUA_REGISTRYINDEX);
else
lua_rawseti(L, LUA_REGISTRYINDEX, obj->refiter);
} else if (obj->refiter) {
luaL_unref(L, LUA_REGISTRYINDEX, obj->refiter);
obj->refiter = 0;
}
return ret;
}
static int LuaObject_length(LuaObject *obj)
{
int len;
lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
len = luaL_getn(L, -1);
lua_settop(L, 0);
return len;
}
static PyObject *LuaObject_subscript(PyObject *obj, PyObject *key)
{
return LuaObject_getattr(obj, key);
}
static int LuaObject_ass_subscript(PyObject *obj,
PyObject *key, PyObject *value)
{
return LuaObject_setattr(obj, key, value);
}
static PyMappingMethods LuaObject_as_mapping = {
(inquiry)LuaObject_length, /*mp_length*/
(binaryfunc)LuaObject_subscript,/*mp_subscript*/
(objobjargproc)LuaObject_ass_subscript,/*mp_ass_subscript*/
};
PyTypeObject LuaObject_Type = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"lua.custom", /*tp_name*/
sizeof(LuaObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)LuaObject_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
LuaObject_str, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
&LuaObject_as_mapping, /*tp_as_mapping*/
0, /*tp_hash*/
(ternaryfunc)LuaObject_call, /*tp_call*/
LuaObject_str, /*tp_str*/
LuaObject_getattr, /*tp_getattro*/
LuaObject_setattr, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
PyObject_SelfIter, /*tp_iter*/
(iternextfunc)LuaObject_iternext, /*tp_iternext*/
0, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
PyType_GenericAlloc, /*tp_alloc*/
PyType_GenericNew, /*tp_new*/
_PyObject_Del, /*tp_free*/
0, /*tp_is_gc*/
};
PyObject *Lua_run(PyObject *args, int eval)
{
PyObject *ret;
char *buf = NULL;
char *s;
int len;
if (!PyArg_ParseTuple(args, "s#", &s, &len))
return NULL;
if (eval) {
buf = (char *) malloc(sizeof("return ")+len);
strcpy(buf, "return ");
strncat(buf, s, len);
s = buf;
len = sizeof("return ")-1+len;
}
if (luaL_loadbuffer(L, s, len, "<python>") != 0) {
PyErr_Format(PyExc_RuntimeError,
"error loading code: %s",
lua_tostring(L, -1));
return NULL;
}
free(buf);
if (lua_pcall(L, 0, 1, 0) != 0) {
PyErr_Format(PyExc_RuntimeError,
"error executing code: %s",
lua_tostring(L, -1));
return NULL;
}
ret = LuaConvert(L, -1);
lua_settop(L, 0);
return ret;
}
PyObject *Lua_execute(PyObject *self, PyObject *args)
{
return Lua_run(args, 0);
}
PyObject *Lua_eval(PyObject *self, PyObject *args)
{
return Lua_run(args, 1);
}
PyObject *Lua_globals(PyObject *self, PyObject *args)
{
PyObject *ret = NULL;
lua_pushliteral(L, "_G");
lua_rawget(L, LUA_GLOBALSINDEX);
if (lua_isnil(L, -1)) {
PyErr_SetString(PyExc_RuntimeError,
"lost globals reference");
lua_pop(L, 1);
return NULL;
}
ret = LuaConvert(L, -1);
if (!ret)
PyErr_Format(PyExc_TypeError,
"failed to convert globals table");
lua_settop(L, 0);
return ret;
}
static PyObject *Lua_require(PyObject *self, PyObject *args)
{
lua_pushliteral(L, "require");
lua_rawget(L, LUA_GLOBALSINDEX);
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
PyErr_SetString(PyExc_RuntimeError, "require is not defined");
return NULL;
}
return LuaCall(L, args);
}
static PyMethodDef lua_methods[] = {
{"execute", Lua_execute, METH_VARARGS, NULL},
{"eval", Lua_eval, METH_VARARGS, NULL},
{"globals", Lua_globals, METH_NOARGS, NULL},
{"require", Lua_require, METH_VARARGS, NULL},
{NULL, NULL}
};
DL_EXPORT(void)
initlua(void)
{
PyObject *m;
m = Py_InitModule("lua", lua_methods);
if (!L) {
L = lua_open();
luaopen_base(L);
luaopen_table(L);
luaopen_io(L);
luaopen_string(L);
luaopen_debug(L);
luaopen_loadlib(L);
luaopen_python(L);
lua_settop(L, 0);
}
}

View File

@ -1,42 +0,0 @@
/*
Lunatic Python
--------------
Copyright (c) 2002-2005 Gustavo Niemeyer <gustavo@niemeyer.net>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef LUAINPYTHON_H
#define LUAINPYTHON_H
typedef struct {
PyObject_HEAD
int ref;
int refiter;
} LuaObject;
PyAPI_DATA(PyTypeObject) LuaObject_Type;
#define LuaObject_Check(op) PyObject_TypeCheck(op, &LuaObject_Type)
PyObject *LuaConvert(lua_State *L, int n);
extern lua_State *LuaState;
DL_EXPORT(void) initlua(void);
#endif

View File

@ -1,611 +0,0 @@
/*
Lunatic Python
--------------
Copyright (c) 2002-2005 Gustavo Niemeyer <gustavo@niemeyer.net>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <Python.h>
#include <lua.h>
#include <lauxlib.h>
#include "pythoninlua.h"
#include "luainpython.h"
static int py_asfunc_call(lua_State *L);
static int py_convert_custom(lua_State *L, PyObject *o, int asindx)
{
int ret = 0;
py_object *obj = (py_object*) lua_newuserdata(L, sizeof(py_object));
if (obj) {
Py_INCREF(o);
obj->o = o;
obj->asindx = asindx;
luaL_getmetatable(L, POBJECT);
lua_setmetatable(L, -2);
ret = 1;
} else {
luaL_error(L, "failed to allocate userdata object");
}
return ret;
}
int py_convert(lua_State *L, PyObject *o, int withnone)
{
int ret = 0;
if (o == Py_None) {
if (withnone) {
lua_pushliteral(L, "Py_None");
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
luaL_error(L, "lost none from registry");
}
} else {
/* Not really needed, but this way we may check
* for errors with ret == 0. */
lua_pushnil(L);
ret = 1;
}
} else if (o == Py_True) {
lua_pushboolean(L, 1);
} else if (o == Py_False) {
lua_pushboolean(L, 0);
} else if (PyString_Check(o)) {
char *s;
int len;
PyString_AsStringAndSize(o, &s, &len);
lua_pushlstring(L, s, len);
ret = 1;
} else if (PyInt_Check(o) || PyFloat_Check(o)) {
lua_pushnumber(L, (lua_Number)PyInt_AsLong(o));
ret = 1;
} else if (LuaObject_Check(o)) {
lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)o)->ref);
ret = 1;
} else {
int asindx = 0;
if (PyDict_Check(o) || PyList_Check(o) || PyTuple_Check(o))
asindx = 1;
ret = py_convert_custom(L, o, asindx);
if (ret && !asindx &&
(PyFunction_Check(o) || PyCFunction_Check(o)))
lua_pushcclosure(L, py_asfunc_call, 1);
}
return ret;
}
static int py_object_call(lua_State *L)
{
py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT);
PyObject *args;
PyObject *value;
int nargs = lua_gettop(L)-1;
int ret = 0;
int i;
if (!obj) {
luaL_argerror(L, 1, "not a python object");
return 0;
}
if (!PyCallable_Check(obj->o)) {
luaL_error(L, "object is not callable");
return 0;
}
args = PyTuple_New(nargs);
if (!args) {
PyErr_Print();
luaL_error(L, "failed to create arguments tuple");
return 0;
}
for (i = 0; i != nargs; i++) {
PyObject *arg = LuaConvert(L, i+2);
if (!arg) {
luaL_error(L, "failed to convert argument #%d", i+1);
Py_DECREF(args);
return 0;
}
PyTuple_SetItem(args, i, arg);
}
value = PyObject_CallObject(obj->o, args);
if (value) {
ret = py_convert(L, value, 0);
Py_DECREF(value);
} else {
PyErr_Print();
luaL_error(L, "error calling python function");
}
return ret;
}
static int _p_object_newindex_set(lua_State *L, py_object *obj,
int keyn, int valuen)
{
PyObject *value;
PyObject *key = LuaConvert(L, keyn);
if (!key) {
luaL_argerror(L, 1, "failed to convert key");
return 0;
}
if (!lua_isnil(L, valuen)) {
value = LuaConvert(L, valuen);
if (!value) {
Py_DECREF(key);
luaL_argerror(L, 1, "failed to convert value");
return 0;
}
if (PyObject_SetItem(obj->o, key, value) == -1) {
PyErr_Print();
luaL_error(L, "failed to set item");
}
Py_DECREF(value);
} else {
if (PyObject_DelItem(obj->o, key) == -1) {
PyErr_Print();
luaL_error(L, "failed to delete item");
}
}
Py_DECREF(key);
return 0;
}
static int py_object_newindex_set(lua_State *L)
{
py_object *obj = (py_object*) luaL_checkudata(L, lua_upvalueindex(1),
POBJECT);
if (lua_gettop(L) != 2) {
luaL_error(L, "invalid arguments");
return 0;
}
return _p_object_newindex_set(L, obj, 1, 2);
}
static int py_object_newindex(lua_State *L)
{
py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT);
const char *attr;
PyObject *value;
if (!obj) {
luaL_argerror(L, 1, "not a python object");
return 0;
}
if (obj->asindx)
return _p_object_newindex_set(L, obj, 2, 3);
attr = luaL_checkstring(L, 2);
if (!attr) {
luaL_argerror(L, 2, "string needed");
return 0;
}
value = LuaConvert(L, 3);
if (!value) {
luaL_argerror(L, 1, "failed to convert value");
return 0;
}
if (PyObject_SetAttrString(obj->o, (char*)attr, value) == -1) {
Py_DECREF(value);
PyErr_Print();
luaL_error(L, "failed to set value");
return 0;
}
Py_DECREF(value);
return 0;
}
static int _p_object_index_get(lua_State *L, py_object *obj, int keyn)
{
PyObject *key = LuaConvert(L, keyn);
PyObject *item;
int ret = 0;
if (!key) {
luaL_argerror(L, 1, "failed to convert key");
return 0;
}
item = PyObject_GetItem(obj->o, key);
Py_DECREF(key);
if (item) {
ret = py_convert(L, item, 0);
Py_DECREF(item);
} else {
PyErr_Clear();
if (lua_gettop(L) > keyn) {
lua_pushvalue(L, keyn+1);
ret = 1;
}
}
return ret;
}
static int py_object_index_get(lua_State *L)
{
py_object *obj = (py_object*) luaL_checkudata(L, lua_upvalueindex(1),
POBJECT);
int top = lua_gettop(L);
if (top < 1 || top > 2) {
luaL_error(L, "invalid arguments");
return 0;
}
return _p_object_index_get(L, obj, 1);
}
static int py_object_index(lua_State *L)
{
py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT);
const char *attr;
PyObject *value;
int ret = 0;
if (!obj) {
luaL_argerror(L, 1, "not a python object");
return 0;
}
if (obj->asindx)
return _p_object_index_get(L, obj, 2);
attr = luaL_checkstring(L, 2);
if (!attr) {
luaL_argerror(L, 2, "string needed");
return 0;
}
if (attr[0] == '_' && strcmp(attr, "__get") == 0) {
lua_pushvalue(L, 1);
lua_pushcclosure(L, py_object_index_get, 1);
return 1;
} else if (attr[0] == '_' && strcmp(attr, "__set") == 0) {
lua_pushvalue(L, 1);
lua_pushcclosure(L, py_object_newindex_set, 1);
return 1;
}
value = PyObject_GetAttrString(obj->o, (char*)attr);
if (value) {
ret = py_convert(L, value, 0);
Py_DECREF(value);
} else {
PyErr_Clear();
luaL_error(L, "unknown attribute in python object");
}
return ret;
}
static int py_object_gc(lua_State *L)
{
py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT);
if (obj) {
Py_DECREF(obj->o);
}
return 0;
}
static int py_object_tostring(lua_State *L)
{
py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT);
if (obj) {
PyObject *repr = PyObject_Str(obj->o);
if (!repr) {
char buf[256];
snprintf(buf, 256, "python object: %p", obj->o);
lua_pushstring(L, buf);
PyErr_Clear();
} else {
char *s;
int len;
PyString_AsStringAndSize(repr, &s, &len);
lua_pushlstring(L, s, len);
Py_DECREF(repr);
}
}
return 1;
}
static const luaL_reg py_object_lib[] = {
{"__call", py_object_call},
{"__index", py_object_index},
{"__newindex", py_object_newindex},
{"__gc", py_object_gc},
{"__tostring", py_object_tostring},
{NULL, NULL}
};
static int py_run(lua_State *L, int eval)
{
const char *s;
char *buffer = NULL;
PyObject *m, *d, *o;
int ret = 0;
int len;
s = luaL_checkstring(L, 1);
if (!s)
return 0;
if (!eval) {
len = strlen(s)+1;
buffer = (char *) malloc(len+1);
if (!buffer) {
luaL_error(L, "Failed allocating buffer for execution");
return 0;
}
strcpy(buffer, s);
buffer[len-1] = '\n';
buffer[len] = '\0';
s = buffer;
}
m = PyImport_AddModule("__main__");
if (!m) {
free(buffer);
luaL_error(L, "Can't get __main__ module");
return 0;
}
d = PyModule_GetDict(m);
o = PyRun_StringFlags(s, eval ? Py_eval_input : Py_single_input,
d, d, NULL);
free(buffer);
if (!o) {
PyErr_Print();
return 0;
}
if (py_convert(L, o, 0))
ret = 1;
Py_DECREF(o);
if (Py_FlushLine())
PyErr_Clear();
return ret;
}
static int py_execute(lua_State *L)
{
return py_run(L, 0);
}
static int py_eval(lua_State *L)
{
return py_run(L, 1);
}
static int py_asindx(lua_State *L)
{
py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT);
if (obj)
return py_convert_custom(L, obj->o, 1);
else
luaL_argerror(L, 1, "not a python object");
return 0;
}
static int py_asattr(lua_State *L)
{
py_object *obj = (py_object*) luaL_checkudata(L, 1, POBJECT);
if (obj)
return py_convert_custom(L, obj->o, 0);
else
luaL_argerror(L, 1, "not a python object");
return 0;
}
static int py_asfunc_call(lua_State *L)
{
lua_pushvalue(L, lua_upvalueindex(1));
lua_insert(L, 1);
return py_object_call(L);
}
static int py_asfunc(lua_State *L)
{
int ret = 0;
if (luaL_checkudata(L, 1, POBJECT)) {
lua_pushcclosure(L, py_asfunc_call, 1);
ret = 1;
} else {
luaL_argerror(L, 1, "not a python object");
}
return ret;
}
static int py_globals(lua_State *L)
{
PyObject *globals;
if (lua_gettop(L) != 0) {
luaL_error(L, "invalid arguments");
return 0;
}
globals = PyEval_GetGlobals();
if (!globals) {
PyObject *module = PyImport_AddModule("__main__");
if (!module) {
luaL_error(L, "Can't get __main__ module");
return 0;
}
globals = PyModule_GetDict(module);
}
if (!globals) {
PyErr_Print();
luaL_error(L, "can't get globals");
return 0;
}
return py_convert_custom(L, globals, 1);
}
static int py_locals(lua_State *L)
{
PyObject *locals;
if (lua_gettop(L) != 0) {
luaL_error(L, "invalid arguments");
return 0;
}
locals = PyEval_GetLocals();
if (!locals)
return py_globals(L);
return py_convert_custom(L, locals, 1);
}
static int py_builtins(lua_State *L)
{
PyObject *builtins;
if (lua_gettop(L) != 0) {
luaL_error(L, "invalid arguments");
return 0;
}
builtins = PyEval_GetBuiltins();
if (!builtins) {
PyErr_Print();
luaL_error(L, "failed to get builtins");
return 0;
}
return py_convert_custom(L, builtins, 1);
}
static int py_import(lua_State *L)
{
const char *name = luaL_checkstring(L, 1);
PyObject *module;
int ret;
if (!name) {
luaL_argerror(L, 1, "module name expected");
return 0;
}
module = PyImport_ImportModule((char*)name);
if (!module) {
PyErr_Print();
luaL_error(L, "failed importing '%s'", name);
return 0;
}
ret = py_convert_custom(L, module, 0);
Py_DECREF(module);
return ret;
}
static const luaL_reg py_lib[] = {
{"execute", py_execute},
{"eval", py_eval},
{"asindx", py_asindx},
{"asattr", py_asattr},
{"asfunc", py_asfunc},
{"locals", py_locals},
{"globals", py_globals},
{"builtins", py_builtins},
{"import", py_import},
{NULL, NULL}
};
LUA_API int luaopen_python(lua_State *L)
{
int rc;
/* Register module */
luaL_openlib(L, "python", py_lib, 0);
/* Register python object metatable */
luaL_newmetatable(L, POBJECT);
luaL_openlib(L, NULL, py_object_lib, 0);
lua_pop(L, 1);
/* Initialize Lua state in Python territory */
if (!LuaState) LuaState = L;
/* Initialize Python interpreter */
if (!Py_IsInitialized()) {
PyObject *luam, *mainm, *maind;
char *argv[] = {"<lua>", 0};
Py_SetProgramName("<lua>");
Py_Initialize();
PySys_SetArgv(1, argv);
initlua();
/* Import 'lua' automatically. */
luam = PyImport_ImportModule("lua");
if (!luam) {
luaL_error(L, "Can't import lua module");
} else {
mainm = PyImport_AddModule("__main__");
if (!mainm) {
luaL_error(L, "Can't get __main__ module");
} else {
maind = PyModule_GetDict(mainm);
PyDict_SetItemString(maind, "lua", luam);
Py_DECREF(luam);
}
}
}
/* Register 'none' */
lua_pushliteral(L, "Py_None");
rc = py_convert_custom(L, Py_None, 0);
if (rc) {
lua_pushliteral(L, "none");
lua_pushvalue(L, -2);
lua_rawset(L, -5); /* python.none */
lua_rawset(L, LUA_REGISTRYINDEX); /* registry.Py_None */
} else {
lua_pop(L, 1);
luaL_error(L, "failed to convert none object");
}
return 0;
}

View File

@ -1,37 +0,0 @@
/*
Lunatic Python
--------------
Copyright (c) 2002-2005 Gustavo Niemeyer <gustavo@niemeyer.net>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PYTHONINLUA_H
#define PYTHONINLUA_H
#define POBJECT "POBJECT"
int py_convert(lua_State *L, PyObject *o, int withnone);
typedef struct {
PyObject *o;
int asindx;
} py_object;
LUA_API int luaopen_python(lua_State *L);
#endif

0
rasters/biomes.tif Executable file → Normal file
View File

0
rasters/dem.tif Executable file → Normal file
View File

0
rasters/water.tif Executable file → Normal file
View File