From 39162de15a2603f1282241aef412ef1b70162b27 Mon Sep 17 00:00:00 2001 From: sapier Date: Fri, 28 Nov 2014 20:06:34 +0100 Subject: Make hud use fontengine too Fix non coding style conforming glb_fontengine to g_fontengine Fix fonts never been deleted due to grabbed to often --- src/defaultsettings.cpp | 2 +- src/drawscene.cpp | 4 ++-- src/fontengine.cpp | 6 ++---- src/fontengine.h | 2 +- src/game.cpp | 23 +++++++++++------------ src/guiChatConsole.cpp | 2 +- src/guiEngine.cpp | 10 +++++----- src/guiFormSpecMenu.cpp | 10 +++++----- src/hud.cpp | 12 ++++++------ src/hud.h | 7 ++----- src/main.cpp | 8 ++++---- 11 files changed, 40 insertions(+), 46 deletions(-) (limited to 'src') diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index a8ae9e251..1ebf5dc49 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -195,7 +195,7 @@ void set_default_settings(Settings *settings) settings->setDefault("mono_font_size", fontsize.str()); settings->setDefault("fallback_font_size", fontsize.str()); #else - settings->setDefault("freetype", "false"); + settings->setDefault("freetype", "false"); settings->setDefault("font_path", porting::getDataPath("fonts" DIR_DELIM "lucida_sans")); settings->setDefault("mono_font_path", porting::getDataPath("fonts" DIR_DELIM "mono_dejavu_sans")); diff --git a/src/drawscene.cpp b/src/drawscene.cpp index ba3316143..8ba2be1b0 100644 --- a/src/drawscene.cpp +++ b/src/drawscene.cpp @@ -507,7 +507,7 @@ void draw_load_screen(const std::wstring &text, IrrlichtDevice* device, video::IVideoDriver* driver = device->getVideoDriver(); v2u32 screensize = porting::getWindowSize(); - v2s32 textsize(glb_fontengine->getTextWidth(text), glb_fontengine->getLineHeight()); + v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight()); v2s32 center(screensize.X / 2, screensize.Y / 2); core::rect textrect(center - textsize / 2, center + textsize / 2); @@ -534,7 +534,7 @@ void draw_load_screen(const std::wstring &text, IrrlichtDevice* device, // before with default settings 342 * porting::getDisplayDensity() * g_settings->getFloat("gui_scaling"), - glb_fontengine->getTextHeight() * 2); + g_fontengine->getTextHeight() * 2); core::rect barrect(center - barsize / 2, center + barsize / 2); driver->draw2DRectangle(video::SColor(255, 255, 255, 255),barrect, NULL); // border diff --git a/src/fontengine.cpp b/src/fontengine.cpp index c1e36d6c8..f73f47ff7 100644 --- a/src/fontengine.cpp +++ b/src/fontengine.cpp @@ -33,11 +33,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #define MAX_FONT_SIZE_OFFSET 10 /** reference to access font engine, has to be initialized by main */ -FontEngine* glb_fontengine = NULL; +FontEngine* g_fontengine = NULL; /** callback to be used on change of font size setting */ static void font_setting_changed(const std::string) { - glb_fontengine->readSettings(); + g_fontengine->readSettings(); } /******************************************************************************/ @@ -349,7 +349,6 @@ void FontEngine::initFont(unsigned int basesize, FontMode mode) font_shadow_alpha); if (font != NULL) { - font->grab(); m_font_cache[mode][basesize] = font; } else { @@ -457,7 +456,6 @@ void FontEngine::initSimpleFont(unsigned int basesize, FontMode mode) } if (font != NULL) { - font->grab(); m_font_cache[mode][basesize] = font; } } diff --git a/src/fontengine.h b/src/fontengine.h index 6a5339770..679a96bea 100644 --- a/src/fontengine.h +++ b/src/fontengine.h @@ -135,6 +135,6 @@ private: }; /** interface to access main font engine*/ -extern FontEngine* glb_fontengine; +extern FontEngine* g_fontengine; #endif diff --git a/src/game.cpp b/src/game.cpp index c2b53420e..b6f96acc3 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -1159,7 +1159,7 @@ static void updateChat(Client &client, f32 dtime, bool show_debug, // Display all messages in a static text element unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount(); std::wstring recent_chat = chat_backend.getRecentChat(); - unsigned int line_height = glb_fontengine->getLineHeight(); + unsigned int line_height = g_fontengine->getLineHeight(); guitext_chat->setText(recent_chat.c_str()); @@ -1170,7 +1170,7 @@ static void updateChat(Client &client, f32 dtime, bool show_debug, chat_y += line_height; // first pass to calculate height of text to be set - s32 width = std::min(glb_fontengine->getTextWidth(recent_chat) + 10, + s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10, porting::getWindowSize().X - 20); core::rect rect(10, chat_y, width, chat_y + porting::getWindowSize().Y); guitext_chat->setRelativePosition(rect); @@ -1923,7 +1923,7 @@ bool Game::createClient(const std::string &playername, } // Update cached textures, meshes and materials - client->afterContentReceived(device, glb_fontengine->getFont()); + client->afterContentReceived(device, g_fontengine->getFont()); /* Camera */ @@ -1981,8 +1981,7 @@ bool Game::createClient(const std::string &playername, player->hurt_tilt_timer = 0; player->hurt_tilt_strength = 0; - hud = new Hud(driver, smgr, guienv, glb_fontengine->getFont(), - glb_fontengine->getTextHeight(), gamedef, player, local_inventory); + hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory); if (!hud) { *error_message = L"Memory error: could not create HUD"; @@ -2011,7 +2010,7 @@ bool Game::initGui(std::wstring *error_message) // Object infos are shown in this guitext_info = guienv->addStaticText( L"", - core::rect(0, 0, 400, glb_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200), + core::rect(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200), false, true, guiroot); // Status text (displays info when showing and hiding GUI stuff, etc.) @@ -2342,7 +2341,7 @@ void Game::updateProfilers(const GameRunData &run_data, const RunStats &stats, g_profiler->print(infostream); } - update_profiler_gui(guitext_profiler, glb_fontengine, + update_profiler_gui(guitext_profiler, g_fontengine, run_data.profiler_current_page, run_data.profiler_max_page); g_profiler->clear(); @@ -2753,7 +2752,7 @@ void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page, *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1); // FIXME: This updates the profiler with incomplete values - update_profiler_gui(guitext_profiler, glb_fontengine, *profiler_current_page, + update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page, profiler_max_page); if (*profiler_current_page != 0) { @@ -3872,7 +3871,7 @@ void Game::updateFrame(std::vector &highlight_boxes, Profiler graph */ if (flags.show_profiler_graph) - graph->draw(10, screensize.Y - 10, driver, glb_fontengine->getFont()); + graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont()); /* Damage flash @@ -3955,7 +3954,7 @@ void Game::updateGui(float *statustext_time, const RunStats& stats, if (guitext->isVisible()) { core::rect rect( 5, 5, - screensize.X, 5 + glb_fontengine->getTextHeight() + screensize.X, 5 + g_fontengine->getTextHeight() ); guitext->setRelativePosition(rect); } @@ -3973,8 +3972,8 @@ void Game::updateGui(float *statustext_time, const RunStats& stats, guitext2->setVisible(true); core::rect rect( - 5, 5 + glb_fontengine->getTextHeight(), - screensize.X, 5 + glb_fontengine->getTextHeight() * 2 + 5, 5 + g_fontengine->getTextHeight(), + screensize.X, 5 + g_fontengine->getTextHeight() * 2 ); guitext2->setRelativePosition(rect); } else { diff --git a/src/guiChatConsole.cpp b/src/guiChatConsole.cpp index c9f41c76f..62ce0d1e1 100644 --- a/src/guiChatConsole.cpp +++ b/src/guiChatConsole.cpp @@ -92,7 +92,7 @@ GUIChatConsole::GUIChatConsole( m_background_color.setBlue(255); } - m_font = glb_fontengine->getFont(FONT_SIZE_UNSPECIFIED, FM_Mono); + m_font = g_fontengine->getFont(FONT_SIZE_UNSPECIFIED, FM_Mono); if (m_font == NULL) { diff --git a/src/guiEngine.cpp b/src/guiEngine.cpp index e941003fa..814a7504a 100644 --- a/src/guiEngine.cpp +++ b/src/guiEngine.cpp @@ -174,7 +174,7 @@ GUIEngine::GUIEngine( irr::IrrlichtDevice* dev, std::wstring t = narrow_to_wide(std::string("Minetest ") + minetest_version_hash); - core::rect rect(0, 0, glb_fontengine->getTextWidth(t), glb_fontengine->getTextHeight()); + core::rect rect(0, 0, g_fontengine->getTextWidth(t), g_fontengine->getTextHeight()); rect += v2s32(4, 0); m_irr_toplefttext = @@ -260,14 +260,14 @@ void GUIEngine::run() cloudInit(); - unsigned int text_height = glb_fontengine->getTextHeight(); + unsigned int text_height = g_fontengine->getTextHeight(); while(m_device->run() && (!m_startgame) && (!m_kill)) { //check if we need to update the "upper left corner"-text - if (text_height != glb_fontengine->getTextHeight()) { + if (text_height != g_fontengine->getTextHeight()) { updateTopLeftTextSize(); - text_height = glb_fontengine->getTextHeight(); + text_height = g_fontengine->getTextHeight(); } driver->beginScene(true, true, video::SColor(255,140,186,250)); @@ -590,7 +590,7 @@ void GUIEngine::updateTopLeftTextSize() { std::wstring text = m_irr_toplefttext->getText(); - core::rect rect(0, 0, glb_fontengine->getTextWidth(text), glb_fontengine->getTextHeight()); + core::rect rect(0, 0, g_fontengine->getTextWidth(text), g_fontengine->getTextHeight()); rect += v2s32(4, 0); m_irr_toplefttext->remove(); diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index c81238a65..0a7a82399 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -91,11 +91,11 @@ static gui::IGUIFont *select_font_by_line_height(double target_line_height) unsigned int hireq = ceil(target_line_height / porting::getDisplayDensity() / g_settings->getFloat("gui_scaling")); - unsigned int lohgt = font_line_height(glb_fontengine->getFont(loreq)); - unsigned int hihgt = font_line_height(glb_fontengine->getFont(hireq)); + unsigned int lohgt = font_line_height(g_fontengine->getFont(loreq)); + unsigned int hihgt = font_line_height(g_fontengine->getFont(hireq)); while(hireq - loreq > 1 && lohgt != hihgt) { unsigned int nureq = (loreq + hireq) >> 1; - unsigned int nuhgt = font_line_height(glb_fontengine->getFont(nureq)); + unsigned int nuhgt = font_line_height(g_fontengine->getFont(nureq)); if(nuhgt < target_line_height) { loreq = nureq; lohgt = nuhgt; @@ -104,7 +104,7 @@ static gui::IGUIFont *select_font_by_line_height(double target_line_height) hihgt = nuhgt; } } - return glb_fontengine->getFont(target_line_height - lohgt < hihgt - target_line_height ? loreq : hireq); + return g_fontengine->getFont(target_line_height - lohgt < hihgt - target_line_height ? loreq : hireq); } GUIFormSpecMenu::GUIFormSpecMenu(irr::IrrlichtDevice* dev, @@ -1992,7 +1992,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) // Non-size[] form must consist only of text fields and // implicit "Proceed" button. Use default font, and // temporary form size which will be recalculated below. - m_font = glb_fontengine->getFont(); + m_font = g_fontengine->getFont(); m_btn_height = font_line_height(m_font) * 0.875; DesiredRect = core::rect( mydata.screensize.X/2 - 580/2, diff --git a/src/hud.cpp b/src/hud.cpp index 02071835f..eb2dca573 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -31,6 +31,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "localplayer.h" #include "camera.h" #include "porting.h" +#include "fontengine.h" #include #ifdef HAVE_TOUCHSCREENGUI @@ -38,14 +39,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #endif Hud::Hud(video::IVideoDriver *driver, scene::ISceneManager* smgr, - gui::IGUIEnvironment* guienv, gui::IGUIFont *font, - u32 text_height, IGameDef *gamedef, - LocalPlayer *player, Inventory *inventory) { + gui::IGUIEnvironment* guienv, IGameDef *gamedef, LocalPlayer *player, + Inventory *inventory) { this->driver = driver; this->smgr = smgr; this->guienv = guienv; - this->font = font; - this->text_height = text_height; this->gamedef = gamedef; this->player = player; this->inventory = inventory; @@ -156,7 +154,7 @@ void Hud::drawItem(const ItemStack &item, const core::rect& rect, bool sele video::SColor bgcolor2(128, 0, 0, 0); if (!use_hotbar_image) driver->draw2DRectangle(bgcolor2, rect, NULL); - drawItemStack(driver, font, item, rect, NULL, gamedef); + drawItemStack(driver, g_fontengine->getFont(), item, rect, NULL, gamedef); } //NOTE: selectitem = 0 -> no selected; selectitem 1-based @@ -240,6 +238,8 @@ void Hud::drawItems(v2s32 upperleftpos, s32 itemcount, s32 offset, void Hud::drawLuaElements(v3s16 camera_offset) { + uint32_t text_height = g_fontengine->getTextHeight(); + irr::gui::IGUIFont* font = g_fontengine->getFont(); for (size_t i = 0; i != player->maxHudId(); i++) { HudElement *e = player->getHud(i); if (!e) diff --git a/src/hud.h b/src/hud.h index 9969fce73..2e6838eb1 100644 --- a/src/hud.h +++ b/src/hud.h @@ -103,8 +103,6 @@ public: video::IVideoDriver *driver; scene::ISceneManager* smgr; gui::IGUIEnvironment *guienv; - gui::IGUIFont *font; - u32 text_height; IGameDef *gamedef; LocalPlayer *player; Inventory *inventory; @@ -120,9 +118,8 @@ public: v3s16 camera_offset; Hud(video::IVideoDriver *driver,scene::ISceneManager* smgr, - gui::IGUIEnvironment* guienv, gui::IGUIFont *font, - u32 text_height, IGameDef *gamedef, - LocalPlayer *player, Inventory *inventory); + gui::IGUIEnvironment* guienv, IGameDef *gamedef, LocalPlayer *player, + Inventory *inventory); void drawHotbar(u16 playeritem); void resizeHotbar(); diff --git a/src/main.cpp b/src/main.cpp index 7141bec66..d9fa8faa2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1569,8 +1569,8 @@ ClientLauncher::~ClientLauncher() if (input) delete input; - if (glb_fontengine) - delete glb_fontengine; + if (g_fontengine) + delete g_fontengine; if (device) device->drop(); @@ -1630,8 +1630,8 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 100, 50)); skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255)); - glb_fontengine = new FontEngine(g_settings, guienv); - assert(glb_fontengine != NULL); + g_fontengine = new FontEngine(g_settings, guienv); + assert(g_fontengine != NULL); #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2 // Irrlicht 1.8 input colours -- cgit v1.2.3 80 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
--[[
More Blocks: circular saw

Copyright (c) 2011-2017 Hugo Locurcio, Sokomine and contributors.
Licensed under the zlib license. See LICENSE.md for more information.
--]]

local S = moreblocks.intllib

circular_saw = {}

circular_saw.known_stairs = setmetatable({}, {
	__newindex = function(k, v)
		local modname = minetest.get_current_modname()
		print(("WARNING: mod %s tried to add node %s to the circular saw"
				.. " manually."):format(modname, v))
	end,
})

-- This is populated by stairsplus:register_all:
circular_saw.known_nodes = {}

-- How many microblocks does this shape at the output inventory cost:
-- It may cause slight loss, but no gain.
circular_saw.cost_in_microblocks = {
	1, 1, 1, 1, 1, 1, 1, 2,
	2, 3, 2, 4, 2, 4, 5, 6,
	7, 1, 1, 2, 4, 6, 7, 8,
	1, 2, 2, 3, 1, 1, 2, 4,
	4, 2, 6, 7, 3, 7, 7, 4,
	8, 3, 2, 6, 2, 1, 3, 4
}

circular_saw.names = {
	{"micro", "_1"},
	{"panel", "_1"},
	{"micro", "_2"},
	{"panel", "_2"},
	{"micro", "_4"},
	{"panel", "_4"},
	{"micro", ""},
	{"panel", ""},

	{"micro", "_12"},
	{"panel", "_12"},
	{"micro", "_14"},
	{"panel", "_14"},
	{"micro", "_15"},
	{"panel", "_15"},
	{"stair", "_outer"},
	{"stair", ""},

	{"stair", "_inner"},
	{"slab", "_1"},
	{"slab", "_2"},
	{"slab", "_quarter"},
	{"slab", ""},
	{"slab", "_three_quarter"},
	{"slab", "_14"},
	{"slab", "_15"},

	{"slab", "_two_sides"},
	{"slab", "_three_sides"},
	{"slab", "_three_sides_u"},
	{"stair", "_half"},
	{"stair", "_alt_1"},
	{"stair", "_alt_2"},
	{"stair", "_alt_4"},
	{"stair", "_alt"},

	{"slope", ""},
	{"slope", "_half"},
	{"slope", "_half_raised"},
	{"slope", "_inner"},
	{"slope", "_inner_half"},
	{"slope", "_inner_half_raised"},
	{"slope", "_inner_cut"},
	{"slope", "_inner_cut_half"},

	{"slope", "_inner_cut_half_raised"},
	{"slope", "_outer"},
	{"slope", "_outer_half"},
	{"slope", "_outer_half_raised"},
	{"slope", "_outer_cut"},
	{"slope", "_outer_cut_half"},
	{"slope", "_outer_cut_half_raised"},
	{"slope", "_cut"},
}

function circular_saw:get_cost(inv, stackname)
	for i, item in pairs(inv:get_list("output")) do
		if item:get_name() == stackname then
			return circular_saw.cost_in_microblocks[i]
		end
	end
end

function circular_saw:get_output_inv(modname, material, amount, max)
	if (not max or max < 1 or max > 99) then max = 99 end

	local list = {}
	local pos = #list

	-- If there is nothing inside, display empty inventory:
	if amount < 1 then
		return list
	end

	for i = 1, #circular_saw.names do
		local t = circular_saw.names[i]
		local cost = circular_saw.cost_in_microblocks[i]
		local balance = math.min(math.floor(amount/cost), max)
		local nodename = modname .. ":" .. t[1] .. "_" .. material .. t[2]
		if  minetest.registered_nodes[nodename] then
			pos = pos + 1
			list[pos] = nodename .. " " .. balance
		end
	end
	return list
end


-- Reset empty circular_saw after last full block has been taken out
-- (or the circular_saw has been placed the first time)
-- Note: max_offered is not reset:
function circular_saw:reset(pos)
	local meta = minetest.get_meta(pos)
	local inv  = meta:get_inventory()

	inv:set_list("input",  {})
	inv:set_list("micro",  {})
	inv:set_list("output", {})
	meta:set_int("anz", 0)

	meta:set_string("infotext",
			S("Circular Saw is empty (owned by %s)")
			:format(meta:get_string("owner") or ""))
end


-- Player has taken something out of the box or placed something inside
-- that amounts to count microblocks:
function circular_saw:update_inventory(pos, amount)
	local meta          = minetest.get_meta(pos)
	local inv           = meta:get_inventory()

	amount = meta:get_int("anz") + amount

	-- The material is recycled automaticly.
	inv:set_list("recycle",  {})

	if amount < 1 then -- If the last block is taken out.
		self:reset(pos)
		return
	end

	local stack = inv:get_stack("input",  1)
	-- At least one "normal" block is necessary to see what kind of stairs are requested.
	if stack:is_empty() then
		-- Any microblocks not taken out yet are now lost.
		-- (covers material loss in the machine)
		self:reset(pos)
		return

	end
	local node_name = stack:get_name() or ""
	local name_parts = circular_saw.known_nodes[node_name] or ""
	local modname  = name_parts[1] or ""
	local material = name_parts[2] or ""

	inv:set_list("input", { -- Display as many full blocks as possible:
		node_name.. " " .. math.floor(amount / 8)
	})

	-- The stairnodes made of default nodes use moreblocks namespace, other mods keep own:
	if modname == "default" then
		modname = "moreblocks"
	end
	-- print("circular_saw set to " .. modname .. " : "
	--	.. material .. " with " .. (amount) .. " microblocks.")

	-- 0-7 microblocks may remain left-over:
	inv:set_list("micro", {
		modname .. ":micro_" .. material .. "_bottom " .. (amount % 8)
	})
	-- Display:
	inv:set_list("output",
		self:get_output_inv(modname, material, amount,
				meta:get_int("max_offered")))
	-- Store how many microblocks are available:
	meta:set_int("anz", amount)

	meta:set_string("infotext",
			S("Circular Saw is working on %s (owned by %s)")
			:format(material, meta:get_string("owner") or ""))
end


-- The amount of items offered per shape can be configured:
function circular_saw.on_receive_fields(pos, formname, fields, sender)
	local meta = minetest.get_meta(pos)
	local max = tonumber(fields.max_offered)
	if max and max > 0 then
		meta:set_string("max_offered",  max)
		-- Update to show the correct number of items:
		circular_saw:update_inventory(pos, 0)
	end
end


-- Moving the inventory of the circular_saw around is not allowed because it
-- is a fictional inventory. Moving inventory around would be rather
-- impractical and make things more difficult to calculate:
function circular_saw.allow_metadata_inventory_move(
		pos, from_list, from_index, to_list, to_index, count, player)
	return 0
end


-- Only input- and recycle-slot are intended as input slots:
function circular_saw.allow_metadata_inventory_put(
		pos, listname, index, stack, player)
	-- The player is not allowed to put something in there:
	if listname == "output" or listname == "micro" then
		return 0
	end

	local meta = minetest.get_meta(pos)
	local inv  = meta:get_inventory()
	local stackname = stack:get_name()
	local count = stack:get_count()

	-- Only alow those items that are offered in the output inventory to be recycled:
	if listname == "recycle" then
		if not inv:contains_item("output", stackname) then
			return 0
		end
		local stackmax = stack:get_stack_max()
		local instack = inv:get_stack("input", 1)
		local microstack = inv:get_stack("micro", 1)
		local incount = instack:get_count()
		local incost = (incount * 8) + microstack:get_count()
		local maxcost = (stackmax * 8) + 7
		local cost = circular_saw:get_cost(inv, stackname)
		if not cost then 
		   return 0 
		end
		if (incost + cost) > maxcost then
			return math.max((maxcost - incost) / cost, 0)
		end
		return count
	end

	-- Only accept certain blocks as input which are known to be craftable into stairs:
	if listname == "input" then
		if not inv:is_empty("input") then
			if inv:get_stack("input", index):get_name() ~= stackname then
				return 0
			end
		end
		if not inv:is_empty("micro") then
			local microstackname = inv:get_stack("micro", 1):get_name():gsub("^.+:micro_", "", 1)
			local cutstackname = stackname:gsub("^.+:", "", 1)
			if microstackname ~= cutstackname then
				return 0
			end
		end
		for name, t in pairs(circular_saw.known_nodes) do
			if name == stackname and inv:room_for_item("input", stack) then
				return count
			end
		end
		return 0
	end
end

-- Taking is allowed from all slots (even the internal microblock slot).
-- Putting something in is slightly more complicated than taking anything
-- because we have to make sure it is of a suitable material:
function circular_saw.on_metadata_inventory_put(
		pos, listname, index, stack, player)
	-- We need to find out if the circular_saw is already set to a
	-- specific material or not:
	local meta = minetest.get_meta(pos)
	local inv  = meta:get_inventory()
	local stackname = stack:get_name()
	local count = stack:get_count()

	-- Putting something into the input slot is only possible if that had
	-- been empty before or did contain something of the same material:
	if listname == "input" then
		-- Each new block is worth 8 microblocks:
		circular_saw:update_inventory(pos, 8 * count)
	elseif listname == "recycle" then
		-- Lets look which shape this represents:
		local cost = circular_saw:get_cost(inv, stackname)
		local input_stack = inv:get_stack("input", 1)
		-- check if this would not exceed input itemstack max_stacks
		if input_stack:get_count() + ((cost * count) / 8) <= input_stack:get_stack_max() then
			circular_saw:update_inventory(pos, cost * count)
		end
	end
end

function circular_saw.allow_metadata_inventory_take(pos, listname, index, stack, player)
	local meta	= minetest.get_meta(pos)
	local inv	= meta:get_inventory()
	local input_stack = inv:get_stack(listname,  index)
	local player_inv = player:get_inventory()
	if not player_inv:room_for_item("main", input_stack) then
		return 0
	else return stack:get_count()
	end
end




function circular_saw.on_metadata_inventory_take(
		pos, listname, index, stack, player)

	-- Prevent (inbuilt) swapping between inventories with different blocks
	-- corrupting player inventory or Saw with 'unknown' items.
	local meta          = minetest.get_meta(pos)
	local inv           = meta:get_inventory()
	local input_stack = inv:get_stack(listname,  index)
	if not input_stack:is_empty() and input_stack:get_name()~=stack:get_name() then
		local player_inv = player:get_inventory()
		if player_inv:room_for_item("main", input_stack) then
			player_inv:add_item("main", input_stack)
		end

		circular_saw:reset(pos)
		return
	end

	-- If it is one of the offered stairs: find out how many
	-- microblocks have to be substracted:
	if listname == "output" then
		-- We do know how much each block at each position costs:
		local cost = circular_saw.cost_in_microblocks[index]
				* stack:get_count()

		circular_saw:update_inventory(pos, -cost)
	elseif listname == "micro" then
		-- Each microblock costs 1 microblock:
		circular_saw:update_inventory(pos, -stack:get_count())
	elseif listname == "input" then
		-- Each normal (= full) block taken costs 8 microblocks:
		circular_saw:update_inventory(pos, 8 * -stack:get_count())
	end
	-- The recycle field plays no role here since it is processed immediately.
end

function circular_saw.on_construct(pos)
	local meta = minetest.get_meta(pos)
	local fancy_inv = default.gui_bg..default.gui_bg_img..default.gui_slots
	meta:set_string("formspec", "size[11,10]"..fancy_inv..
			"label[0,0;" ..S("Input\nmaterial").. "]" ..
			"list[current_name;input;1.5,0;1,1;]" ..
			"label[0,1;" ..S("Left-over").. "]" ..
			"list[current_name;micro;1.5,1;1,1;]" ..
			"label[0,2;" ..S("Recycle\noutput").. "]" ..
			"list[current_name;recycle;1.5,2;1,1;]" ..
			"field[0.3,3.5;1,1;max_offered;" ..S("Max").. ":;${max_offered}]" ..
			"button[1,3.2;1,1;Set;" ..S("Set").. "]" ..
			"list[current_name;output;2.8,0;8,6;]" ..
			"list[current_player;main;1.5,6.25;8,4;]")

	meta:set_int("anz", 0) -- No microblocks inside yet.
	meta:set_string("max_offered", 99) -- How many items of this kind are offered by default?
	meta:set_string("infotext", S("Circular Saw is empty"))

	local inv = meta:get_inventory()
	inv:set_size("input", 1)    -- Input slot for full blocks of material x.
	inv:set_size("micro", 1)    -- Storage for 1-7 surplus microblocks.
	inv:set_size("recycle", 1)  -- Surplus partial blocks can be placed here.
	inv:set_size("output", 6*8) -- 6x8 versions of stair-parts of material x.

	circular_saw:reset(pos)
end


function circular_saw.can_dig(pos,player)
	local meta = minetest.get_meta(pos)
	local inv = meta:get_inventory()
	if not inv:is_empty("input") or
	   not inv:is_empty("micro") or
	   not inv:is_empty("recycle") then
		return false
	end
	-- Can be dug by anyone when empty, not only by the owner:
	return true
end

minetest.register_node("moreblocks:circular_saw",  {
	description = S("Circular Saw"),
	drawtype = "nodebox",
	node_box = {
		type = "fixed",
		fixed = {
			{-0.4, -0.5, -0.4, -0.25, 0.25, -0.25}, -- Leg
			{0.25, -0.5, 0.25, 0.4, 0.25, 0.4}, -- Leg
			{-0.4, -0.5, 0.25, -0.25, 0.25, 0.4}, -- Leg
			{0.25, -0.5, -0.4, 0.4, 0.25, -0.25}, -- Leg
			{-0.5, 0.25, -0.5, 0.5, 0.375, 0.5}, -- Tabletop
			{-0.01, 0.4375, -0.125, 0.01, 0.5, 0.125}, -- Saw blade (top)
			{-0.01, 0.375, -0.1875, 0.01, 0.4375, 0.1875}, -- Saw blade (bottom)
			{-0.25, -0.0625, -0.25, 0.25, 0.25, 0.25}, -- Motor case
		},
	},
	tiles = {"moreblocks_circular_saw_top.png",
		"moreblocks_circular_saw_bottom.png",
		"moreblocks_circular_saw_side.png"},
	paramtype = "light",
	sunlight_propagates = true,
	paramtype2 = "facedir",
	groups = {choppy = 2,oddly_breakable_by_hand = 2},
	sounds = default.node_sound_wood_defaults(),
	on_construct = circular_saw.on_construct,
	can_dig = circular_saw.can_dig,
	-- Set the owner of this circular saw.
	after_place_node = function(pos, placer)
		local meta = minetest.get_meta(pos)
		local owner = placer and placer:get_player_name() or ""
		meta:set_string("owner",  owner)
		meta:set_string("infotext",
				S("Circular Saw is empty (owned by %s)")
				:format(owner))
	end,

	-- The amount of items offered per shape can be configured:
	on_receive_fields = circular_saw.on_receive_fields,
	allow_metadata_inventory_move = circular_saw.allow_metadata_inventory_move,
	-- Only input- and recycle-slot are intended as input slots:
	allow_metadata_inventory_put = circular_saw.allow_metadata_inventory_put,
	allow_metadata_inventory_take = circular_saw.allow_metadata_inventory_take,
	-- Taking is allowed from all slots (even the internal microblock slot). Moving is forbidden.
	-- Putting something in is slightly more complicated than taking anything because we have to make sure it is of a suitable material:
	on_metadata_inventory_put = circular_saw.on_metadata_inventory_put,
	on_metadata_inventory_take = circular_saw.on_metadata_inventory_take,
})