├── docs ├── index.md ├── requirements.txt ├── logo.png ├── loaded_example.png ├── stylesheets │ └── extra.css ├── examples │ ├── java-jython-integration │ │ ├── interfaces │ │ │ ├── Human.java │ │ │ ├── Alien.java │ │ │ ├── Main.java │ │ │ └── SimpleFactory.java │ │ ├── README.md │ │ └── Creatures.py │ └── chapter-10 │ │ └── org │ │ └── jythonbook │ │ ├── Main.java │ │ └── JythonObjectFactory.java ├── README.md ├── painpoints.md ├── contributions.md ├── internals.md └── jamboard.md ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── resources │ └── META-INF │ │ ├── services │ │ └── net.minecraftforge.forgespi.language.IModLanguageProvider │ │ └── MANIFEST.MF │ └── java │ ├── rickaym │ └── pyforge │ │ ├── PyModLoadingContext.java │ │ ├── events │ │ ├── PySubscribeEvent.java │ │ └── PyEventBusWrapper.java │ │ ├── WrappedModInstance.java │ │ ├── Mod.java │ │ ├── PyLanguageProvider.java │ │ ├── PyModContainer.java │ │ └── PyModLoader.java │ └── test │ └── Main.java ├── gradle.properties ├── .readthedocs.yaml ├── .gitignore ├── changelog.txt ├── mkdocs.yml ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /docs/index.md: -------------------------------------------------------------------------------- 1 | --8<-- "README.md" -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | mkdocs-material 2 | pymdown-extensions -------------------------------------------------------------------------------- /docs/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rickaym/pyforge/HEAD/docs/logo.png -------------------------------------------------------------------------------- /docs/loaded_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rickaym/pyforge/HEAD/docs/loaded_example.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rickaym/pyforge/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/net.minecraftforge.forgespi.language.IModLanguageProvider: -------------------------------------------------------------------------------- 1 | rickaym.pyforge.PyLanguageProvider -------------------------------------------------------------------------------- /src/main/resources/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | FMLModType: LANGPROVIDER 3 | Automatic-Module-Name: pyforge 4 | -------------------------------------------------------------------------------- /docs/stylesheets/extra.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --md-primary-fg-color: #4f0000; 3 | --md-primary-fg-color--light: #9b0000; 4 | --md-primary-fg-color--dark: #4e0000; 5 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Sets default memory used for gradle commands. Can be overridden by user or command line properties. 2 | # This is required to provide enough memory for the Minecraft decompilation process. 3 | org.gradle.jvmargs=-Xmx3G 4 | org.gradle.daemon=false -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | mkdocs: 4 | configuration: mkdocs.yml 5 | 6 | formats: 7 | - pdf 8 | 9 | build: 10 | os: ubuntu-22.04 11 | tools: 12 | python: "3.9" 13 | 14 | python: 15 | install: 16 | - requirements: docs/requirements.txt -------------------------------------------------------------------------------- /docs/examples/java-jython-integration/interfaces/Human.java: -------------------------------------------------------------------------------- 1 | package interfaces; 2 | 3 | public interface Human{ 4 | /** 5 | * Shadows the incoming Alien Python class. 6 | */ 7 | String getHumanName(); 8 | int getHumanAge(); 9 | String getHumanSex(); 10 | } 11 | -------------------------------------------------------------------------------- /docs/examples/java-jython-integration/interfaces/Alien.java: -------------------------------------------------------------------------------- 1 | package interfaces; 2 | 3 | public interface Alien{ 4 | /** 5 | * Shadows the incoming Alien Python class. 6 | */ 7 | String getAlienName(); 8 | int getAlienAge(); 9 | String getAlienRace(); 10 | } 11 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Information 2 | 3 | - [**Courseboard**](https://github.com/Rickaym/minecraft.py/tree/main/.info/courseboard) - a definitive guide to understand the project 4 | 5 | - [**examples**](https://github.com/Rickaym/minecraft.py/tree/main/.info/examples) - most of the files and folders there are directly referenced in the Courseboard as needed 6 | 7 | _Navigate in directional order top to bottom_ 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # todo 2 | *.todo 3 | 4 | # IDE stuff 5 | *.iml 6 | *.ipr 7 | *.iws 8 | .idea 9 | out 10 | bin 11 | 12 | .settings 13 | .metadata 14 | .classpath 15 | .project 16 | 17 | .vscode 18 | 19 | # Python Cache 20 | *.jython_cache 21 | __pycache__ 22 | 23 | # Gense 24 | *.pdf 25 | 26 | # sphinx 27 | build 28 | run 29 | _build 30 | _static 31 | _templates 32 | make.bat 33 | Makefile 34 | 35 | # bytecode 36 | *.class 37 | *$py.class 38 | 39 | .gradle/ 40 | /src/examplemod/ 41 | site/ -------------------------------------------------------------------------------- /docs/painpoints.md: -------------------------------------------------------------------------------- 1 | # Painpoints 2 | 3 | Here are some of the biggest difficulties when considering usability: 4 | 5 | 1. Stacktrace is almost impenetrable with too many lines from jython internals 6 | 2. Hard to pinpoint runtime errors to the Python code as exceptions are raised inside Jython internally 7 | 3. Documentation is not visible unless packages are imported a certain way import (...) as (...) 8 | 4. From the perspective of a Python developer, there are simply way too many Java concepts and prerequisite knowledge to call this anything deeply related to Python 9 | -------------------------------------------------------------------------------- /src/main/java/rickaym/pyforge/PyModLoadingContext.java: -------------------------------------------------------------------------------- 1 | package rickaym.pyforge; 2 | 3 | import net.minecraftforge.eventbus.api.IEventBus; 4 | import net.minecraftforge.fml.ModLoadingContext; 5 | 6 | public class PyModLoadingContext { 7 | private final PyModContainer container; 8 | 9 | public PyModLoadingContext(PyModContainer container) { 10 | this.container = container; 11 | } 12 | 13 | public IEventBus getModEventBus() { 14 | return container.eventBus; 15 | } 16 | 17 | public static PyModLoadingContext get() { 18 | return ModLoadingContext.get().extension(); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/rickaym/pyforge/events/PySubscribeEvent.java: -------------------------------------------------------------------------------- 1 | package rickaym.pyforge.events; 2 | 3 | import org.python.core.*; 4 | 5 | public class PySubscribeEvent extends PyObject { 6 | @Override 7 | public PyObject __call__(PyObject[] args, String[] keywords) { 8 | if (!(args[0] instanceof PyFunction)) { 9 | throw Py.TypeError("Expected function type, got " + args[0].getType() 10 | .fastGetName()); 11 | } 12 | PyFunction function = (PyFunction) args[0]; 13 | function.__setattr__("__event_subscriber__", Py.True); 14 | return function; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /docs/examples/java-jython-integration/interfaces/Main.java: -------------------------------------------------------------------------------- 1 | package interfaces; 2 | 3 | public class Main { 4 | /** 5 | * Usage of the object factory design pattern by making calls to the 6 | * createXYZ methods. 7 | * 8 | * @see `Alien`, `Human` and `SimpleFactory` 9 | */ 10 | public static void main(String[] args) { 11 | SimpleFactory factory = new SimpleFactory(); 12 | 13 | Human ricky = factory.createMale("Ricky", 12); 14 | SimpleFactory.interpretHuman(ricky); 15 | 16 | System.out.println("\n"); 17 | 18 | Alien jorgan = factory.createLizzie("Jorgan", 102, "lizzies"); 19 | SimpleFactory.interpretAlien((jorgan)); 20 | } 21 | } -------------------------------------------------------------------------------- /changelog.txt: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [0.0.2] - 2023-07-19 9 | 10 | ### Added 11 | 12 | - Decorator to transfer mod metadata to pyforge 13 | - Language provider to interacts with the FML system 14 | - Mod loader to load mods from the mods folder 15 | - Mod container to provide arms length access to FML 16 | - Wrapped mod container to provide a java interface to mod instances 17 | 18 | ## [0.0.1] - 2021-07-01 19 | 20 | ### Added 21 | 22 | - Preliminary project setup 23 | - Jython Class Loader 24 | -------------------------------------------------------------------------------- /docs/examples/chapter-10/org/jythonbook/Main.java: -------------------------------------------------------------------------------- 1 | package org.jythonbook; 2 | 3 | public class Main { 4 | 5 | public static void main(String args[]) { 6 | // what other control options should we provide to the factory? 7 | // jsr223 might have some good ideas, but also let's keep some simple code usage 8 | // for now, let's just try out and refine 9 | JythonObjectFactory factory = new JythonObjectFactory( 10 | BuildingType.class, "building", "Building"); 11 | 12 | BuildingType building = (BuildingType) factory.createObject(); 13 | 14 | building.setBuildingName("BUIDING-A"); 15 | building.setBuildingAddress("100 MAIN ST."); 16 | building.setBuildingId(1); 17 | 18 | System.out.println(building.getBuildingId() + " " + building.getBuildingName() + " " + 19 | building.getBuildingAddress()); 20 | } 21 | } -------------------------------------------------------------------------------- /docs/examples/java-jython-integration/README.md: -------------------------------------------------------------------------------- 1 | # `java-jython-integration` with a working example 2 | 3 | # Integration 4 | 5 | Let's walk through the process of Java to Jython integration. 6 | 7 | ## Design Pattern 8 | 9 | > Perhaps the most widely used technique used today for incorporating Jython code within Java applications is the object factory design pattern. This idea basically enables seamless integration between Java and Jython via the use of object factories. There are various different implementations of the logic, but all of them do have the same result in the end. Implementations of the object factory paradigm allow one to include Jython modules within Java applications without the use of an extra compilation step. Moreover, this technique allows for a clean integration of Jython and Java code through usage of Java interfaces [...continues here..](https://jython.readthedocs.io/en/latest/JythonAndJavaIntegration/?highlight=generics#object-factories) 10 | 11 | You will see an implementation of this design pattern as above. The code will be self documenting. -------------------------------------------------------------------------------- /src/main/java/rickaym/pyforge/WrappedModInstance.java: -------------------------------------------------------------------------------- 1 | package rickaym.pyforge; 2 | 3 | import org.python.core.PyInstance; 4 | import org.python.core.PyTuple; 5 | 6 | import java.util.Map; 7 | 8 | /** 9 | * Wraps a Python mod instance with a Java interface. 10 | */ 11 | public class WrappedModInstance { 12 | private final PyInstance modInstance; 13 | WrappedModInstance(PyInstance instance) { 14 | modInstance = instance; 15 | } 16 | 17 | /** 18 | * Invokes the mod's inner register function. 19 | */ 20 | public void register() { 21 | modInstance.invoke("register"); 22 | } 23 | 24 | /** 25 | * Gets the mod's metadata set through the decorator. 26 | */ 27 | public Map getModMeta() { 28 | PyTuple ret = (PyTuple) modInstance.invoke("__mod_meta__"); 29 | Map modMeta = new java.util.HashMap<>(); 30 | for (int i = 0; i < ret.__len__(); i++) { 31 | PyTuple tuple = (PyTuple) ret.__getitem__(i); 32 | modMeta.put(tuple.__getitem__(0).toString(), tuple.__getitem__(1).toString()); 33 | } 34 | return modMeta; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: PyForge 2 | site_description: "The Python Language Provider for Minecraft Forge" 3 | site_url: "https://pyforge-mc.readthedocs.io/" 4 | repo_url: "https://github.com/rickaym/pyforge" 5 | watch: ["README.md"] 6 | repo_name: "rickaym/pyforge" 7 | site_dir: "site" 8 | copyright: Copyright © 2024 Pyae Sone Myo 9 | nav: 10 | - Home: index.md 11 | - Contributions: contributions.md 12 | - Internals: internals.md 13 | - Painpoints: painpoints.md 14 | - Jamboard: jamboard.md 15 | 16 | theme: 17 | name: material 18 | palette: 19 | primary: custom 20 | features: 21 | - navigation.footer 22 | 23 | extra: 24 | social: 25 | - icon: fontawesome/brands/discord 26 | link: https://discord.gg/UmnzdPgn6g 27 | - icon: fontawesome/brands/github 28 | link: https://github.com/rickaym/pyforge 29 | 30 | markdown_extensions: 31 | - pymdownx.highlight: 32 | anchor_linenums: true 33 | line_spans: __span 34 | pygments_lang_class: true 35 | - pymdownx.inlinehilite 36 | - pymdownx.superfences 37 | - pymdownx.snippets: 38 | check_paths: true 39 | - admonition 40 | - pymdownx.details 41 | 42 | extra_css: 43 | - stylesheets/extra.css 44 | -------------------------------------------------------------------------------- /src/main/java/rickaym/pyforge/Mod.java: -------------------------------------------------------------------------------- 1 | package rickaym.pyforge; 2 | 3 | import org.python.core.*; 4 | 5 | /** 6 | * `@Mod` decorator to mark a Python class as a mod. 7 | */ 8 | public class Mod extends PyObject { 9 | public static String mod_id; 10 | 11 | @Override 12 | public PyObject __call__(PyObject[] args, String[] keywords) { 13 | PyObject mod_class = args[0]; 14 | { 15 | if (!(mod_class instanceof PyClass)) { 16 | throw Py.TypeError("Expected class type, got " + mod_class.getType() 17 | .fastGetName()); 18 | } 19 | class ModMetaFunction extends PyObject { 20 | @Override 21 | public PyObject __call__() { 22 | return new PyTuple( 23 | new PyTuple(new PyString("mod_id"), new PyString(mod_id)), 24 | new PyTuple(new PyString("class_name"), new PyString(mod_class.getType() 25 | .fastGetName())) 26 | ); 27 | } 28 | } 29 | mod_class.__setattr__("__mod_meta__", new ModMetaFunction()); 30 | return mod_class; 31 | } 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /docs/contributions.md: -------------------------------------------------------------------------------- 1 | # Contributions 2 | 3 | You will be working with Minecraft Forge so it is necessary that you 4 | understand the basic aspects of Minecraft Forge if not complex mod 5 | loading mechanisms. Understanding the basic concepts of mod making will 6 | also be very useful in learning low level concepts within Forge. Check out their documentation. 7 | 8 | ## Requirements 9 | 10 | The codebase is developed in `Java`. Most other language providers write in their respective languages, but 11 | pyforge is not written in Python. Python to Java porting demands 12 | boilerplate code and it is unnecessary in the perspective of the 13 | library. The class loader is written in Java along with everything else; 14 | so we implement things in Jython only when it is in necessity. Generally 15 | writing things in Java helps the process of interpolating with the core 16 | Forge mod loading systems as they too are written in Java. 17 | 18 | In any case, we will be juggling with the concepts in all three languages: 19 | 20 | 1. Java 21 | 2. Python 22 | 3. Jython 23 | 24 | ## Setup 25 | 26 | In summary; 27 | 28 | 1. Install a JDK 29 | 2. Obtain an MDK from [Forge](https://files.minecraftforge.net/) 30 | 3. Extract the MDK to an folder and pick out necessary files for mod 31 | development, namely; `build.gradle`, `gradlew.bat`, `gradlew` and 32 | the `gradle` folder. 33 | 4. Move files listed above to a new folder. (this will be your mod 34 | projects folder) 35 | 5. Choose an IDE and load as Gradle project 36 | 6. Generating IDE Launch/Run Configurations with ForgeGradle 37 | 38 | See [here](https://mcforge.readthedocs.io/en/latest/gettingstarted/) for 39 | more information. 40 | -------------------------------------------------------------------------------- /src/main/java/test/Main.java: -------------------------------------------------------------------------------- 1 | package test; 2 | 3 | import org.python.core.Py; 4 | import org.python.core.PyObject; 5 | import org.python.core.PySystemState; 6 | import org.python.util.PythonInterpreter; 7 | import rickaym.pyforge.PyModLoader; 8 | 9 | import java.nio.file.Paths; 10 | 11 | 12 | public class Main { 13 | public static void main(String[] args) { 14 | String moduleName = "examplemod"; 15 | String sourceDir = Paths.get("src") 16 | .toAbsolutePath() 17 | .normalize() 18 | .toString(); 19 | PyModLoader.loadMod(sourceDir, moduleName); 20 | } 21 | private static void testLoadInterpreter(String sourceDir, String moduleName) { 22 | PythonInterpreter jyInterpreter = new PythonInterpreter(); 23 | jyInterpreter.exec("import sys"); 24 | jyInterpreter.exec(String.format("sys.path.append(\"%s\")", sourceDir)); // replace with actual path 25 | jyInterpreter.exec(String.format("import %s", moduleName)); // replace with actual module name 26 | PyObject module = jyInterpreter.get(moduleName); 27 | System.out.format("Interpreter loaded in module '%s'.\n", module); 28 | } 29 | 30 | private static void testLoadSysState(String sourceDir, String moduleName) { 31 | PySystemState sys = new PySystemState(); 32 | sys.path.append(Py.newString(sourceDir)); 33 | PyObject importer = sys.getBuiltins() 34 | .__getitem__(Py.newString("__import__")); 35 | System.out.format("%s importer calling the top level module '%s'.\n", importer, moduleName); 36 | PyObject module = importer.__call__(Py.newString(moduleName)); 37 | System.out.format("System state loaded in module '%s'.\n", module); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /docs/examples/java-jython-integration/interfaces/SimpleFactory.java: -------------------------------------------------------------------------------- 1 | package interfaces; 2 | 3 | import org.python.core.PyInteger; 4 | import org.python.core.PyObject; 5 | import org.python.core.PyString; 6 | import org.python.util.PythonInterpreter; 7 | 8 | public class SimpleFactory { 9 | private final PyObject maleClass; 10 | private final PyObject lizziesClass; 11 | 12 | /** 13 | * HumanFactory constructor (similar to cls.__init__ method in Python) 14 | */ 15 | SimpleFactory() { 16 | 17 | PythonInterpreter interpreter = new PythonInterpreter(); 18 | interpreter.exec("from Creatures import Male, Lizzies"); 19 | 20 | maleClass = interpreter.get("Male"); 21 | lizziesClass = interpreter.get("Lizzies"); 22 | } 23 | 24 | public Human createMale(String name, int age) { 25 | // Calls the dunder method __call__ with the arguments needed to 26 | // instantiate a PyObject or an instance of the Python class. 27 | PyObject maleObject = maleClass.__call__(new PyString(name), new PyInteger(age)); 28 | 29 | //Casts its return value of __tojava__ to the shadow interface 30 | // Read more about __tojava__ here -> () 31 | return (Human) maleObject.__tojava__(Human.class); 32 | } 33 | public Alien createLizzie(String name, int age, String race) { 34 | PyObject lizzieObject = lizziesClass.__call__(new PyString(name), new PyInteger(age), new PyString(race)); 35 | return (Alien) lizzieObject.__tojava__(Alien.class); 36 | } 37 | 38 | public static void interpretHuman(Human person) { 39 | System.out.format("NAME: %s\nAGE: %o\nSEX: %s", person.getHumanName(), person.getHumanAge(), person.getHumanSex()); 40 | } 41 | public static void interpretAlien(Alien species) { 42 | System.out.format("NAME: %s\nAGE: %o\nRACE: %s", species.getAlienName(), species.getAlienAge(), species.getAlienRace()); 43 | } 44 | } -------------------------------------------------------------------------------- /docs/internals.md: -------------------------------------------------------------------------------- 1 | # Internals Primer 2 | 3 | Let's first understand how the modding process works in perspective to the interactions between Forge, third party mods and pyforge. 4 | 5 | ## Intermediary 6 | PyForge is a mod loader, which means that it acts as an intermediary between the target mod (Jython) and Minecraft Forge (Java). Our target mod is able to make calls on the Forge library purely by language capabilities. The majority of the work PyForge does is to discover and load the mod into Forge. PyForge is different to other mod loaders like for those of Scala and Kotlin (it is recommended to check them out) in that the Jython classes can be loaded directly into Java, our effort is to wrap around the mod to play well with Forge. 7 | 8 | ## \_\_init\_\_.py 9 | 10 | We scan for packages that contain the `__init__.py` file as potential mod candidates. The target mod is expected to expose their mod instance in this file. We do not have any concern to access other objects in the mod. 11 | 12 | Earlier, we saw this example of the init file. 13 | 14 | ```python 15 | ... 16 | get_mod_instance = lambda: MyMod() 17 | ... 18 | ``` 19 | 20 | When we have the path to the mod's init file, we try to find the factory function `get_mod_instance` that readily returns a new mod instance. 21 | 22 | This method is preferred over constructing the mod class ourselves in the Jython interpreter because: 23 | 1. Simplifies the whole mod loading process to finding a single factory function in a conventional init file 24 | 2. Easier to understand and regulate how the mod instance is constructed for the developer 25 | 26 | ## @Mod Class Decorator 27 | 28 | The @Mod class decorator is implemented in Java inside pyforge. It is an "annotation" on the mod class that assigns metadata to the mod class. It does this by setting an attribute `cls.__mod_meta__` to a supplier function that returns a tuple of `(mod_id, class_name)`. Since the decorator is applied to the class, all its instances have a reference to the supplier function. 29 | -------------------------------------------------------------------------------- /docs/examples/java-jython-integration/Creatures.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from interfaces import Human, Alien # type: ignore 3 | 4 | """ 5 | Exemplifies the class structure for Python classes that are needed to be integrated into java. 6 | 7 | `Human` is a Java interface under which is defined after finalizing Male class details. 8 | 9 | In order for the integration to be compatible Python classes must be subclassed under the 10 | desired interfaces, in this case the `Human` interface. 11 | 12 | You will see docstrings that looks like => 13 | @sig () 14 | They are provided for means of comparison to its methods found in the 15 | Java interface. 16 | 17 | Always keep in mind to use 2.x syntax. 18 | """ 19 | 20 | 21 | class Male(Human): 22 | """ 23 | Male sex class that implements `HUMAN` interface 24 | """ 25 | 26 | def __init__(self, name, age): 27 | """@sig default Male (String name, int age) {...}""" 28 | self.name = name 29 | self.age = age 30 | 31 | def getHumanName(self): 32 | """@sig String getHumanName ();""" 33 | return self.name 34 | 35 | def getHumanAge(self): 36 | """@sig int getHumanAge ();""" 37 | return self.age 38 | 39 | def getHumanSex(self): 40 | """@sig String getHumanSex ();""" 41 | return "male" 42 | 43 | 44 | class Lizzies(Alien): 45 | """ 46 | Lizzie subclass of the `Alien` interface as an example 47 | """ 48 | 49 | def __init__(self, name, age, race): 50 | """@sig default Female (String name, int age) {...}""" 51 | self.name = name 52 | self.age = age 53 | self.race = race 54 | 55 | def getAlienName(self): 56 | """@sig String getAlienName();""" 57 | return self.name 58 | 59 | def getAlienAge(self): 60 | """@sig int getAlienAge();""" 61 | return self.age 62 | 63 | def getAlienRace(self): 64 | """@sig String getAlienRace();""" 65 | return "Lizzie" -------------------------------------------------------------------------------- /docs/examples/chapter-10/org/jythonbook/JythonObjectFactory.java: -------------------------------------------------------------------------------- 1 | package org.jythonbook; 2 | 3 | import org.python.core.Py; 4 | 5 | import org.python.core.PyObject; 6 | import org.python.core.PySystemState; 7 | 8 | public class JythonObjectFactory { 9 | 10 | private final Class interfaceType; 11 | private final PyObject klass; 12 | 13 | // likely want to reuse PySystemState in some clever fashion since expensive to setup... 14 | public JythonObjectFactory(PySystemState state, Class interfaceType, String moduleName, String className) { 15 | this.interfaceType = interfaceType; 16 | PyObject importer = state.getBuiltins().__getitem__(Py.newString("__import__")); 17 | PyObject module = importer.__call__(Py.newString(moduleName)); 18 | klass = module.__getattr__(className); 19 | System.err.println("module=" + module + ",class=" + klass); 20 | } 21 | 22 | public JythonObjectFactory(Class interfaceType, String moduleName, String className) { 23 | this(new PySystemState(), interfaceType, moduleName, className); 24 | } 25 | 26 | public Object createObject() { 27 | return klass.__call__().__tojava__(interfaceType); 28 | } 29 | 30 | public Object createObject(Object arg1) { 31 | return klass.__call__(Py.java2py(arg1)).__tojava__(interfaceType); 32 | } 33 | 34 | public Object createObject(Object arg1, Object arg2) { 35 | return klass.__call__(Py.java2py(arg1), Py.java2py(arg2)).__tojava__(interfaceType); 36 | } 37 | 38 | public Object createObject(Object arg1, Object arg2, Object arg3) { 39 | return klass.__call__(Py.java2py(arg1), Py.java2py(arg2), Py.java2py(arg3)).__tojava__(interfaceType); 40 | } 41 | 42 | public Object creatObject(Object args[], String keywords[]) { 43 | PyObject convertedArgs[] = new PyObject[args.length]; 44 | for (int i = 0; i < args.length; i++) { 45 | convertedArgs[i] = Py.java2py(args[i]); 46 | } 47 | return klass.__call__(convertedArgs, keywords).__tojava__(interfaceType); 48 | } 49 | 50 | public Object creatObject(Object... args) { 51 | return createObject(args, Py.NoKeywords); 52 | } 53 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/java/rickaym/pyforge/events/PyEventBusWrapper.java: -------------------------------------------------------------------------------- 1 | package rickaym.pyforge.events; 2 | 3 | import net.minecraftforge.eventbus.api.*; 4 | import org.python.core.*; 5 | 6 | import java.util.function.Consumer; 7 | 8 | 9 | public class PyEventBusWrapper { 10 | final IEventBus eventBus; 11 | 12 | public static PyEventBusWrapper from(IEventBus eventBus) { 13 | return new PyEventBusWrapper(eventBus); 14 | } 15 | 16 | public PyEventBusWrapper(IEventBus eventBus) { 17 | this.eventBus = eventBus; 18 | } 19 | 20 | public void register(PyObject target) { 21 | PyType type = (PyType) target.getType(); 22 | for (PyObject name : type.getDict() 23 | .__iter__() 24 | .asIterable()) { 25 | PyObject value = type.getDict() 26 | .__finditem__(name); 27 | 28 | // if (value instanceof PyFunction) { 29 | // if (value.__getattr__("__event_subscriber__") == Py.True) { 30 | // eventBus.register(); 31 | // eventBus.addListener(new Object() { 32 | // @SubscribeEvent 33 | // public void onEvent(Event event) { 34 | // value.__call__(event); 35 | // } 36 | // }); 37 | // } 38 | // } 39 | } 40 | } 41 | 42 | public , F> void addGenericListener 43 | (Class genericClassFilter, Consumer consumer) { 44 | 45 | } 46 | 47 | public , F> void addGenericListener 48 | (Class genericClassFilter, EventPriority priority, Consumer consumer) { 49 | 50 | } 51 | 52 | public , F> void addGenericListener 53 | (Class genericClassFilter, EventPriority priority, boolean receiveCancelled, Consumer consumer) { 54 | 55 | } 56 | 57 | public , F> void addGenericListener 58 | (Class genericClassFilter, EventPriority priority, boolean receiveCancelled, Class< 59 | T> eventType, Consumer consumer) { 60 | 61 | } 62 | 63 | public void unregister(Object object) { 64 | 65 | } 66 | 67 | public boolean post(Event event) { 68 | return false; 69 | } 70 | 71 | public boolean post(Event event, IEventBusInvokeDispatcher wrapper) { 72 | return false; 73 | } 74 | 75 | public void shutdown() { 76 | 77 | } 78 | 79 | public void start() { 80 | 81 | } 82 | } -------------------------------------------------------------------------------- /src/main/java/rickaym/pyforge/PyLanguageProvider.java: -------------------------------------------------------------------------------- 1 | package rickaym.pyforge; 2 | 3 | import net.minecraftforge.fml.loading.moddiscovery.ModInfo; 4 | import net.minecraftforge.forgespi.language.*; 5 | 6 | import java.lang.reflect.Constructor; 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.util.Map; 9 | import java.util.function.Consumer; 10 | import java.util.function.Function; 11 | import java.util.function.Supplier; 12 | import java.util.stream.Collectors; 13 | 14 | import org.apache.logging.log4j.LogManager; 15 | import org.apache.logging.log4j.Logger; 16 | 17 | import static net.minecraftforge.fml.Logging.LOADING; 18 | 19 | 20 | public class PyLanguageProvider implements IModLanguageProvider { 21 | private static final Logger LOGGER = LogManager.getLogger(); 22 | 23 | @Override 24 | public String name() { 25 | return "pyforge"; 26 | } 27 | 28 | public static class PyModTarget implements IModLanguageProvider.IModLanguageLoader { 29 | private final String entryClass; 30 | private final String modId; 31 | 32 | private PyModTarget(String entryClass, String modId) { 33 | this.entryClass = entryClass; 34 | this.modId = modId; 35 | } 36 | 37 | public String getModId() { 38 | return modId; 39 | } 40 | 41 | @Override 42 | @SuppressWarnings("unchecked") 43 | public T loadMod(final IModInfo info, final ClassLoader modClassLoader, final ModFileScanData modFileScanResults) { 44 | try { 45 | LOGGER.debug(LOADING, "Loading mod '{}' at entry class '{}'", info.getModId(), entryClass); 46 | final Class pyContainer = Class.forName("rickaym.pyforge.PyModContainer", true, 47 | Thread.currentThread() 48 | .getContextClassLoader()); 49 | final Constructor constructor; 50 | constructor = pyContainer.getConstructor(IModInfo.class, String.class); 51 | T modContainer = (T) constructor.newInstance(info, entryClass); 52 | LOGGER.debug(LOADING, "Loaded mod container {}", modContainer); 53 | return modContainer; 54 | } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | 55 | InvocationTargetException e) { 56 | throw new RuntimeException(e); 57 | } 58 | } 59 | } 60 | 61 | @Override 62 | public Consumer getFileVisitor() { 63 | return scanResult -> { 64 | Map modTargetMap = scanResult.getIModInfoData() 65 | .stream() 66 | .map((IModFileInfo infoData) -> ((ModInfo) infoData.getMods() 67 | .get(0))) 68 | .map(ad -> new PyModTarget((String) ad.getConfigElement("entryClass") 69 | .orElse(null), ad.getModId())) 70 | .collect(Collectors.toMap(PyModTarget::getModId, Function.identity())); 71 | LOGGER.debug(LOADING, "Adding into language loader mod target map {}", modTargetMap); 72 | scanResult.addLanguageLoader(modTargetMap); 73 | }; 74 | } 75 | 76 | @Override 77 | public > void consumeLifecycleEvent(Supplier supplier) { 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/rickaym/pyforge/PyModContainer.java: -------------------------------------------------------------------------------- 1 | package rickaym.pyforge; 2 | 3 | import net.minecraftforge.eventbus.EventBusErrorMessage; 4 | import net.minecraftforge.eventbus.api.BusBuilder; 5 | import net.minecraftforge.eventbus.api.Event; 6 | import net.minecraftforge.eventbus.api.IEventBus; 7 | import net.minecraftforge.eventbus.api.IEventListener; 8 | import net.minecraftforge.fml.ModContainer; 9 | import net.minecraftforge.fml.ModLoadingException; 10 | import net.minecraftforge.fml.ModLoadingStage; 11 | import net.minecraftforge.fml.event.lifecycle.IModBusEvent; 12 | import net.minecraftforge.forgespi.language.IModInfo; 13 | import net.minecraftforge.forgespi.language.ModFileScanData; 14 | import org.apache.logging.log4j.LogManager; 15 | import org.apache.logging.log4j.Logger; 16 | import rickaym.pyforge.events.PyEventBusWrapper; 17 | 18 | import static net.minecraftforge.fml.Logging.LOADING; 19 | 20 | import java.nio.file.Paths; 21 | 22 | /** 23 | * This is the default implementation. 24 | *

25 | * Extending the abstract class ModContainer to make a mod wrapper that comforts interactions with 26 | * the mod loading service and the overall system contact and management. 27 | *

28 | *

29 | * Check the {@link ModContainer} class to understand more about what this class implements. 30 | *

31 | * 32 | * @see IModInfo 33 | * @see ModFileScanData 34 | */ 35 | public class PyModContainer extends ModContainer { 36 | private static final Logger LOGGER = LogManager.getLogger(); 37 | 38 | /** 39 | * Integrated @Mod Java instance 40 | **/ 41 | private WrappedModInstance modInstance; 42 | private final String entryClass; 43 | private final IModInfo modInfo; 44 | public IEventBus eventBus; 45 | 46 | /** 47 | * Puts the appropriate mod instantiation method `constructMod` on the activity 48 | * map. It is called somewhere deep in the fml accordingly. 49 | * 50 | * @param info IModInfo is an interface with getters and setters that fetches corresponding mod data, this surmises a mod 51 | */ 52 | public PyModContainer(IModInfo info, String entryClass) { 53 | // Calls the ModContainer constructor, this will do the job of registering the modId, 54 | // reserve a name space and instantiate the mod loading stage 55 | super(info); 56 | this.modInfo = info; 57 | this.entryClass = entryClass; 58 | PyModLoadingContext ctx = new PyModLoadingContext(this); 59 | this.contextExtension = () -> ctx; 60 | LOGGER.debug(LOADING, "Creating PyModContainer instance."); 61 | eventBus = BusBuilder.builder() 62 | .setExceptionHandler(this::onEventFailed) 63 | .setTrackPhases(false) 64 | .build(); 65 | activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod); 66 | } 67 | 68 | private void onEventFailed(IEventBus eventBus, Event event, IEventListener[] listeners, int busId, Throwable throwable) { 69 | LOGGER.error(new EventBusErrorMessage(event, busId, listeners, throwable)); 70 | } 71 | 72 | private void constructMod() { 73 | LOGGER.debug(LOADING, "Constructing mod from entry class {}", entryClass); 74 | modInstance = PyModLoader.loadMod(Paths.get("../src") 75 | .toAbsolutePath() 76 | .normalize() 77 | .toString(), entryClass); 78 | LOGGER.debug(LOADING, "Mod constructed {}", modInstance); 79 | } 80 | 81 | /** 82 | * Does this mod match the supplied mod? 83 | * 84 | * @param mod to compare 85 | * @return if the mod matches 86 | */ 87 | @Override 88 | public boolean matches(Object mod) { 89 | return mod == modInstance; 90 | } 91 | 92 | /** 93 | * @return the mod object instance 94 | */ 95 | @Override 96 | public Object getMod() { 97 | return modInstance; 98 | } 99 | 100 | @Override 101 | public void acceptEvent(T e) { 102 | try { 103 | LOGGER.trace("Firing event for modid $modId : $e"); 104 | eventBus.post(e); 105 | LOGGER.trace("Fired event for modid $modId : $e"); 106 | } catch (Throwable t) { 107 | LOGGER.error("Caught exception during event $e dispatch for modid $modId", t); 108 | throw new ModLoadingException(modInfo, modLoadingStage, "fml.modloading.errorduringevent", t); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /docs/jamboard.md: -------------------------------------------------------------------------------- 1 | # JamBoard 2 | 3 | This is intended for contributors only (currently just me tho :))! Also 4 | includes assumptions and pre-set positions and does not guarantee to be 5 | accurate - it\'s why this isn\'t attached in the sphinx docs. 6 | 7 | ## Language Providers 8 | 9 | Other existing language providers for Forge; may be useful for common 10 | practices. 11 | 12 | [Scorge](https://github.com/MinecraftForge/Scorge) 13 | 14 | root: 15 | `src/main.jython.rickaym.main/scala/net/minecraftforge/scorge/lang...` 16 | providerEntry: 17 | `src/main.jython.rickaym.main/resources/META-INF/services/"net.minecraftforge.forgespi.language.IModLanguageProvider"` 18 | 19 | [KotlinForForge](https://github.com/thedarkcolour/KotlinForForge) 20 | 21 | root: 22 | `src/main.jython.rickaym.main/kotlin/thedarkcolour/kotlinforforge...` 23 | providerEntry: 24 | `src/main.jython.rickaym.main/resources/META-INF/services/"net.minecraftforge.forgespi.language.IModLanguageProvider"` 25 | 26 | # Information 27 | 28 | ## How do you integrate Jython classes into Java? 29 | 30 | The most common way to achieve this is by utilizing the object factory 31 | design pattern. This means that for Jython to go upstream into Java, 32 | that class object must have an implementable Java interface. By using 33 | this Java interface you can create a Python subclass of the interface. 34 | In essence, the interface is the Java counter-part of the Python class 35 | that is needed for integration to be possible. The Python subclass will 36 | now be available to the Java code by using the python executor of the 37 | `jython.jar` package. 38 | 39 | \"1.16.5 looks for the mods.toml file. In there the loader field 40 | indicates which language provider is responsible for loading, which is 41 | javafml javafml then reads the mods.toml and builds the mods that way 42 | Then, the specified file system is scanned by javafml for a class with 43 | the \@Mod annotation An \@Mod without a corresponding mod entry is 44 | marked as an error. The same happens viceversa The run configuration 45 | injects some Metadata into the environment variables in the Form of 46 | MOD_CLASSES \" 47 | 48 | ## How does the internal FML system load through LanguageProviders? 49 | 50 | Note: `fml` is `net.minecraftforge.fml` in the codebase 51 | 52 | 1. Mod loading starts in `fml.Client.ClientModLoader:103`, calling 53 | `fml.ModLoader.gatherAndInitializeMods(...)` 54 | 2. `fml.ModLoader.gatherAndInitializeMods:175` calls 55 | `fml.ModLoader.buildMods(...)` to get `` `ModContainer ``s 56 | 3. `fml.ModLoader.buildMods:272` calls 57 | `fml.ModLoader.buildModContainerFromTOML(...)` to build 58 | `ModContainer`s 59 | 4. in the `fml.ModLoader.buildModContainerFromTOML` function, the 60 | `IModLanguageLoader` is parsed from the `mods.toml` file, it is then 61 | loaded as a service loader from the classpath 62 | 5. the `IModLanguageLoader` is then used to load the mod container by 63 | calling `IModLanguageLoader.loadMod(...)`. 64 | 65 | ## How does a language provider work? 66 | 67 | 1. The Language Provider is placed inside the mods directory and is 68 | loaded as a ServiceLoader from the classpath - as with all service 69 | loaders, it is guided by the 70 | `net.minecraftforge.forgespi.language.IModLanguageProvider` file 71 | inside services,`META-INF/services` referenced in the code as 72 | `providerEntry`. Watch 73 | `here `{.interpreted-text 74 | role="ref"}\_ and read 75 | `read here `{.interpreted-text 76 | role="ref"}\_ to learn more about how this system works. 77 | 78 | Let\'s assume that we\'ve made a language provider called 79 | UServiceProvided and have inserted it into the meta-inf folder. 80 | 81 | 2\. Any class that implements `IModLanguageProvider` must override 82 | several methods, most importantly the `loadMod` method The `loadMod` 83 | method is called in the system level classLoader @ 84 | net.minecraftforge.fml.ModLoader:296. With `loadMod`, we are given 3 85 | useful parameters 86 | `IModInfo info, ClassLoader modClassLoader, ModFileScanResults scanResults` 87 | 88 | Parameter 1, `info` is fetched from the `modInfoMap` @ 89 | net.minecraftforge.fml.ModLoader:269, this is generated from the mod 90 | file 91 | 92 | Parameter 2, `modClassLoader` java class loader in the correct context 93 | 94 | Parameter 3, `scanResults` internal mod scanning stuff done somewhere in 95 | the system mod loader and has an implementable IModLocator that we can 96 | work with to implement scanning \-- loaded as a service loader as well 97 | 98 | 3. `loadMod` proceeds depending on the Language Provider 99 | implementation - generally it returns a Mod container instance 100 | 101 | (TO BE CONTINUED) 102 | 103 | ::: warning 104 | ::: title 105 | Warning 106 | ::: 107 | 108 | To implement; - build.gradle - mods.toml 109 | ::: 110 | 111 | ::: note 112 | ::: title 113 | Note 114 | ::: 115 | 116 | Check out: \| [Scala Language 117 | Provider](https://github.com/MinecraftForge/Scorge) \| [Kotlin Language 118 | Provider](https://github.com/thedarkcolour/KotlinForForge) \| [Jython 119 | Docs](https://jython.readthedocs.io/en/latest) \| [Jython 120 | UserGuide](https://wiki.python.org/jython/UserGuide) and importantly 121 | [Chapter 122 | 10](https://jython.readthedocs.io/en/latest/JythonAndJavaIntegration/?highlight=generics#chapter-10-jython-and-java-integration) 123 | \| [Forge Docs](https://mcforge.readthedocs.io/en/latest) and [Minecraft 124 | Forge Repository](https://github.com/MinecraftForge/MinecraftForge) \| 125 | [Java Doc Comment 126 | Spec](https://docs.oracle.com/en/java/javase/11/docs/specs/doc-comment-spec.html) 127 | ::: 128 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ![Static Badge](https://img.shields.io/badge/Forge-Try%20Now-4f0000?style=for-the-badge) 4 | ![Static Badge](https://readthedocs.org/projects/pip/badge/?version=latest&style=for-the-badge) 5 | 6 | # Getting Started 7 | 8 | **PyForge** is a Python language provider crafted for Minecraft Forge. It leverages the Jython implementation of Python which runs on the JVM. The mod loader is compatible with CPython 2.7.x syntax and is designed to support a comprehensive implementation of a Forge Mod. 9 | 10 | A language provider for the Fabric Mod Loader is also in the works. 11 | 12 | [See an example mod using PyForge here](https://github.com/Rickaym/pymod). 13 | 14 | I created pyforge to test Jython's capabilities and potentially find a way into Minecraft modding using Python. 15 | 16 | Read more after this at [pyforge-mc.readthedocs.io](https://pyforge-mc.readthedocs.io/en/latest/) if you are on GitHub. 17 | 18 | 19 | > [!WARNING] 20 | > 21 | > Pyforge is usable at this point, but much work remains to be done. 22 | 23 | !!! warning 24 | Pyforge is usable at this point, but much work remains to be done. 25 | 26 | ## Version Support 27 | 28 | - 1.16.5-36 29 | 30 | ## Quickstart 31 | 32 | The directory structure of a pyforge mod is the same as that of its Java equivalent. The only difference with our mod is that the package name must be the same as the mod id rather than in Java, conventionally, `com.rickaym.mod`. 33 | 34 | E.g. 35 | ```python 36 | ┓ 37 | ┣━ ... 38 | ┣━ build.gradle 39 | ┗━ src ┓ 40 | ┣━ pymod ┓ 41 | ┃ ┣━ __init__.py 42 | ┃ ┣━ main.py 43 | ┃ ┣━ ext.py 44 | ┃ ┗━ more_ext.py 45 | ┃ 46 | ┗━ resources ┓ 47 | ┣━ ... 48 | ┗━ META-INF ┓ 49 | ┗━ mods.toml 50 | ``` 51 | 52 | ### Setup 53 | 54 | The `__init__.py` file inside the `src.pymod` directory serves as the entry point to the mod. To set up the mod, you have to define a function inside the `__init__.py` file called `get_mod_instance` that readily returns an instance of the mod. 55 | 56 | ```python 57 | # __init__.py 58 | 59 | from main import MyMod 60 | 61 | get_mod_instance = lambda: MyMod() 62 | ``` 63 | 64 | To implement the mod class, decorate it with the `@Mod` decorator and define the `register` method. 65 | 66 | ```py 67 | # main.py 68 | 69 | import org.apache.logging.log4j.LogManager as LogManager 70 | 71 | # import the class decorator from the jar 72 | from rickaym.pyforge import Mod 73 | 74 | @Mod(mod_id="pymod") 75 | class MyMod: 76 | ... 77 | 78 | def __init__(self): 79 | self.LOGGER = LogManager.getLogger() 80 | self.LOGGER.info("Pymod is loaded 🐍☕") 81 | 82 | def register(self): 83 | # Some registration logic 84 | ... 85 | ``` 86 | 87 | Finally, you need a mods.toml file that describes the mod and sets pyforge as its mod loader. 88 | 89 | ```toml 90 | modLoader="pyforge" 91 | loaderVersion="(,1.0)" 92 | license='MIT' 93 | 94 | [[mods]] 95 | modId="pymod" #mandatory 96 | entryClass="pymod" 97 | version="1.0" #mandatory 98 | displayName="pymod" #mandatory 99 | credits="Example mod using the Python language provider." 100 | authors="Rickaym" #optional 101 | description=''' 102 | Mod written completely in Python 2.7 and built with Gradle! 103 | ''' 104 | 105 | [[dependencies.pymod]] 106 | ... 107 | ``` 108 | 109 | !!! note 110 | Throughout the project, you will see a lot of Java concepts and conventions carry over. You should have at least a basic level of understanding in Java to work comfortably with pyforge. Specifically, gradle and 111 | 112 | Run the client! 113 | 114 | 115 | 116 | 117 | ## How it works 118 | 119 | Pyforge is written purely in Java and naturally it produces a jar file. You can download the latest jar [here](https://github.com/Rickaym/pyforge/releases) and save it somewhere accessible. Afterwards, put it as a dependency in the mod's `build.gradle` file: 120 | 121 | ```gradle 122 | dependencies { 123 | ... 124 | 125 | implementation files('your-path/pyforge-0.0.2.jar') 126 | 127 | ... 128 | } 129 | ``` 130 | 131 | **Manually Building Pyforge** 132 | 133 | This is the recommended way of using pyforge for development. Clone and load the project on Intellij. Manually build the jar file by executing the `build` command from gradle. This should build the jar file at a path like `D:\...\pyforge\build\libs\pyforge-0.0.2.jar`, and put this to the build.gradle dependencies section. 134 | 135 | 136 | ### Mod Loading 137 | 138 | The mod loading process looks like this: 139 | 140 | - In the first stage of the mod loader, it searches for packages that contain a `__init__` file. 141 | 142 | - The next step is to import the package and get the mod instance. Pyforge doesn't search for the mod class or construct it by itself, it requires the mod to expose a factory supplier `get_mod_instance` that readily returns a new instance of the mod. 143 | 144 | - It then checks the mod instance for metadata that is assigned by the `@Mod` decorator. Once we have these, the mod is ready! 145 | 146 | For starters, Jython means you can import both Java and Python libraries into your project and use them seamlessly. It is recommended to read the [jython docs](https://jython.readthedocs.io/en/latest/). 147 | 148 | Pyforge is only designed to handle the mod loading process. It intentionally avoids defining any standards or ways to interact with the Forge library. Some common practices are required to work harmoniously with Pyforge but all the rest ascribe to Forge's architecture. This means that you should refer to the official Forge documentation https://docs.minecraftforge.net/ for all modding related information. 149 | 150 | 151 | ## Contribution and Testing 152 | 153 | Contributions are welcome. Contact `@rick.aym` on discord or join [the discord server](https://discord.gg/UmnzdPgn6g). 154 | -------------------------------------------------------------------------------- /src/main/java/rickaym/pyforge/PyModLoader.java: -------------------------------------------------------------------------------- 1 | package rickaym.pyforge; 2 | 3 | import org.python.core.*; 4 | import org.python.jline.internal.Nullable; 5 | import org.python.util.PythonInterpreter; 6 | 7 | import java.io.*; 8 | import java.nio.file.Files; 9 | import java.nio.file.Path; 10 | import java.nio.file.Paths; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.stream.Collectors; 14 | import java.util.stream.Stream; 15 | 16 | import org.apache.logging.log4j.LogManager; 17 | import org.apache.logging.log4j.Logger; 18 | 19 | import static net.minecraftforge.fml.Logging.LOADING; 20 | 21 | /** 22 | * Intermediary module loader for mod and extension classes. The PyModLoader is responsible for the heavy lifting 23 | * required between Java-Python (Jython) conversion, as well as for scanning mod files and initializing modules. 24 | * 25 | * @see Examples 26 | */ 27 | public class PyModLoader { 28 | private static final String INIT_FILE_NAME = "__init__.py"; 29 | private static final String MOD_GETTER_FUNCTION = "get_mod_instance"; 30 | private static final String IMPORT_FUNCTION = "__import__"; 31 | private static List entryFiles; 32 | private static String modEntryFilePath; 33 | 34 | // Ideally, it would be best to load the mod class without instantiating the 35 | // interpreter, using PySystemState alone, but only the interpreter approach has worked so far. 36 | // private static PySystemState sys = new PySystemState(); 37 | private static final PythonInterpreter jyInterpreter = new PythonInterpreter(); 38 | private PyInstance modInstance; 39 | private static final Logger LOGGER = LogManager.getLogger(); 40 | 41 | public PyModLoader findEntryFiles(String rootDir) { 42 | List files = new ArrayList<>(); 43 | try (Stream paths = Files.walk(Paths.get(rootDir))) { 44 | files = paths.filter(Files::isRegularFile) // Filter out directories, we only want files 45 | .filter(path -> path.getFileName() 46 | .toString() 47 | .equals(INIT_FILE_NAME)) // Check if file name is __init__.py 48 | .collect(Collectors.toList()); // Collect results to a list 49 | } catch (IOException e) { 50 | e.printStackTrace(); 51 | } 52 | entryFiles = files; 53 | return this; 54 | } 55 | 56 | /** 57 | * Finds the mod entry file and returns the path to it. 58 | */ 59 | @Nullable 60 | public PyModLoader findModEntryFile() { 61 | String entryFilePath = null; 62 | for (Path filePath : entryFiles) { 63 | try { 64 | BufferedReader reader = new BufferedReader(new FileReader(filePath.toFile() 65 | .getPath())); 66 | String line = reader.readLine(); 67 | 68 | while (line != null && entryFilePath == null) { 69 | if (line.contains(MOD_GETTER_FUNCTION)) { 70 | entryFilePath = filePath.toFile() 71 | .getPath(); 72 | LOGGER.debug(LOADING, "Found the mod entry file '{}'.\n", entryFilePath); 73 | } 74 | line = reader.readLine(); 75 | } 76 | reader.close(); 77 | } catch (IOException e) { 78 | e.printStackTrace(); 79 | } 80 | if (entryFilePath != null) { 81 | break; 82 | } 83 | } 84 | modEntryFilePath = entryFilePath; 85 | return this; 86 | } 87 | 88 | private PyObject getModModule(String sourceDir) { 89 | PyObject module; 90 | String[] descPath = modEntryFilePath.replace("\\", "/") 91 | .split("/"); 92 | LOGGER.debug(LOADING, "Finding the mod class supplier function in {}.\n", modEntryFilePath); 93 | String moduleName = descPath[descPath.length - 2]; 94 | 95 | // sys.path.append(Py.newString(sourceDir)); 96 | // PyObject importer = sys.getBuiltins() 97 | // .__getitem__(Py.newString(IMPORT_FUNCTION)); 98 | // System.out.format("%s importer calling the top level module '%s'.\n", importer, moduleName); 99 | // module = importer.__call__(Py.newString(moduleName)); 100 | jyInterpreter.exec("import sys"); 101 | jyInterpreter.exec(String.format("sys.path.append(\"%s\")", sourceDir)); 102 | jyInterpreter.exec(String.format("import %s", moduleName)); 103 | module = jyInterpreter.get(moduleName); 104 | LOGGER.debug(LOADING, "Loaded in module '{}'", module); 105 | return module; 106 | } 107 | 108 | /** 109 | * Initializes the module by importing the module and calling the mod getter function. 110 | */ 111 | private void initializeMod(String sourceDir) { 112 | PyObject modModule = getModModule(sourceDir); 113 | PyList attrs = (PyList) modModule.__dir__(); 114 | 115 | if (attrs.__contains__(Py.newString(MOD_GETTER_FUNCTION))) { 116 | LOGGER.debug(LOADING, "Fetched the get_mod_instance supplier from the top level entry module."); 117 | PyObject modSupplier = modModule.__getattr__(MOD_GETTER_FUNCTION); 118 | // calls on the mod supplier function to create the instance 119 | modInstance = (PyInstance) modSupplier.__call__(); 120 | LOGGER.debug(LOADING, "Instantiated the mod instance '{}' with metadata {}.\n", modInstance, 121 | modInstance.invoke("__mod_meta__")); 122 | } 123 | } 124 | 125 | /** 126 | * @return IPyModClass of Mod Class implementation 127 | */ 128 | public static WrappedModInstance loadMod(String sourceDir, String moduleName) { 129 | PyModLoader loader = new PyModLoader(); 130 | String absModuleRoot = Paths.get(sourceDir, moduleName) 131 | .toAbsolutePath() 132 | .toString(); 133 | LOGGER.debug(LOADING, "Gathering entry files recursively from the module root directory '{}'.\n", 134 | absModuleRoot); 135 | loader.findEntryFiles(absModuleRoot) 136 | .findModEntryFile() 137 | .initializeMod(sourceDir); 138 | return new WrappedModInstance(loader.modInstance); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | --------------------------------------------------------------------------------