aboutsummaryrefslogtreecommitdiff
path: root/advtrains_interlocking/tcb_ts_ui.lua
Commit message (Collapse)AuthorAge
* [advtrains_interlocking] lokalizace dalších textůSingularis2025-05-27
|
* [advtrains] lokalizace částí souvisejících s TCBSingularis2025-05-27
|
* [drinks,itemshelf] ochrana inventářů před novými postavamiSingularis2025-05-27
|
* [advtrains]Singularis2025-05-27
| | | | | | - odebrán mód advtrains_luaautomation - lokalizace - zastaralá funkce getpos() nahrazena za get_pos()
* Route Formspec: When cancelling route, disable ARS only temporarily, not ↵orwell962021-10-26
| | | | permanently
* Added alternative recipes, falling back on the default: items as they seem ↵Maverick27972021-03-06
| | | | | | to be in the rest of the mod. May need rebalancing though.
* Add some missing craft recipesorwell962021-02-19
| | | | | | | - LuaATC remains non-craftable for now (elevated privs necessary anyway) - Some crafts altered from dario's proposal Co-authored-by: W3RQ01 <dario23@linux-forks.de>
* Fix new green signals bug caused by old trav_lzbdata, and callback loop in ↵orwell962021-02-10
| | | | signalling formspec
* Forbid track modification when train, IP or TCB is on it, better handle ↵orwell962020-10-07
| | | | removing of TCBs (H#149)
* tcb: Fix crash when player is nilLinus Jahn2020-09-01
|
* Apply minetest.formspec_escape() to prevent formspec injection (H#143)MT0.4Blockhead2020-01-04
|
* Don't allow to remove TCB when a signal is assignedorwell962019-08-26
|
* Disable-ARS switch in signal and set this when cancelling an ARS routeorwell962019-03-15
|
* Fix cancelling "Unknown Route" when section is deleted.orwell962019-03-15
|
* Signalling form auto-updateorwell962019-02-05
|
* Prohibit removing/changing of TCBs and sections while routes or signals are setorwell962019-01-22
|
* Can disable automatic working without cancelling routeorwell962019-01-15
|
* Add Automatic Routesetting UIorwell962019-01-09
| | | | Settings have no effect so far
* Permit basic signal aspect settingorwell962018-11-19
| | | | (basically only usable with Ks signals, because they're the only signals supporting slow move and/or shunt move
* Do not allow static signals for routesettingorwell962018-10-30
|
* Fix typo in signal assignment, causing crashorwell962018-10-29
|
* Miscellaneous routesetting fixesorwell962018-10-29
| | | | | | | - Move handling of "route_committed" to the routesetting function - Put aspect in every TCBS on the way - Add "route_origin" to TCBS fields to prevent subroute cancelling - Cancel entire route when another train enters from the wrong TCB
* Add Interlocking Tool to inspect route locksorwell962018-10-26
|
* Add "Reset track section" functionorwell962018-10-26
|
* Make signal influence point (~halt point) specifiableorwell962018-10-09
| | | | Also extend signal api necessarily
* Fix various bugs found while testingorwell962018-08-13
|
* Add 'interlocking' privilege and add security checksorwell962018-08-12
|
* Automatic working (re-set certain route on train pass)orwell962018-08-12
|
* fix digging unconfigured tcbsorwell962018-08-12
|
* Signal aspect handling, make default signals compatible, fix signal diggingorwell962018-08-12
|
* Add routesetting callbacks.orwell962018-08-12
| | | | Now, only the signal aspect setting is still missing
* Uncommitted route handling (update_route function)orwell962018-08-03
|
* Implement routesettingorwell962018-07-21
| | | | Missing things: signal aspect updating, waiting routes handling, management /info tool
* Basic route management from signalling formspecorwell962018-07-04
|
* Signal assignment and route programming procedureorwell962018-07-04
|
* Implement trains blocking sectionsorwell962018-06-29
|
* Complete Track Section handling, incl. removing tcb's and marker entitiesorwell962018-06-26
|
* Add track section concept and rework TCB design, implement new linking behaviororwell962018-06-21
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2013 Kahrl <kahrl@gmx.net>

This program 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 program 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 program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include <fstream>
#include <iterator>
#include "shader.h"
#include "irrlichttypes_extrabloated.h"
#include "irr_ptr.h"
#include "debug.h"
#include "filesys.h"
#include "util/container.h"
#include "util/thread.h"
#include "settings.h"
#include <ICameraSceneNode.h>
#include <IGPUProgrammingServices.h>
#include <IMaterialRenderer.h>
#include <IMaterialRendererServices.h>
#include <IShaderConstantSetCallBack.h>
#include "client/renderingengine.h"
#include "EShaderTypes.h"
#include "log.h"
#include "gamedef.h"
#include "client/tile.h"
#include "config.h"

#if ENABLE_GLES
#ifdef _IRR_COMPILE_WITH_OGLES1_
#include <GLES/gl.h>
#else
#include <GLES2/gl2.h>
#endif
#else
#ifndef __APPLE__
#include <GL/gl.h>
#else
#define GL_SILENCE_DEPRECATION
#include <OpenGL/gl.h>
#endif
#endif

/*
	A cache from shader name to shader path
*/
MutexedMap<std::string, std::string> g_shadername_to_path_cache;

/*
	Gets the path to a shader by first checking if the file
	  name_of_shader/filename
	exists in shader_path and if not, using the data path.

	If not found, returns "".

	Utilizes a thread-safe cache.
*/
std::string getShaderPath(const std::string &name_of_shader,
		const std::string &filename)
{
	std::string combined = name_of_shader + DIR_DELIM + filename;
	std::string fullpath;
	/*
		Check from cache
	*/
	bool incache = g_shadername_to_path_cache.get(combined, &fullpath);
	if(incache)
		return fullpath;

	/*
		Check from shader_path
	*/
	std::string shader_path = g_settings->get("shader_path");
	if (!shader_path.empty()) {
		std::string testpath = shader_path + DIR_DELIM + combined;
		if(fs::PathExists(testpath))
			fullpath = testpath;
	}

	/*
		Check from default data directory
	*/
	if (fullpath.empty()) {
		std::string rel_path = std::string("client") + DIR_DELIM
				+ "shaders" + DIR_DELIM
				+ name_of_shader + DIR_DELIM
				+ filename;
		std::string testpath = porting::path_share + DIR_DELIM + rel_path;
		if(fs::PathExists(testpath))
			fullpath = testpath;
	}

	// Add to cache (also an empty result is cached)
	g_shadername_to_path_cache.set(combined, fullpath);

	// Finally return it
	return fullpath;
}

/*
	SourceShaderCache: A cache used for storing source shaders.
*/

class SourceShaderCache
{
public:
	void insert(const std::string &name_of_shader, const std::string &filename,
		const std::string &program, bool prefer_local)
	{
		std::string combined = name_of_shader + DIR_DELIM + filename;
		// Try to use local shader instead if asked to
		if(prefer_local){
			std::string path = getShaderPath(name_of_shader, filename);
			if(!path.empty()){
				std::string p = readFile(path);
				if (!p.empty()) {
					m_programs[combined] = p;
					return;
				}
			}
		}
		m_programs[combined] = program;
	}

	std::string get(const std::string &name_of_shader,
		const std::string &filename)
	{
		std::string combined = name_of_shader + DIR_DELIM + filename;
		StringMap::iterator n = m_programs.find(combined);
		if (n != m_programs.end())
			return n->second;
		return "";
	}

	// Primarily fetches from cache, secondarily tries to read from filesystem
	std::string getOrLoad(const std::string &name_of_shader,
		const std::string &filename)
	{
		std::string combined = name_of_shader + DIR_DELIM + filename;
		StringMap::iterator n = m_programs.find(combined);
		if (n != m_programs.end())
			return n->second;
		std::string path = getShaderPath(name_of_shader, filename);
		if (path.empty()) {
			infostream << "SourceShaderCache::getOrLoad(): No path found for \""
				<< combined << "\"" << std::endl;
			return "";
		}
		infostream << "SourceShaderCache::getOrLoad(): Loading path \""
			<< path << "\"" << std::endl;
		std::string p = readFile(path);
		if (!p.empty()) {
			m_programs[combined] = p;
			return p;
		}
		return "";
	}
private:
	StringMap m_programs;

	std::string readFile(const std::string &path)
	{
		std::ifstream is(path.c_str(), std::ios::binary);
		if(!is.is_open())
			return "";
		std::ostringstream tmp_os;
		tmp_os << is.rdbuf();
		return tmp_os.str();
	}
};


/*
	ShaderCallback: Sets constants that can be used in shaders
*/

class ShaderCallback : public video::IShaderConstantSetCallBack
{
	std::vector<std::unique_ptr<IShaderConstantSetter>> m_setters;

public:
	template <typename Factories>
	ShaderCallback(const Factories &factories)
	{
		for (auto &&factory : factories)
			m_setters.push_back(std::unique_ptr<IShaderConstantSetter>(factory->create()));
	}

	virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData) override
	{
		video::IVideoDriver *driver = services->getVideoDriver();
		sanity_check(driver != NULL);

		for (auto &&setter : m_setters)
			setter->onSetConstants(services);
	}

	virtual void OnSetMaterial(const video::SMaterial& material) override
	{
		for (auto &&setter : m_setters)
			setter->onSetMaterial(material);
	}
};


/*
	MainShaderConstantSetter: Set basic constants required for almost everything
*/

class MainShaderConstantSetter : public IShaderConstantSetter
{
	CachedVertexShaderSetting<float, 16> m_world_view_proj;
	CachedVertexShaderSetting<float, 16> m_world;

	// Shadow-related
	CachedPixelShaderSetting<float, 16> m_shadow_view_proj;
	CachedPixelShaderSetting<float, 3> m_light_direction;
	CachedPixelShaderSetting<float> m_texture_res;
	CachedPixelShaderSetting<float> m_shadow_strength;
	CachedPixelShaderSetting<float> m_time_of_day;
	CachedPixelShaderSetting<float> m_shadowfar;
	CachedPixelShaderSetting<s32> m_shadow_texture;

#if ENABLE_GLES
	// Modelview matrix
	CachedVertexShaderSetting<float, 16> m_world_view;
	// Texture matrix
	CachedVertexShaderSetting<float, 16> m_texture;
	// Normal matrix
	CachedVertexShaderSetting<float, 9> m_normal;
#endif

public:
	MainShaderConstantSetter() :
		  m_world_view_proj("mWorldViewProj")
		, m_world("mWorld")
#if ENABLE_GLES
		, m_world_view("mWorldView")
		, m_texture("mTexture")
		, m_normal("mNormal")
#endif
		, m_shadow_view_proj("m_ShadowViewProj")
		, m_light_direction("v_LightDirection")
		, m_texture_res("f_textureresolution")
		, m_shadow_strength("f_shadow_strength")
		, m_time_of_day("f_timeofday")
		, m_shadowfar("f_shadowfar")
		, m_shadow_texture("ShadowMapSampler")
	{}
	~MainShaderConstantSetter() = default;

	virtual void onSetConstants(video::IMaterialRendererServices *services) override
	{
		video::IVideoDriver *driver = services->getVideoDriver();
		sanity_check(driver);

		// Set world matrix
		core::matrix4 world = driver->getTransform(video::ETS_WORLD);
		m_world.set(*reinterpret_cast<float(*)[16]>(world.pointer()), services);

		// Set clip matrix
		core::matrix4 worldView;
		worldView = driver->getTransform(video::ETS_VIEW);
		worldView *= world;

		core::matrix4 worldViewProj;
		worldViewProj = driver->getTransform(video::ETS_PROJECTION);
		worldViewProj *= worldView;
		m_world_view_proj.set(*reinterpret_cast<float(*)[16]>(worldViewProj.pointer()), services);

#if ENABLE_GLES
		core::matrix4 texture = driver->getTransform(video::ETS_TEXTURE_0);
		m_world_view.set(*reinterpret_cast<float(*)[16]>(worldView.pointer()), services);
		m_texture.set(*reinterpret_cast<float(*)[16]>(texture.pointer()), services);

		core::matrix4 normal;
		worldView.getTransposed(normal);
		sanity_check(normal.makeInverse());
		float m[9] = {
			normal[0], normal[1], normal[2],
			normal[4], normal[5], normal[6],
			normal[8], normal[9], normal[10],
		};
		m_normal.set(m, services);
#endif

		// Set uniforms for Shadow shader
		if (ShadowRenderer *shadow = RenderingEngine::get_shadow_renderer()) {
			const auto &light = shadow->getDirectionalLight();

			core::matrix4 shadowViewProj = light.getProjectionMatrix();
			shadowViewProj *= light.getViewMatrix();
			m_shadow_view_proj.set(shadowViewProj.pointer(), services);

			float v_LightDirection[3];
			light.getDirection().getAs3Values(v_LightDirection);
			m_light_direction.set(v_LightDirection, services);

			float TextureResolution = light.getMapResolution();
			m_texture_res.set(&TextureResolution, services);

			float ShadowStrength = shadow->getShadowStrength();
			m_shadow_strength.set(&ShadowStrength, services);

			float timeOfDay = shadow->getTimeOfDay();
			m_time_of_day.set(&timeOfDay, services);

			float shadowFar = shadow->getMaxShadowFar();
			m_shadowfar.set(&shadowFar, services);

			// I dont like using this hardcoded value. maybe something like
			// MAX_TEXTURE - 1 or somthing like that??
			s32 TextureLayerID = 3;
			m_shadow_texture.set(&TextureLayerID, services);
		}
	}
};


class MainShaderConstantSetterFactory : public IShaderConstantSetterFactory
{
public:
	virtual IShaderConstantSetter* create()
		{ return new MainShaderConstantSetter(); }
};


/*
	ShaderSource
*/

class ShaderSource : public IWritableShaderSource
{
public:
	ShaderSource();

	/*
		- If shader material specified by name is found from cache,
		  return the cached id.
		- Otherwise generate the shader material, add to cache and return id.

		The id 0 points to a null shader. Its material is EMT_SOLID.
	*/
	u32 getShaderIdDirect(const std::string &name,
		MaterialType material_type, NodeDrawType drawtype) override;

	/*
		If shader specified by the name pointed by the id doesn't
		exist, create it, then return id.

		Can be called from any thread. If called from some other thread
		and not found in cache, the call is queued to the main thread
		for processing.
	*/

	u32 getShader(const std::string &name,
		MaterialType material_type, NodeDrawType drawtype) override;

	ShaderInfo getShaderInfo(u32 id) override;

	// Processes queued shader requests from other threads.
	// Shall be called from the main thread.
	void processQueue() override;

	// Insert a shader program into the cache without touching the
	// filesystem. Shall be called from the main thread.
	void insertSourceShader(const std::string &name_of_shader,
		const std::string &filename, const std::string &program) override;

	// Rebuild shaders from the current set of source shaders
	// Shall be called from the main thread.
	void rebuildShaders() override;

	void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) override
	{
		m_setter_factories.push_back(std::unique_ptr<IShaderConstantSetterFactory>(setter));
	}

private:

	// The id of the thread that is allowed to use irrlicht directly
	std::thread::id m_main_thread;

	// Cache of source shaders
	// This should be only accessed from the main thread
	SourceShaderCache m_sourcecache;

	// A shader id is index in this array.
	// The first position contains a dummy shader.
	std::vector<ShaderInfo> m_shaderinfo_cache;
	// The former container is behind this mutex
	std::mutex m_shaderinfo_cache_mutex;

	// Queued shader fetches (to be processed by the main thread)
	RequestQueue<std::string, u32, u8, u8> m_get_shader_queue;

	// Global constant setter factories
	std::vector<std::unique_ptr<IShaderConstantSetterFactory>> m_setter_factories;

	// Generate shader given the shader name.
	ShaderInfo generateShader(const std::string &name,
			MaterialType material_type, NodeDrawType drawtype);
};