diff --git a/.cache/clangd/index/.null-ls_947684_Test.cpp.DB38D9A5602D5B5E.idx b/.cache/clangd/index/.null-ls_947684_Test.cpp.DB38D9A5602D5B5E.idx deleted file mode 100644 index ebcb7e2..0000000 Binary files a/.cache/clangd/index/.null-ls_947684_Test.cpp.DB38D9A5602D5B5E.idx and /dev/null differ diff --git a/.cache/clangd/index/Allocators.cpp.556DFD68EFF599B7.idx b/.cache/clangd/index/Allocators.cpp.556DFD68EFF599B7.idx deleted file mode 100644 index f77e293..0000000 Binary files a/.cache/clangd/index/Allocators.cpp.556DFD68EFF599B7.idx and /dev/null differ diff --git a/.cache/clangd/index/Allocators.hpp.BFBAA8A4FE8DF7EF.idx b/.cache/clangd/index/Allocators.hpp.BFBAA8A4FE8DF7EF.idx deleted file mode 100644 index 4291dc4..0000000 Binary files a/.cache/clangd/index/Allocators.hpp.BFBAA8A4FE8DF7EF.idx and /dev/null differ diff --git a/.cache/clangd/index/Animations.cpp.6C977FC51783DD42.idx b/.cache/clangd/index/Animations.cpp.6C977FC51783DD42.idx deleted file mode 100644 index 20ec024..0000000 Binary files a/.cache/clangd/index/Animations.cpp.6C977FC51783DD42.idx and /dev/null differ diff --git a/.cache/clangd/index/Animations.hpp.121469E5A08466E0.idx b/.cache/clangd/index/Animations.hpp.121469E5A08466E0.idx deleted file mode 100644 index 70e0d55..0000000 Binary files a/.cache/clangd/index/Animations.hpp.121469E5A08466E0.idx and /dev/null differ diff --git a/.cache/clangd/index/Archiver.hpp.A25D3F2B46296B4E.idx b/.cache/clangd/index/Archiver.hpp.A25D3F2B46296B4E.idx deleted file mode 100644 index f49383f..0000000 Binary files a/.cache/clangd/index/Archiver.hpp.A25D3F2B46296B4E.idx and /dev/null differ diff --git a/.cache/clangd/index/Assert.cpp.8D786DCBB40248EE.idx b/.cache/clangd/index/Assert.cpp.8D786DCBB40248EE.idx deleted file mode 100644 index d06812c..0000000 Binary files a/.cache/clangd/index/Assert.cpp.8D786DCBB40248EE.idx and /dev/null differ diff --git a/.cache/clangd/index/Assert.hpp.C19820BE28569501.idx b/.cache/clangd/index/Assert.hpp.C19820BE28569501.idx deleted file mode 100644 index d8c563f..0000000 Binary files a/.cache/clangd/index/Assert.hpp.C19820BE28569501.idx and /dev/null differ diff --git a/.cache/clangd/index/AutomataGraph.h.D2A0EFBA5D4E223D.idx b/.cache/clangd/index/AutomataGraph.h.D2A0EFBA5D4E223D.idx deleted file mode 100644 index 0bbd984..0000000 Binary files a/.cache/clangd/index/AutomataGraph.h.D2A0EFBA5D4E223D.idx and /dev/null differ diff --git a/.cache/clangd/index/Buffer.hpp.E4B72645387D73E8.idx b/.cache/clangd/index/Buffer.hpp.E4B72645387D73E8.idx deleted file mode 100644 index e5e7bda..0000000 Binary files a/.cache/clangd/index/Buffer.hpp.E4B72645387D73E8.idx and /dev/null differ diff --git a/.cache/clangd/index/Buffer2D.hpp.F936B1D51D85DFA1.idx b/.cache/clangd/index/Buffer2D.hpp.F936B1D51D85DFA1.idx deleted file mode 100644 index 2847fc1..0000000 Binary files a/.cache/clangd/index/Buffer2D.hpp.F936B1D51D85DFA1.idx and /dev/null differ diff --git a/.cache/clangd/index/Buffer2DTest.cpp.49358C25C3339422.idx b/.cache/clangd/index/Buffer2DTest.cpp.49358C25C3339422.idx deleted file mode 100644 index 7c5a0ed..0000000 Binary files a/.cache/clangd/index/Buffer2DTest.cpp.49358C25C3339422.idx and /dev/null differ diff --git a/.cache/clangd/index/BufferTest.cpp.1AC5B746F96EE9EF.idx b/.cache/clangd/index/BufferTest.cpp.1AC5B746F96EE9EF.idx deleted file mode 100644 index a08c54f..0000000 Binary files a/.cache/clangd/index/BufferTest.cpp.1AC5B746F96EE9EF.idx and /dev/null differ diff --git a/.cache/clangd/index/CLR.cpp.1902C569BDB83CA6.idx b/.cache/clangd/index/CLR.cpp.1902C569BDB83CA6.idx deleted file mode 100644 index ad6ac78..0000000 Binary files a/.cache/clangd/index/CLR.cpp.1902C569BDB83CA6.idx and /dev/null differ diff --git a/.cache/clangd/index/CLR.hpp.CDFF28D47A1B6357.idx b/.cache/clangd/index/CLR.hpp.CDFF28D47A1B6357.idx deleted file mode 100644 index 25a0811..0000000 Binary files a/.cache/clangd/index/CLR.hpp.CDFF28D47A1B6357.idx and /dev/null differ diff --git a/.cache/clangd/index/CLRTests.cpp.DE1F924BC944F639.idx b/.cache/clangd/index/CLRTests.cpp.DE1F924BC944F639.idx deleted file mode 100644 index a40095b..0000000 Binary files a/.cache/clangd/index/CLRTests.cpp.DE1F924BC944F639.idx and /dev/null differ diff --git a/.cache/clangd/index/Camera.cpp.7523D24D62BCA8D7.idx b/.cache/clangd/index/Camera.cpp.7523D24D62BCA8D7.idx deleted file mode 100644 index af8a9d2..0000000 Binary files a/.cache/clangd/index/Camera.cpp.7523D24D62BCA8D7.idx and /dev/null differ diff --git a/.cache/clangd/index/Camera.hpp.B07606E76202D65A.idx b/.cache/clangd/index/Camera.hpp.B07606E76202D65A.idx deleted file mode 100644 index 1255cbb..0000000 Binary files a/.cache/clangd/index/Camera.hpp.B07606E76202D65A.idx and /dev/null differ diff --git a/.cache/clangd/index/Canvas.cpp.B42F9C001EF2AD4E.idx b/.cache/clangd/index/Canvas.cpp.B42F9C001EF2AD4E.idx deleted file mode 100644 index 2852ecf..0000000 Binary files a/.cache/clangd/index/Canvas.cpp.B42F9C001EF2AD4E.idx and /dev/null differ diff --git a/.cache/clangd/index/CfGrammar.cpp.6C80FCC539639DD5.idx b/.cache/clangd/index/CfGrammar.cpp.6C80FCC539639DD5.idx deleted file mode 100644 index f2d69b2..0000000 Binary files a/.cache/clangd/index/CfGrammar.cpp.6C80FCC539639DD5.idx and /dev/null differ diff --git a/.cache/clangd/index/CfGrammar.hpp.3F1D78A697E0429F.idx b/.cache/clangd/index/CfGrammar.hpp.3F1D78A697E0429F.idx deleted file mode 100644 index 4236082..0000000 Binary files a/.cache/clangd/index/CfGrammar.hpp.3F1D78A697E0429F.idx and /dev/null differ diff --git a/.cache/clangd/index/CfGrammarParser.cpp.599610939A98E440.idx b/.cache/clangd/index/CfGrammarParser.cpp.599610939A98E440.idx deleted file mode 100644 index 084ed82..0000000 Binary files a/.cache/clangd/index/CfGrammarParser.cpp.599610939A98E440.idx and /dev/null differ diff --git a/.cache/clangd/index/Cfg.cpp.700F0005B847AFD8.idx b/.cache/clangd/index/Cfg.cpp.700F0005B847AFD8.idx deleted file mode 100644 index 83acb48..0000000 Binary files a/.cache/clangd/index/Cfg.cpp.700F0005B847AFD8.idx and /dev/null differ diff --git a/.cache/clangd/index/ChunkAllocator.hpp.3913093FF881DC0B.idx b/.cache/clangd/index/ChunkAllocator.hpp.3913093FF881DC0B.idx deleted file mode 100644 index c31f46b..0000000 Binary files a/.cache/clangd/index/ChunkAllocator.hpp.3913093FF881DC0B.idx and /dev/null differ diff --git a/.cache/clangd/index/CmdLineInterpreter.cpp.CB7347C57F853EAB.idx b/.cache/clangd/index/CmdLineInterpreter.cpp.CB7347C57F853EAB.idx deleted file mode 100644 index fb5b0a3..0000000 Binary files a/.cache/clangd/index/CmdLineInterpreter.cpp.CB7347C57F853EAB.idx and /dev/null differ diff --git a/.cache/clangd/index/CmdLineInterpreter.hpp.A34F818348C8A38D.idx b/.cache/clangd/index/CmdLineInterpreter.hpp.A34F818348C8A38D.idx deleted file mode 100644 index 1211993..0000000 Binary files a/.cache/clangd/index/CmdLineInterpreter.hpp.A34F818348C8A38D.idx and /dev/null differ diff --git a/.cache/clangd/index/Color.cpp.4DAC882033CC1275.idx b/.cache/clangd/index/Color.cpp.4DAC882033CC1275.idx deleted file mode 100644 index 9b726cc..0000000 Binary files a/.cache/clangd/index/Color.cpp.4DAC882033CC1275.idx and /dev/null differ diff --git a/.cache/clangd/index/Color.hpp.230C9F2844365B2D.idx b/.cache/clangd/index/Color.hpp.230C9F2844365B2D.idx deleted file mode 100644 index e442add..0000000 Binary files a/.cache/clangd/index/Color.hpp.230C9F2844365B2D.idx and /dev/null differ diff --git a/.cache/clangd/index/CommandLine.cpp.B912FD66482DFBEF.idx b/.cache/clangd/index/CommandLine.cpp.B912FD66482DFBEF.idx deleted file mode 100644 index 683d60e..0000000 Binary files a/.cache/clangd/index/CommandLine.cpp.B912FD66482DFBEF.idx and /dev/null differ diff --git a/.cache/clangd/index/CommandLine.hpp.934A9A86CD8FCCA5.idx b/.cache/clangd/index/CommandLine.hpp.934A9A86CD8FCCA5.idx deleted file mode 100644 index 863a88b..0000000 Binary files a/.cache/clangd/index/CommandLine.hpp.934A9A86CD8FCCA5.idx and /dev/null differ diff --git a/.cache/clangd/index/Common.cpp.17F19A5FEA07DBF9.idx b/.cache/clangd/index/Common.cpp.17F19A5FEA07DBF9.idx deleted file mode 100644 index eb96148..0000000 Binary files a/.cache/clangd/index/Common.cpp.17F19A5FEA07DBF9.idx and /dev/null differ diff --git a/.cache/clangd/index/Common.hpp.40599DCAE44CEE8C.idx b/.cache/clangd/index/Common.hpp.40599DCAE44CEE8C.idx deleted file mode 100644 index 1292613..0000000 Binary files a/.cache/clangd/index/Common.hpp.40599DCAE44CEE8C.idx and /dev/null differ diff --git a/.cache/clangd/index/ConnectionCommon.cpp.4B84FD22FB67FE81.idx b/.cache/clangd/index/ConnectionCommon.cpp.4B84FD22FB67FE81.idx deleted file mode 100644 index becc042..0000000 Binary files a/.cache/clangd/index/ConnectionCommon.cpp.4B84FD22FB67FE81.idx and /dev/null differ diff --git a/.cache/clangd/index/ConnectionCommon.hpp.D2FEDCCBED9817BE.idx b/.cache/clangd/index/ConnectionCommon.hpp.D2FEDCCBED9817BE.idx deleted file mode 100644 index 37db28c..0000000 Binary files a/.cache/clangd/index/ConnectionCommon.hpp.D2FEDCCBED9817BE.idx and /dev/null differ diff --git a/.cache/clangd/index/Containers.cpp.6803C4B5518D9DC4.idx b/.cache/clangd/index/Containers.cpp.6803C4B5518D9DC4.idx deleted file mode 100644 index 1ebc3a7..0000000 Binary files a/.cache/clangd/index/Containers.cpp.6803C4B5518D9DC4.idx and /dev/null differ diff --git a/.cache/clangd/index/ContainersCommon.hpp.15C73294E64BAAB5.idx b/.cache/clangd/index/ContainersCommon.hpp.15C73294E64BAAB5.idx deleted file mode 100644 index b74ff52..0000000 Binary files a/.cache/clangd/index/ContainersCommon.hpp.15C73294E64BAAB5.idx and /dev/null differ diff --git a/.cache/clangd/index/DebugGUI.cpp.F5E8B68D2130C971.idx b/.cache/clangd/index/DebugGUI.cpp.F5E8B68D2130C971.idx deleted file mode 100644 index 966a46c..0000000 Binary files a/.cache/clangd/index/DebugGUI.cpp.F5E8B68D2130C971.idx and /dev/null differ diff --git a/.cache/clangd/index/Debugging.cpp.1B526E26109178BF.idx b/.cache/clangd/index/Debugging.cpp.1B526E26109178BF.idx deleted file mode 100644 index 854976b..0000000 Binary files a/.cache/clangd/index/Debugging.cpp.1B526E26109178BF.idx and /dev/null differ diff --git a/.cache/clangd/index/Debugging.hpp.A1358CEABFFE85CA.idx b/.cache/clangd/index/Debugging.hpp.A1358CEABFFE85CA.idx deleted file mode 100644 index 5eb1a57..0000000 Binary files a/.cache/clangd/index/Debugging.hpp.A1358CEABFFE85CA.idx and /dev/null differ diff --git a/.cache/clangd/index/Disk.cpp.01204E4C4CB8D7D9.idx b/.cache/clangd/index/Disk.cpp.01204E4C4CB8D7D9.idx deleted file mode 100644 index 23b3163..0000000 Binary files a/.cache/clangd/index/Disk.cpp.01204E4C4CB8D7D9.idx and /dev/null differ diff --git a/.cache/clangd/index/Disk.hpp.8A732F7401A21559.idx b/.cache/clangd/index/Disk.hpp.8A732F7401A21559.idx deleted file mode 100644 index 7ac78b3..0000000 Binary files a/.cache/clangd/index/Disk.hpp.8A732F7401A21559.idx and /dev/null differ diff --git a/.cache/clangd/index/Environment.cpp.E48BE11EFF12B7CE.idx b/.cache/clangd/index/Environment.cpp.E48BE11EFF12B7CE.idx deleted file mode 100644 index 4d97be0..0000000 Binary files a/.cache/clangd/index/Environment.cpp.E48BE11EFF12B7CE.idx and /dev/null differ diff --git a/.cache/clangd/index/Environment.hpp.2C2398354429F20E.idx b/.cache/clangd/index/Environment.hpp.2C2398354429F20E.idx deleted file mode 100644 index 6a9938f..0000000 Binary files a/.cache/clangd/index/Environment.hpp.2C2398354429F20E.idx and /dev/null differ diff --git a/.cache/clangd/index/Example.cpp.263BED8F7AD343F5.idx b/.cache/clangd/index/Example.cpp.263BED8F7AD343F5.idx deleted file mode 100644 index b08e7c7..0000000 Binary files a/.cache/clangd/index/Example.cpp.263BED8F7AD343F5.idx and /dev/null differ diff --git a/.cache/clangd/index/GUI.cpp.19BAE71CC62CEB2F.idx b/.cache/clangd/index/GUI.cpp.19BAE71CC62CEB2F.idx deleted file mode 100644 index d80d27f..0000000 Binary files a/.cache/clangd/index/GUI.cpp.19BAE71CC62CEB2F.idx and /dev/null differ diff --git a/.cache/clangd/index/GUI.h.1264E7AB609DF62D.idx b/.cache/clangd/index/GUI.h.1264E7AB609DF62D.idx deleted file mode 100644 index 1a62dfb..0000000 Binary files a/.cache/clangd/index/GUI.h.1264E7AB609DF62D.idx and /dev/null differ diff --git a/.cache/clangd/index/GUIEntry.cpp.E0EB67ACA6DC214F.idx b/.cache/clangd/index/GUIEntry.cpp.E0EB67ACA6DC214F.idx deleted file mode 100644 index 5a1df51..0000000 Binary files a/.cache/clangd/index/GUIEntry.cpp.E0EB67ACA6DC214F.idx and /dev/null differ diff --git a/.cache/clangd/index/GrammarTests.cpp.A1E5F12624539FFB.idx b/.cache/clangd/index/GrammarTests.cpp.A1E5F12624539FFB.idx deleted file mode 100644 index 8379b5a..0000000 Binary files a/.cache/clangd/index/GrammarTests.cpp.A1E5F12624539FFB.idx and /dev/null differ diff --git a/.cache/clangd/index/Graphics.hpp.896D0A0CB52D768A.idx b/.cache/clangd/index/Graphics.hpp.896D0A0CB52D768A.idx deleted file mode 100644 index e0b1c7f..0000000 Binary files a/.cache/clangd/index/Graphics.hpp.896D0A0CB52D768A.idx and /dev/null differ diff --git a/.cache/clangd/index/GraphicsCommon.cpp.7CA98DE87530F232.idx b/.cache/clangd/index/GraphicsCommon.cpp.7CA98DE87530F232.idx deleted file mode 100644 index 3d6f547..0000000 Binary files a/.cache/clangd/index/GraphicsCommon.cpp.7CA98DE87530F232.idx and /dev/null differ diff --git a/.cache/clangd/index/GraphicsCommon.hpp.A570722961C7AA81.idx b/.cache/clangd/index/GraphicsCommon.hpp.A570722961C7AA81.idx deleted file mode 100644 index a7023f3..0000000 Binary files a/.cache/clangd/index/GraphicsCommon.hpp.A570722961C7AA81.idx and /dev/null differ diff --git a/.cache/clangd/index/HeapAllocator.cpp.97D224AC298B7C14.idx b/.cache/clangd/index/HeapAllocator.cpp.97D224AC298B7C14.idx deleted file mode 100644 index eb240f9..0000000 Binary files a/.cache/clangd/index/HeapAllocator.cpp.97D224AC298B7C14.idx and /dev/null differ diff --git a/.cache/clangd/index/HeapAllocator.hpp.D9CC4B8EC026D263.idx b/.cache/clangd/index/HeapAllocator.hpp.D9CC4B8EC026D263.idx deleted file mode 100644 index 6d3ffed..0000000 Binary files a/.cache/clangd/index/HeapAllocator.hpp.D9CC4B8EC026D263.idx and /dev/null differ diff --git a/.cache/clangd/index/HeapAllocatorGlobal.cpp.93C971B929A45F1D.idx b/.cache/clangd/index/HeapAllocatorGlobal.cpp.93C971B929A45F1D.idx deleted file mode 100644 index 86b2d34..0000000 Binary files a/.cache/clangd/index/HeapAllocatorGlobal.cpp.93C971B929A45F1D.idx and /dev/null differ diff --git a/.cache/clangd/index/HeapAllocatorGlobal.hpp.14FA3B2B9BE9ABB3.idx b/.cache/clangd/index/HeapAllocatorGlobal.hpp.14FA3B2B9BE9ABB3.idx deleted file mode 100644 index 23ee8fd..0000000 Binary files a/.cache/clangd/index/HeapAllocatorGlobal.hpp.14FA3B2B9BE9ABB3.idx and /dev/null differ diff --git a/.cache/clangd/index/Intersections.hpp.EE2A297ACEB5A95C.idx b/.cache/clangd/index/Intersections.hpp.EE2A297ACEB5A95C.idx deleted file mode 100644 index 6534291..0000000 Binary files a/.cache/clangd/index/Intersections.hpp.EE2A297ACEB5A95C.idx and /dev/null differ diff --git a/.cache/clangd/index/Keycodes.hpp.212C992475674625.idx b/.cache/clangd/index/Keycodes.hpp.212C992475674625.idx deleted file mode 100644 index a246d4e..0000000 Binary files a/.cache/clangd/index/Keycodes.hpp.212C992475674625.idx and /dev/null differ diff --git a/.cache/clangd/index/List.hpp.4BF956E0114C96C3.idx b/.cache/clangd/index/List.hpp.4BF956E0114C96C3.idx deleted file mode 100644 index f75c01e..0000000 Binary files a/.cache/clangd/index/List.hpp.4BF956E0114C96C3.idx and /dev/null differ diff --git a/.cache/clangd/index/ListTest.cpp.ECFE18A73652B13F.idx b/.cache/clangd/index/ListTest.cpp.ECFE18A73652B13F.idx deleted file mode 100644 index 0f7f225..0000000 Binary files a/.cache/clangd/index/ListTest.cpp.ECFE18A73652B13F.idx and /dev/null differ diff --git a/.cache/clangd/index/LocalConnection.cpp.0325DCB1525CF589.idx b/.cache/clangd/index/LocalConnection.cpp.0325DCB1525CF589.idx deleted file mode 100644 index c90e0d6..0000000 Binary files a/.cache/clangd/index/LocalConnection.cpp.0325DCB1525CF589.idx and /dev/null differ diff --git a/.cache/clangd/index/LocalConnection.hpp.FB28F19432032FCD.idx b/.cache/clangd/index/LocalConnection.hpp.FB28F19432032FCD.idx deleted file mode 100644 index a10587a..0000000 Binary files a/.cache/clangd/index/LocalConnection.hpp.FB28F19432032FCD.idx and /dev/null differ diff --git a/.cache/clangd/index/Logging.cpp.80F79BD5DEBFF435.idx b/.cache/clangd/index/Logging.cpp.80F79BD5DEBFF435.idx deleted file mode 100644 index 6c14e2f..0000000 Binary files a/.cache/clangd/index/Logging.cpp.80F79BD5DEBFF435.idx and /dev/null differ diff --git a/.cache/clangd/index/Logging.hpp.4213EBBF9CEBA786.idx b/.cache/clangd/index/Logging.hpp.4213EBBF9CEBA786.idx deleted file mode 100644 index 6544772..0000000 Binary files a/.cache/clangd/index/Logging.hpp.4213EBBF9CEBA786.idx and /dev/null differ diff --git a/.cache/clangd/index/Map.hpp.039D93F9BB6B63C5.idx b/.cache/clangd/index/Map.hpp.039D93F9BB6B63C5.idx deleted file mode 100644 index 1de4a80..0000000 Binary files a/.cache/clangd/index/Map.hpp.039D93F9BB6B63C5.idx and /dev/null differ diff --git a/.cache/clangd/index/MapTest.cpp.8E08B7C6B59FE3AE.idx b/.cache/clangd/index/MapTest.cpp.8E08B7C6B59FE3AE.idx deleted file mode 100644 index 68465c9..0000000 Binary files a/.cache/clangd/index/MapTest.cpp.8E08B7C6B59FE3AE.idx and /dev/null differ diff --git a/.cache/clangd/index/Mat.hpp.BDC77294B6C6017B.idx b/.cache/clangd/index/Mat.hpp.BDC77294B6C6017B.idx deleted file mode 100644 index 61681a3..0000000 Binary files a/.cache/clangd/index/Mat.hpp.BDC77294B6C6017B.idx and /dev/null differ diff --git a/.cache/clangd/index/MathCommon.cpp.7A75BEDBE754DDE0.idx b/.cache/clangd/index/MathCommon.cpp.7A75BEDBE754DDE0.idx deleted file mode 100644 index e71969e..0000000 Binary files a/.cache/clangd/index/MathCommon.cpp.7A75BEDBE754DDE0.idx and /dev/null differ diff --git a/.cache/clangd/index/MathCommon.hpp.F65F7690A429D85F.idx b/.cache/clangd/index/MathCommon.hpp.F65F7690A429D85F.idx deleted file mode 100644 index e9fb160..0000000 Binary files a/.cache/clangd/index/MathCommon.hpp.F65F7690A429D85F.idx and /dev/null differ diff --git a/.cache/clangd/index/Module.cpp.4480FB25611E6FCE.idx b/.cache/clangd/index/Module.cpp.4480FB25611E6FCE.idx deleted file mode 100644 index 9133c98..0000000 Binary files a/.cache/clangd/index/Module.cpp.4480FB25611E6FCE.idx and /dev/null differ diff --git a/.cache/clangd/index/Module.hpp.78DA83823D8DD971.idx b/.cache/clangd/index/Module.hpp.78DA83823D8DD971.idx deleted file mode 100644 index dc84c7e..0000000 Binary files a/.cache/clangd/index/Module.hpp.78DA83823D8DD971.idx and /dev/null differ diff --git a/.cache/clangd/index/Multithreading.hpp.D96320643316EC16.idx b/.cache/clangd/index/Multithreading.hpp.D96320643316EC16.idx deleted file mode 100644 index dc9ef4e..0000000 Binary files a/.cache/clangd/index/Multithreading.hpp.D96320643316EC16.idx and /dev/null differ diff --git a/.cache/clangd/index/Network.cpp.7D62B66949B08D9A.idx b/.cache/clangd/index/Network.cpp.7D62B66949B08D9A.idx deleted file mode 100644 index 83aa068..0000000 Binary files a/.cache/clangd/index/Network.cpp.7D62B66949B08D9A.idx and /dev/null differ diff --git a/.cache/clangd/index/Network.hpp.76C76499287A015A.idx b/.cache/clangd/index/Network.hpp.76C76499287A015A.idx deleted file mode 100644 index ec3a06d..0000000 Binary files a/.cache/clangd/index/Network.hpp.76C76499287A015A.idx and /dev/null differ diff --git a/.cache/clangd/index/NewPlacement.hpp.1928FAA55E835C9A.idx b/.cache/clangd/index/NewPlacement.hpp.1928FAA55E835C9A.idx deleted file mode 100644 index 5ff9752..0000000 Binary files a/.cache/clangd/index/NewPlacement.hpp.1928FAA55E835C9A.idx and /dev/null differ diff --git a/.cache/clangd/index/OBJ_Loader.h.AEBB5C46129686DA.idx b/.cache/clangd/index/OBJ_Loader.h.AEBB5C46129686DA.idx deleted file mode 100644 index 65afd08..0000000 Binary files a/.cache/clangd/index/OBJ_Loader.h.AEBB5C46129686DA.idx and /dev/null differ diff --git a/.cache/clangd/index/Parser.cpp.2E1D930D82B26F63.idx b/.cache/clangd/index/Parser.cpp.2E1D930D82B26F63.idx deleted file mode 100644 index 364e0e1..0000000 Binary files a/.cache/clangd/index/Parser.cpp.2E1D930D82B26F63.idx and /dev/null differ diff --git a/.cache/clangd/index/Parser.hpp.B83AB08A62AD32D7.idx b/.cache/clangd/index/Parser.hpp.B83AB08A62AD32D7.idx deleted file mode 100644 index e5fe4f8..0000000 Binary files a/.cache/clangd/index/Parser.hpp.B83AB08A62AD32D7.idx and /dev/null differ diff --git a/.cache/clangd/index/PoolAllocator.hpp.23E998A0EC2CF703.idx b/.cache/clangd/index/PoolAllocator.hpp.23E998A0EC2CF703.idx deleted file mode 100644 index 9c594df..0000000 Binary files a/.cache/clangd/index/PoolAllocator.hpp.23E998A0EC2CF703.idx and /dev/null differ diff --git a/.cache/clangd/index/PrivateConfig.hpp.E55D644070E96F03.idx b/.cache/clangd/index/PrivateConfig.hpp.E55D644070E96F03.idx deleted file mode 100644 index e989d48..0000000 Binary files a/.cache/clangd/index/PrivateConfig.hpp.E55D644070E96F03.idx and /dev/null differ diff --git a/.cache/clangd/index/Ray.cpp.D59F3C60683923A2.idx b/.cache/clangd/index/Ray.cpp.D59F3C60683923A2.idx deleted file mode 100644 index 8311c69..0000000 Binary files a/.cache/clangd/index/Ray.cpp.D59F3C60683923A2.idx and /dev/null differ diff --git a/.cache/clangd/index/Ray.hpp.563FF9A9C043857C.idx b/.cache/clangd/index/Ray.hpp.563FF9A9C043857C.idx deleted file mode 100644 index 87e5585..0000000 Binary files a/.cache/clangd/index/Ray.hpp.563FF9A9C043857C.idx and /dev/null differ diff --git a/.cache/clangd/index/RayTracer.cpp.706696E63CB24D27.idx b/.cache/clangd/index/RayTracer.cpp.706696E63CB24D27.idx deleted file mode 100644 index 9840df7..0000000 Binary files a/.cache/clangd/index/RayTracer.cpp.706696E63CB24D27.idx and /dev/null differ diff --git a/.cache/clangd/index/RayTracer.hpp.BA4CDB43D4BB156E.idx b/.cache/clangd/index/RayTracer.hpp.BA4CDB43D4BB156E.idx deleted file mode 100644 index 863b850..0000000 Binary files a/.cache/clangd/index/RayTracer.hpp.BA4CDB43D4BB156E.idx and /dev/null differ diff --git a/.cache/clangd/index/Rayt.cpp.99D21B87C48A33DE.idx b/.cache/clangd/index/Rayt.cpp.99D21B87C48A33DE.idx deleted file mode 100644 index 44c1c93..0000000 Binary files a/.cache/clangd/index/Rayt.cpp.99D21B87C48A33DE.idx and /dev/null differ diff --git a/.cache/clangd/index/Raytracer.cpp.EF912C6A9D068FBF.idx b/.cache/clangd/index/Raytracer.cpp.EF912C6A9D068FBF.idx deleted file mode 100644 index c4481f8..0000000 Binary files a/.cache/clangd/index/Raytracer.cpp.EF912C6A9D068FBF.idx and /dev/null differ diff --git a/.cache/clangd/index/Rect.hpp.B107009348EA0FD9.idx b/.cache/clangd/index/Rect.hpp.B107009348EA0FD9.idx deleted file mode 100644 index c9c18e2..0000000 Binary files a/.cache/clangd/index/Rect.hpp.B107009348EA0FD9.idx and /dev/null differ diff --git a/.cache/clangd/index/RegularExpression.h.C47AE408FC6B1D9A.idx b/.cache/clangd/index/RegularExpression.h.C47AE408FC6B1D9A.idx deleted file mode 100644 index c637cd1..0000000 Binary files a/.cache/clangd/index/RegularExpression.h.C47AE408FC6B1D9A.idx and /dev/null differ diff --git a/.cache/clangd/index/RemoteConnection.cpp.A6B48020816BE17E.idx b/.cache/clangd/index/RemoteConnection.cpp.A6B48020816BE17E.idx deleted file mode 100644 index 9f754d2..0000000 Binary files a/.cache/clangd/index/RemoteConnection.cpp.A6B48020816BE17E.idx and /dev/null differ diff --git a/.cache/clangd/index/RemoteConnection.hpp.FBB9BB263AFF13BF.idx b/.cache/clangd/index/RemoteConnection.hpp.FBB9BB263AFF13BF.idx deleted file mode 100644 index f5c6b88..0000000 Binary files a/.cache/clangd/index/RemoteConnection.hpp.FBB9BB263AFF13BF.idx and /dev/null differ diff --git a/.cache/clangd/index/SizeCounter.hpp.54D2437D05B502A8.idx b/.cache/clangd/index/SizeCounter.hpp.54D2437D05B502A8.idx deleted file mode 100644 index e96d3fe..0000000 Binary files a/.cache/clangd/index/SizeCounter.hpp.54D2437D05B502A8.idx and /dev/null differ diff --git a/.cache/clangd/index/StringLogic.hpp.3F8BEDBA74D82123.idx b/.cache/clangd/index/StringLogic.hpp.3F8BEDBA74D82123.idx deleted file mode 100644 index 4422847..0000000 Binary files a/.cache/clangd/index/StringLogic.hpp.3F8BEDBA74D82123.idx and /dev/null differ diff --git a/.cache/clangd/index/Strings.cpp.54FFADC03BDDB670.idx b/.cache/clangd/index/Strings.cpp.54FFADC03BDDB670.idx deleted file mode 100644 index 3abcadc..0000000 Binary files a/.cache/clangd/index/Strings.cpp.54FFADC03BDDB670.idx and /dev/null differ diff --git a/.cache/clangd/index/Strings.hpp.18245F8F37BB7C0B.idx b/.cache/clangd/index/Strings.hpp.18245F8F37BB7C0B.idx deleted file mode 100644 index a3537ad..0000000 Binary files a/.cache/clangd/index/Strings.hpp.18245F8F37BB7C0B.idx and /dev/null differ diff --git a/.cache/clangd/index/Test.cpp.4C88BCFF493D273E.idx b/.cache/clangd/index/Test.cpp.4C88BCFF493D273E.idx deleted file mode 100644 index 01a0628..0000000 Binary files a/.cache/clangd/index/Test.cpp.4C88BCFF493D273E.idx and /dev/null differ diff --git a/.cache/clangd/index/TestArchiver.cpp.578E21C75011BE9B.idx b/.cache/clangd/index/TestArchiver.cpp.578E21C75011BE9B.idx deleted file mode 100644 index eb4f00b..0000000 Binary files a/.cache/clangd/index/TestArchiver.cpp.578E21C75011BE9B.idx and /dev/null differ diff --git a/.cache/clangd/index/TestCommandLine.cpp.3ADD9246C869ABB7.idx b/.cache/clangd/index/TestCommandLine.cpp.3ADD9246C869ABB7.idx deleted file mode 100644 index 6b40380..0000000 Binary files a/.cache/clangd/index/TestCommandLine.cpp.3ADD9246C869ABB7.idx and /dev/null differ diff --git a/.cache/clangd/index/TestCommon.cpp.DBDAB8B67406BB26.idx b/.cache/clangd/index/TestCommon.cpp.DBDAB8B67406BB26.idx deleted file mode 100644 index d3a7d32..0000000 Binary files a/.cache/clangd/index/TestCommon.cpp.DBDAB8B67406BB26.idx and /dev/null differ diff --git a/.cache/clangd/index/TestCore.cpp.37D7D811CD0AB967.idx b/.cache/clangd/index/TestCore.cpp.37D7D811CD0AB967.idx deleted file mode 100644 index 84ce724..0000000 Binary files a/.cache/clangd/index/TestCore.cpp.37D7D811CD0AB967.idx and /dev/null differ diff --git a/.cache/clangd/index/TestInterpreter.cpp.3E90235A586B9084.idx b/.cache/clangd/index/TestInterpreter.cpp.3E90235A586B9084.idx deleted file mode 100644 index 894fc0c..0000000 Binary files a/.cache/clangd/index/TestInterpreter.cpp.3E90235A586B9084.idx and /dev/null differ diff --git a/.cache/clangd/index/TestInterpreter.cpp.93FD6E4F62B37135.idx b/.cache/clangd/index/TestInterpreter.cpp.93FD6E4F62B37135.idx deleted file mode 100644 index bc47beb..0000000 Binary files a/.cache/clangd/index/TestInterpreter.cpp.93FD6E4F62B37135.idx and /dev/null differ diff --git a/.cache/clangd/index/TestLocal.cpp.5EFB93EFA363372E.idx b/.cache/clangd/index/TestLocal.cpp.5EFB93EFA363372E.idx deleted file mode 100644 index a269413..0000000 Binary files a/.cache/clangd/index/TestLocal.cpp.5EFB93EFA363372E.idx and /dev/null differ diff --git a/.cache/clangd/index/TestPrimitives.cpp.B88371AF5567E4FF.idx b/.cache/clangd/index/TestPrimitives.cpp.B88371AF5567E4FF.idx deleted file mode 100644 index 2f2f4b8..0000000 Binary files a/.cache/clangd/index/TestPrimitives.cpp.B88371AF5567E4FF.idx and /dev/null differ diff --git a/.cache/clangd/index/TestTokenizer.cpp.652DA3890E3CF1B6.idx b/.cache/clangd/index/TestTokenizer.cpp.652DA3890E3CF1B6.idx deleted file mode 100644 index fb8ddfa..0000000 Binary files a/.cache/clangd/index/TestTokenizer.cpp.652DA3890E3CF1B6.idx and /dev/null differ diff --git a/.cache/clangd/index/Testing.cpp.2741C43D308DB2D7.idx b/.cache/clangd/index/Testing.cpp.2741C43D308DB2D7.idx deleted file mode 100644 index 87a2f14..0000000 Binary files a/.cache/clangd/index/Testing.cpp.2741C43D308DB2D7.idx and /dev/null differ diff --git a/.cache/clangd/index/Testing.hpp.0A1FA045E3340ECE.idx b/.cache/clangd/index/Testing.hpp.0A1FA045E3340ECE.idx deleted file mode 100644 index 692b442..0000000 Binary files a/.cache/clangd/index/Testing.hpp.0A1FA045E3340ECE.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.25A454C3BF588348.idx b/.cache/clangd/index/Tests.cpp.25A454C3BF588348.idx deleted file mode 100644 index 1a18015..0000000 Binary files a/.cache/clangd/index/Tests.cpp.25A454C3BF588348.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.31385871B2A29421.idx b/.cache/clangd/index/Tests.cpp.31385871B2A29421.idx deleted file mode 100644 index 7101f2b..0000000 Binary files a/.cache/clangd/index/Tests.cpp.31385871B2A29421.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.44665482628F6F54.idx b/.cache/clangd/index/Tests.cpp.44665482628F6F54.idx deleted file mode 100644 index e4b3a22..0000000 Binary files a/.cache/clangd/index/Tests.cpp.44665482628F6F54.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.5EA1122D7D230298.idx b/.cache/clangd/index/Tests.cpp.5EA1122D7D230298.idx deleted file mode 100644 index 89f35a7..0000000 Binary files a/.cache/clangd/index/Tests.cpp.5EA1122D7D230298.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.77F119757775AFFC.idx b/.cache/clangd/index/Tests.cpp.77F119757775AFFC.idx deleted file mode 100644 index df825c7..0000000 Binary files a/.cache/clangd/index/Tests.cpp.77F119757775AFFC.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.78F9B9075E79E71C.idx b/.cache/clangd/index/Tests.cpp.78F9B9075E79E71C.idx deleted file mode 100644 index f259ffe..0000000 Binary files a/.cache/clangd/index/Tests.cpp.78F9B9075E79E71C.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.85DB85F5BE54B30D.idx b/.cache/clangd/index/Tests.cpp.85DB85F5BE54B30D.idx deleted file mode 100644 index d547a98..0000000 Binary files a/.cache/clangd/index/Tests.cpp.85DB85F5BE54B30D.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.995B45FC5D3C16F2.idx b/.cache/clangd/index/Tests.cpp.995B45FC5D3C16F2.idx deleted file mode 100644 index 0219737..0000000 Binary files a/.cache/clangd/index/Tests.cpp.995B45FC5D3C16F2.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.CB4877B697A03867.idx b/.cache/clangd/index/Tests.cpp.CB4877B697A03867.idx deleted file mode 100644 index 106a245..0000000 Binary files a/.cache/clangd/index/Tests.cpp.CB4877B697A03867.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.cpp.F2CFB98D9B87C8BF.idx b/.cache/clangd/index/Tests.cpp.F2CFB98D9B87C8BF.idx deleted file mode 100644 index f4107d5..0000000 Binary files a/.cache/clangd/index/Tests.cpp.F2CFB98D9B87C8BF.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.hpp.43F16621F04DF189.idx b/.cache/clangd/index/Tests.hpp.43F16621F04DF189.idx deleted file mode 100644 index 70704ee..0000000 Binary files a/.cache/clangd/index/Tests.hpp.43F16621F04DF189.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.hpp.59FB719B2BA7D8F9.idx b/.cache/clangd/index/Tests.hpp.59FB719B2BA7D8F9.idx deleted file mode 100644 index f955122..0000000 Binary files a/.cache/clangd/index/Tests.hpp.59FB719B2BA7D8F9.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.hpp.70875D5FA4627A93.idx b/.cache/clangd/index/Tests.hpp.70875D5FA4627A93.idx deleted file mode 100644 index 36d8a23..0000000 Binary files a/.cache/clangd/index/Tests.hpp.70875D5FA4627A93.idx and /dev/null differ diff --git a/.cache/clangd/index/Tests.hpp.DBD412A32DBED20F.idx b/.cache/clangd/index/Tests.hpp.DBD412A32DBED20F.idx deleted file mode 100644 index aab9be9..0000000 Binary files a/.cache/clangd/index/Tests.hpp.DBD412A32DBED20F.idx and /dev/null differ diff --git a/.cache/clangd/index/TestsAll.cpp.ADC5791AD4F268D8.idx b/.cache/clangd/index/TestsAll.cpp.ADC5791AD4F268D8.idx deleted file mode 100644 index 2162d6f..0000000 Binary files a/.cache/clangd/index/TestsAll.cpp.ADC5791AD4F268D8.idx and /dev/null differ diff --git a/.cache/clangd/index/TestsLogging.cpp.FA992E71F669E2D3.idx b/.cache/clangd/index/TestsLogging.cpp.FA992E71F669E2D3.idx deleted file mode 100644 index fb0180b..0000000 Binary files a/.cache/clangd/index/TestsLogging.cpp.FA992E71F669E2D3.idx and /dev/null differ diff --git a/.cache/clangd/index/TestsStrings.cpp.AFC62CAC05389C53.idx b/.cache/clangd/index/TestsStrings.cpp.AFC62CAC05389C53.idx deleted file mode 100644 index e9d359a..0000000 Binary files a/.cache/clangd/index/TestsStrings.cpp.AFC62CAC05389C53.idx and /dev/null differ diff --git a/.cache/clangd/index/TestsStringsLogic.cpp.B04F466CDC92DEF1.idx b/.cache/clangd/index/TestsStringsLogic.cpp.B04F466CDC92DEF1.idx deleted file mode 100644 index f7295db..0000000 Binary files a/.cache/clangd/index/TestsStringsLogic.cpp.B04F466CDC92DEF1.idx and /dev/null differ diff --git a/.cache/clangd/index/Timing.cpp.F1D537CDE0293BE1.idx b/.cache/clangd/index/Timing.cpp.F1D537CDE0293BE1.idx deleted file mode 100644 index bd62543..0000000 Binary files a/.cache/clangd/index/Timing.cpp.F1D537CDE0293BE1.idx and /dev/null differ diff --git a/.cache/clangd/index/Timing.hpp.18E814EA6AE538D3.idx b/.cache/clangd/index/Timing.hpp.18E814EA6AE538D3.idx deleted file mode 100644 index 7782c19..0000000 Binary files a/.cache/clangd/index/Timing.hpp.18E814EA6AE538D3.idx and /dev/null differ diff --git a/.cache/clangd/index/Tokenizer.cpp.56DADBCB63A53785.idx b/.cache/clangd/index/Tokenizer.cpp.56DADBCB63A53785.idx deleted file mode 100644 index 28e20d3..0000000 Binary files a/.cache/clangd/index/Tokenizer.cpp.56DADBCB63A53785.idx and /dev/null differ diff --git a/.cache/clangd/index/Tokenizer.hpp.993BC8D7D2A8B17A.idx b/.cache/clangd/index/Tokenizer.hpp.993BC8D7D2A8B17A.idx deleted file mode 100644 index 0dfde75..0000000 Binary files a/.cache/clangd/index/Tokenizer.hpp.993BC8D7D2A8B17A.idx and /dev/null differ diff --git a/.cache/clangd/index/Topology.cpp.9B969A00AB31711C.idx b/.cache/clangd/index/Topology.cpp.9B969A00AB31711C.idx deleted file mode 100644 index c43f3b9..0000000 Binary files a/.cache/clangd/index/Topology.cpp.9B969A00AB31711C.idx and /dev/null differ diff --git a/.cache/clangd/index/Topology.hpp.BC7A9B19D791E2E7.idx b/.cache/clangd/index/Topology.hpp.BC7A9B19D791E2E7.idx deleted file mode 100644 index a42fc84..0000000 Binary files a/.cache/clangd/index/Topology.hpp.BC7A9B19D791E2E7.idx and /dev/null differ diff --git a/.cache/clangd/index/Tree.hpp.8605C325228A41A5.idx b/.cache/clangd/index/Tree.hpp.8605C325228A41A5.idx deleted file mode 100644 index c30ceb4..0000000 Binary files a/.cache/clangd/index/Tree.hpp.8605C325228A41A5.idx and /dev/null differ diff --git a/.cache/clangd/index/TreeTest.cpp.C4E2A11AA9312616.idx b/.cache/clangd/index/TreeTest.cpp.C4E2A11AA9312616.idx deleted file mode 100644 index 0e9ef61..0000000 Binary files a/.cache/clangd/index/TreeTest.cpp.C4E2A11AA9312616.idx and /dev/null differ diff --git a/.cache/clangd/index/Trig.cpp.EEEA5392B16F2E7B.idx b/.cache/clangd/index/Trig.cpp.EEEA5392B16F2E7B.idx deleted file mode 100644 index 60d1ffd..0000000 Binary files a/.cache/clangd/index/Trig.cpp.EEEA5392B16F2E7B.idx and /dev/null differ diff --git a/.cache/clangd/index/Trig.hpp.2E013E07A95ABC85.idx b/.cache/clangd/index/Trig.hpp.2E013E07A95ABC85.idx deleted file mode 100644 index 4a96b5c..0000000 Binary files a/.cache/clangd/index/Trig.hpp.2E013E07A95ABC85.idx and /dev/null differ diff --git a/.cache/clangd/index/TypeInfo.hpp.E38B7582B5317DEC.idx b/.cache/clangd/index/TypeInfo.hpp.E38B7582B5317DEC.idx deleted file mode 100644 index ba7cf58..0000000 Binary files a/.cache/clangd/index/TypeInfo.hpp.E38B7582B5317DEC.idx and /dev/null differ diff --git a/.cache/clangd/index/Utils.cpp.624561FA13AAF098.idx b/.cache/clangd/index/Utils.cpp.624561FA13AAF098.idx deleted file mode 100644 index 8f58372..0000000 Binary files a/.cache/clangd/index/Utils.cpp.624561FA13AAF098.idx and /dev/null differ diff --git a/.cache/clangd/index/Utils.hpp.C9BC66165C4D89DA.idx b/.cache/clangd/index/Utils.hpp.C9BC66165C4D89DA.idx deleted file mode 100644 index 4e32928..0000000 Binary files a/.cache/clangd/index/Utils.hpp.C9BC66165C4D89DA.idx and /dev/null differ diff --git a/.cache/clangd/index/Vec.hpp.448B67AA69D69345.idx b/.cache/clangd/index/Vec.hpp.448B67AA69D69345.idx deleted file mode 100644 index eb4e93d..0000000 Binary files a/.cache/clangd/index/Vec.hpp.448B67AA69D69345.idx and /dev/null differ diff --git a/.cache/clangd/index/Window.cpp.F490B88E5A33B9F0.idx b/.cache/clangd/index/Window.cpp.F490B88E5A33B9F0.idx deleted file mode 100644 index 85b2191..0000000 Binary files a/.cache/clangd/index/Window.cpp.F490B88E5A33B9F0.idx and /dev/null differ diff --git a/.cache/clangd/index/Window.hpp.AAFADCFB78B6FEC5.idx b/.cache/clangd/index/Window.hpp.AAFADCFB78B6FEC5.idx deleted file mode 100644 index f604ef2..0000000 Binary files a/.cache/clangd/index/Window.hpp.AAFADCFB78B6FEC5.idx and /dev/null differ diff --git a/.cache/clangd/index/WindowContext.hpp.34292AF37EFDA52D.idx b/.cache/clangd/index/WindowContext.hpp.34292AF37EFDA52D.idx deleted file mode 100644 index 432544d..0000000 Binary files a/.cache/clangd/index/WindowContext.hpp.34292AF37EFDA52D.idx and /dev/null differ diff --git a/.cache/clangd/index/address.hpp.3E9FEA7E9CA985B4.idx b/.cache/clangd/index/address.hpp.3E9FEA7E9CA985B4.idx deleted file mode 100644 index 08aea29..0000000 Binary files a/.cache/clangd/index/address.hpp.3E9FEA7E9CA985B4.idx and /dev/null differ diff --git a/.cache/clangd/index/address.hpp.4D3393128B99F584.idx b/.cache/clangd/index/address.hpp.4D3393128B99F584.idx deleted file mode 100644 index 85fb1e7..0000000 Binary files a/.cache/clangd/index/address.hpp.4D3393128B99F584.idx and /dev/null differ diff --git a/.cache/clangd/index/address.ipp.0D17AE53D3683CF5.idx b/.cache/clangd/index/address.ipp.0D17AE53D3683CF5.idx deleted file mode 100644 index 49dd6ef..0000000 Binary files a/.cache/clangd/index/address.ipp.0D17AE53D3683CF5.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v4.hpp.5EAE0AFC3F14E225.idx b/.cache/clangd/index/address_v4.hpp.5EAE0AFC3F14E225.idx deleted file mode 100644 index 30b9f88..0000000 Binary files a/.cache/clangd/index/address_v4.hpp.5EAE0AFC3F14E225.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v4.hpp.D3A792098D72A714.idx b/.cache/clangd/index/address_v4.hpp.D3A792098D72A714.idx deleted file mode 100644 index 5e0d575..0000000 Binary files a/.cache/clangd/index/address_v4.hpp.D3A792098D72A714.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v4.ipp.B3ECD645424909E5.idx b/.cache/clangd/index/address_v4.ipp.B3ECD645424909E5.idx deleted file mode 100644 index f245c93..0000000 Binary files a/.cache/clangd/index/address_v4.ipp.B3ECD645424909E5.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v4_iterator.hpp.1581044C28967959.idx b/.cache/clangd/index/address_v4_iterator.hpp.1581044C28967959.idx deleted file mode 100644 index 983eeac..0000000 Binary files a/.cache/clangd/index/address_v4_iterator.hpp.1581044C28967959.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v4_range.hpp.61639D3904754D54.idx b/.cache/clangd/index/address_v4_range.hpp.61639D3904754D54.idx deleted file mode 100644 index ac6e329..0000000 Binary files a/.cache/clangd/index/address_v4_range.hpp.61639D3904754D54.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v6.hpp.4CF3AB354B9F1179.idx b/.cache/clangd/index/address_v6.hpp.4CF3AB354B9F1179.idx deleted file mode 100644 index f9ab33b..0000000 Binary files a/.cache/clangd/index/address_v6.hpp.4CF3AB354B9F1179.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v6.hpp.E863876919C8EAF2.idx b/.cache/clangd/index/address_v6.hpp.E863876919C8EAF2.idx deleted file mode 100644 index 199f13d..0000000 Binary files a/.cache/clangd/index/address_v6.hpp.E863876919C8EAF2.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v6.ipp.1F0EE8FB566E69F1.idx b/.cache/clangd/index/address_v6.ipp.1F0EE8FB566E69F1.idx deleted file mode 100644 index 917e4c2..0000000 Binary files a/.cache/clangd/index/address_v6.ipp.1F0EE8FB566E69F1.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v6_iterator.hpp.8C1166F2BB6C70CF.idx b/.cache/clangd/index/address_v6_iterator.hpp.8C1166F2BB6C70CF.idx deleted file mode 100644 index bd2fb2e..0000000 Binary files a/.cache/clangd/index/address_v6_iterator.hpp.8C1166F2BB6C70CF.idx and /dev/null differ diff --git a/.cache/clangd/index/address_v6_range.hpp.1CD770F108427AC2.idx b/.cache/clangd/index/address_v6_range.hpp.1CD770F108427AC2.idx deleted file mode 100644 index 30e3e06..0000000 Binary files a/.cache/clangd/index/address_v6_range.hpp.1CD770F108427AC2.idx and /dev/null differ diff --git a/.cache/clangd/index/allocator.hpp.41619A5401B874C1.idx b/.cache/clangd/index/allocator.hpp.41619A5401B874C1.idx deleted file mode 100644 index de92613..0000000 Binary files a/.cache/clangd/index/allocator.hpp.41619A5401B874C1.idx and /dev/null differ diff --git a/.cache/clangd/index/any_completion_executor.hpp.73B38B86FA94D5CE.idx b/.cache/clangd/index/any_completion_executor.hpp.73B38B86FA94D5CE.idx deleted file mode 100644 index 0f0ee20..0000000 Binary files a/.cache/clangd/index/any_completion_executor.hpp.73B38B86FA94D5CE.idx and /dev/null differ diff --git a/.cache/clangd/index/any_completion_executor.ipp.D4A351734C3DDDCD.idx b/.cache/clangd/index/any_completion_executor.ipp.D4A351734C3DDDCD.idx deleted file mode 100644 index 6905312..0000000 Binary files a/.cache/clangd/index/any_completion_executor.ipp.D4A351734C3DDDCD.idx and /dev/null differ diff --git a/.cache/clangd/index/any_completion_handler.hpp.B185E920D241286E.idx b/.cache/clangd/index/any_completion_handler.hpp.B185E920D241286E.idx deleted file mode 100644 index 70543d5..0000000 Binary files a/.cache/clangd/index/any_completion_handler.hpp.B185E920D241286E.idx and /dev/null differ diff --git a/.cache/clangd/index/any_executor.hpp.944C296B563891A1.idx b/.cache/clangd/index/any_executor.hpp.944C296B563891A1.idx deleted file mode 100644 index b562aa2..0000000 Binary files a/.cache/clangd/index/any_executor.hpp.944C296B563891A1.idx and /dev/null differ diff --git a/.cache/clangd/index/any_io_executor.hpp.CA851B5C84A46819.idx b/.cache/clangd/index/any_io_executor.hpp.CA851B5C84A46819.idx deleted file mode 100644 index 39c2d97..0000000 Binary files a/.cache/clangd/index/any_io_executor.hpp.CA851B5C84A46819.idx and /dev/null differ diff --git a/.cache/clangd/index/any_io_executor.ipp.73A9248B844F4ED3.idx b/.cache/clangd/index/any_io_executor.ipp.73A9248B844F4ED3.idx deleted file mode 100644 index 8144b1c..0000000 Binary files a/.cache/clangd/index/any_io_executor.ipp.73A9248B844F4ED3.idx and /dev/null differ diff --git a/.cache/clangd/index/append.hpp.09CAA3F706BC3BE5.idx b/.cache/clangd/index/append.hpp.09CAA3F706BC3BE5.idx deleted file mode 100644 index 8721881..0000000 Binary files a/.cache/clangd/index/append.hpp.09CAA3F706BC3BE5.idx and /dev/null differ diff --git a/.cache/clangd/index/append.hpp.83395345C28256CB.idx b/.cache/clangd/index/append.hpp.83395345C28256CB.idx deleted file mode 100644 index 52a98db..0000000 Binary files a/.cache/clangd/index/append.hpp.83395345C28256CB.idx and /dev/null differ diff --git a/.cache/clangd/index/array.hpp.11BE7E311B3793B7.idx b/.cache/clangd/index/array.hpp.11BE7E311B3793B7.idx deleted file mode 100644 index 50f2fbf..0000000 Binary files a/.cache/clangd/index/array.hpp.11BE7E311B3793B7.idx and /dev/null differ diff --git a/.cache/clangd/index/array_fwd.hpp.4A702C703A8343FC.idx b/.cache/clangd/index/array_fwd.hpp.4A702C703A8343FC.idx deleted file mode 100644 index d67f546..0000000 Binary files a/.cache/clangd/index/array_fwd.hpp.4A702C703A8343FC.idx and /dev/null differ diff --git a/.cache/clangd/index/as_invocable.hpp.EC42BE9706B443F9.idx b/.cache/clangd/index/as_invocable.hpp.EC42BE9706B443F9.idx deleted file mode 100644 index d6c4994..0000000 Binary files a/.cache/clangd/index/as_invocable.hpp.EC42BE9706B443F9.idx and /dev/null differ diff --git a/.cache/clangd/index/as_operation.hpp.95ECC12DAF269045.idx b/.cache/clangd/index/as_operation.hpp.95ECC12DAF269045.idx deleted file mode 100644 index bc1b4da..0000000 Binary files a/.cache/clangd/index/as_operation.hpp.95ECC12DAF269045.idx and /dev/null differ diff --git a/.cache/clangd/index/as_receiver.hpp.36DDC5912833516B.idx b/.cache/clangd/index/as_receiver.hpp.36DDC5912833516B.idx deleted file mode 100644 index 99c24ad..0000000 Binary files a/.cache/clangd/index/as_receiver.hpp.36DDC5912833516B.idx and /dev/null differ diff --git a/.cache/clangd/index/as_tuple.hpp.74D183470E5D73AB.idx b/.cache/clangd/index/as_tuple.hpp.74D183470E5D73AB.idx deleted file mode 100644 index 2e074c4..0000000 Binary files a/.cache/clangd/index/as_tuple.hpp.74D183470E5D73AB.idx and /dev/null differ diff --git a/.cache/clangd/index/as_tuple.hpp.A5E3EFAF5B22709E.idx b/.cache/clangd/index/as_tuple.hpp.A5E3EFAF5B22709E.idx deleted file mode 100644 index 36705ea..0000000 Binary files a/.cache/clangd/index/as_tuple.hpp.A5E3EFAF5B22709E.idx and /dev/null differ diff --git a/.cache/clangd/index/asio.hpp.47FBD5783F11B2ED.idx b/.cache/clangd/index/asio.hpp.47FBD5783F11B2ED.idx deleted file mode 100644 index 79f1826..0000000 Binary files a/.cache/clangd/index/asio.hpp.47FBD5783F11B2ED.idx and /dev/null differ diff --git a/.cache/clangd/index/assert.hpp.14A117B8294E9EAC.idx b/.cache/clangd/index/assert.hpp.14A117B8294E9EAC.idx deleted file mode 100644 index f9cec14..0000000 Binary files a/.cache/clangd/index/assert.hpp.14A117B8294E9EAC.idx and /dev/null differ diff --git a/.cache/clangd/index/associated_allocator.hpp.38E66F3EA94382C2.idx b/.cache/clangd/index/associated_allocator.hpp.38E66F3EA94382C2.idx deleted file mode 100644 index db098bc..0000000 Binary files a/.cache/clangd/index/associated_allocator.hpp.38E66F3EA94382C2.idx and /dev/null differ diff --git a/.cache/clangd/index/associated_cancellation_slot.hpp.FE0A3E26DB563765.idx b/.cache/clangd/index/associated_cancellation_slot.hpp.FE0A3E26DB563765.idx deleted file mode 100644 index eb7d59d..0000000 Binary files a/.cache/clangd/index/associated_cancellation_slot.hpp.FE0A3E26DB563765.idx and /dev/null differ diff --git a/.cache/clangd/index/associated_executor.hpp.8338FAE0CE45B2E0.idx b/.cache/clangd/index/associated_executor.hpp.8338FAE0CE45B2E0.idx deleted file mode 100644 index f784b21..0000000 Binary files a/.cache/clangd/index/associated_executor.hpp.8338FAE0CE45B2E0.idx and /dev/null differ diff --git a/.cache/clangd/index/associated_immediate_executor.hpp.C4BB3BAAE553D421.idx b/.cache/clangd/index/associated_immediate_executor.hpp.C4BB3BAAE553D421.idx deleted file mode 100644 index 43eb256..0000000 Binary files a/.cache/clangd/index/associated_immediate_executor.hpp.C4BB3BAAE553D421.idx and /dev/null differ diff --git a/.cache/clangd/index/associator.hpp.31075968851C9EEF.idx b/.cache/clangd/index/associator.hpp.31075968851C9EEF.idx deleted file mode 100644 index 4c35020..0000000 Binary files a/.cache/clangd/index/associator.hpp.31075968851C9EEF.idx and /dev/null differ diff --git a/.cache/clangd/index/async_result.hpp.C00E6CC47BB87609.idx b/.cache/clangd/index/async_result.hpp.C00E6CC47BB87609.idx deleted file mode 100644 index 4e1ee67..0000000 Binary files a/.cache/clangd/index/async_result.hpp.C00E6CC47BB87609.idx and /dev/null differ diff --git a/.cache/clangd/index/atomic_count.hpp.8180038E75B7EC8F.idx b/.cache/clangd/index/atomic_count.hpp.8180038E75B7EC8F.idx deleted file mode 100644 index 01487dd..0000000 Binary files a/.cache/clangd/index/atomic_count.hpp.8180038E75B7EC8F.idx and /dev/null differ diff --git a/.cache/clangd/index/awaitable.hpp.361113B81CF75CC1.idx b/.cache/clangd/index/awaitable.hpp.361113B81CF75CC1.idx deleted file mode 100644 index 25775ce..0000000 Binary files a/.cache/clangd/index/awaitable.hpp.361113B81CF75CC1.idx and /dev/null differ diff --git a/.cache/clangd/index/awaitable.hpp.4CD2FD6603E2567A.idx b/.cache/clangd/index/awaitable.hpp.4CD2FD6603E2567A.idx deleted file mode 100644 index 45da7c4..0000000 Binary files a/.cache/clangd/index/awaitable.hpp.4CD2FD6603E2567A.idx and /dev/null differ diff --git a/.cache/clangd/index/bad_address_cast.hpp.C9FE34BBA0B9D56F.idx b/.cache/clangd/index/bad_address_cast.hpp.C9FE34BBA0B9D56F.idx deleted file mode 100644 index dbabb1e..0000000 Binary files a/.cache/clangd/index/bad_address_cast.hpp.C9FE34BBA0B9D56F.idx and /dev/null differ diff --git a/.cache/clangd/index/bad_executor.hpp.0B0F8191E102E3E8.idx b/.cache/clangd/index/bad_executor.hpp.0B0F8191E102E3E8.idx deleted file mode 100644 index 6bdfcf7..0000000 Binary files a/.cache/clangd/index/bad_executor.hpp.0B0F8191E102E3E8.idx and /dev/null differ diff --git a/.cache/clangd/index/bad_executor.ipp.44BFA151E0537E67.idx b/.cache/clangd/index/bad_executor.ipp.44BFA151E0537E67.idx deleted file mode 100644 index a77631c..0000000 Binary files a/.cache/clangd/index/bad_executor.ipp.44BFA151E0537E67.idx and /dev/null differ diff --git a/.cache/clangd/index/base_from_cancellation_state.hpp.D43C947FF1C6AF59.idx b/.cache/clangd/index/base_from_cancellation_state.hpp.D43C947FF1C6AF59.idx deleted file mode 100644 index 1ce523c..0000000 Binary files a/.cache/clangd/index/base_from_cancellation_state.hpp.D43C947FF1C6AF59.idx and /dev/null differ diff --git a/.cache/clangd/index/base_from_completion_cond.hpp.D879F649BA75E3F6.idx b/.cache/clangd/index/base_from_completion_cond.hpp.D879F649BA75E3F6.idx deleted file mode 100644 index 63a8b1f..0000000 Binary files a/.cache/clangd/index/base_from_completion_cond.hpp.D879F649BA75E3F6.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_datagram_socket.hpp.7C2817259B3213B5.idx b/.cache/clangd/index/basic_datagram_socket.hpp.7C2817259B3213B5.idx deleted file mode 100644 index 1211535..0000000 Binary files a/.cache/clangd/index/basic_datagram_socket.hpp.7C2817259B3213B5.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_deadline_timer.hpp.C5A3FB38580A5A85.idx b/.cache/clangd/index/basic_deadline_timer.hpp.C5A3FB38580A5A85.idx deleted file mode 100644 index 37a71e9..0000000 Binary files a/.cache/clangd/index/basic_deadline_timer.hpp.C5A3FB38580A5A85.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_descriptor.hpp.4F84C0605DC37673.idx b/.cache/clangd/index/basic_descriptor.hpp.4F84C0605DC37673.idx deleted file mode 100644 index 01711bc..0000000 Binary files a/.cache/clangd/index/basic_descriptor.hpp.4F84C0605DC37673.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_endpoint.hpp.1A531F521EDDD01B.idx b/.cache/clangd/index/basic_endpoint.hpp.1A531F521EDDD01B.idx deleted file mode 100644 index bb0930d..0000000 Binary files a/.cache/clangd/index/basic_endpoint.hpp.1A531F521EDDD01B.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_endpoint.hpp.5681975A25809E3E.idx b/.cache/clangd/index/basic_endpoint.hpp.5681975A25809E3E.idx deleted file mode 100644 index 2218809..0000000 Binary files a/.cache/clangd/index/basic_endpoint.hpp.5681975A25809E3E.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_endpoint.hpp.5D417560BDB9F461.idx b/.cache/clangd/index/basic_endpoint.hpp.5D417560BDB9F461.idx deleted file mode 100644 index 65ed27e..0000000 Binary files a/.cache/clangd/index/basic_endpoint.hpp.5D417560BDB9F461.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_endpoint.hpp.FA63C3A522CA7818.idx b/.cache/clangd/index/basic_endpoint.hpp.FA63C3A522CA7818.idx deleted file mode 100644 index de06de9..0000000 Binary files a/.cache/clangd/index/basic_endpoint.hpp.FA63C3A522CA7818.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_file.hpp.D1FFEFA5AB9B939E.idx b/.cache/clangd/index/basic_file.hpp.D1FFEFA5AB9B939E.idx deleted file mode 100644 index 9269185..0000000 Binary files a/.cache/clangd/index/basic_file.hpp.D1FFEFA5AB9B939E.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_io_object.hpp.462235C87E69808A.idx b/.cache/clangd/index/basic_io_object.hpp.462235C87E69808A.idx deleted file mode 100644 index b60a1e1..0000000 Binary files a/.cache/clangd/index/basic_io_object.hpp.462235C87E69808A.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_object_handle.hpp.C672CCDC6EE9ED29.idx b/.cache/clangd/index/basic_object_handle.hpp.C672CCDC6EE9ED29.idx deleted file mode 100644 index 3593173..0000000 Binary files a/.cache/clangd/index/basic_object_handle.hpp.C672CCDC6EE9ED29.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_overlapped_handle.hpp.5211C9A637800D53.idx b/.cache/clangd/index/basic_overlapped_handle.hpp.5211C9A637800D53.idx deleted file mode 100644 index a9a2812..0000000 Binary files a/.cache/clangd/index/basic_overlapped_handle.hpp.5211C9A637800D53.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_random_access_file.hpp.5342F7863D108757.idx b/.cache/clangd/index/basic_random_access_file.hpp.5342F7863D108757.idx deleted file mode 100644 index 4ede8b4..0000000 Binary files a/.cache/clangd/index/basic_random_access_file.hpp.5342F7863D108757.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_random_access_handle.hpp.22C6D326589E09D7.idx b/.cache/clangd/index/basic_random_access_handle.hpp.22C6D326589E09D7.idx deleted file mode 100644 index 84bf5c5..0000000 Binary files a/.cache/clangd/index/basic_random_access_handle.hpp.22C6D326589E09D7.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_raw_socket.hpp.1657008E4E4D8595.idx b/.cache/clangd/index/basic_raw_socket.hpp.1657008E4E4D8595.idx deleted file mode 100644 index 3378012..0000000 Binary files a/.cache/clangd/index/basic_raw_socket.hpp.1657008E4E4D8595.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_readable_pipe.hpp.100E1EEBB0867C81.idx b/.cache/clangd/index/basic_readable_pipe.hpp.100E1EEBB0867C81.idx deleted file mode 100644 index f07ec41..0000000 Binary files a/.cache/clangd/index/basic_readable_pipe.hpp.100E1EEBB0867C81.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_resolver.hpp.3E296D29F6E37442.idx b/.cache/clangd/index/basic_resolver.hpp.3E296D29F6E37442.idx deleted file mode 100644 index 5a97333..0000000 Binary files a/.cache/clangd/index/basic_resolver.hpp.3E296D29F6E37442.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_resolver_entry.hpp.121F4681F554FE44.idx b/.cache/clangd/index/basic_resolver_entry.hpp.121F4681F554FE44.idx deleted file mode 100644 index 7214508..0000000 Binary files a/.cache/clangd/index/basic_resolver_entry.hpp.121F4681F554FE44.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_resolver_iterator.hpp.144E507A18931A9D.idx b/.cache/clangd/index/basic_resolver_iterator.hpp.144E507A18931A9D.idx deleted file mode 100644 index 23fde18..0000000 Binary files a/.cache/clangd/index/basic_resolver_iterator.hpp.144E507A18931A9D.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_resolver_query.hpp.C2977B27F850CCE3.idx b/.cache/clangd/index/basic_resolver_query.hpp.C2977B27F850CCE3.idx deleted file mode 100644 index 014af0c..0000000 Binary files a/.cache/clangd/index/basic_resolver_query.hpp.C2977B27F850CCE3.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_resolver_results.hpp.0C8E02DCF1A4BCE7.idx b/.cache/clangd/index/basic_resolver_results.hpp.0C8E02DCF1A4BCE7.idx deleted file mode 100644 index 20e0840..0000000 Binary files a/.cache/clangd/index/basic_resolver_results.hpp.0C8E02DCF1A4BCE7.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_seq_packet_socket.hpp.42802F6F2204AB7C.idx b/.cache/clangd/index/basic_seq_packet_socket.hpp.42802F6F2204AB7C.idx deleted file mode 100644 index 6072571..0000000 Binary files a/.cache/clangd/index/basic_seq_packet_socket.hpp.42802F6F2204AB7C.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_serial_port.hpp.55745DC48A927419.idx b/.cache/clangd/index/basic_serial_port.hpp.55745DC48A927419.idx deleted file mode 100644 index fbf0178..0000000 Binary files a/.cache/clangd/index/basic_serial_port.hpp.55745DC48A927419.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_signal_set.hpp.09BE98B291267CB6.idx b/.cache/clangd/index/basic_signal_set.hpp.09BE98B291267CB6.idx deleted file mode 100644 index e3a0c03..0000000 Binary files a/.cache/clangd/index/basic_signal_set.hpp.09BE98B291267CB6.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_socket.hpp.C8B91E7D04115C4F.idx b/.cache/clangd/index/basic_socket.hpp.C8B91E7D04115C4F.idx deleted file mode 100644 index bd22f13..0000000 Binary files a/.cache/clangd/index/basic_socket.hpp.C8B91E7D04115C4F.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_socket_acceptor.hpp.178FB00F79370068.idx b/.cache/clangd/index/basic_socket_acceptor.hpp.178FB00F79370068.idx deleted file mode 100644 index 921694c..0000000 Binary files a/.cache/clangd/index/basic_socket_acceptor.hpp.178FB00F79370068.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_socket_iostream.hpp.7B919350CB87C50E.idx b/.cache/clangd/index/basic_socket_iostream.hpp.7B919350CB87C50E.idx deleted file mode 100644 index c9a63f2..0000000 Binary files a/.cache/clangd/index/basic_socket_iostream.hpp.7B919350CB87C50E.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_socket_streambuf.hpp.0CFA33ED7E6F64D3.idx b/.cache/clangd/index/basic_socket_streambuf.hpp.0CFA33ED7E6F64D3.idx deleted file mode 100644 index 4bd2244..0000000 Binary files a/.cache/clangd/index/basic_socket_streambuf.hpp.0CFA33ED7E6F64D3.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_stream_descriptor.hpp.801371792FF4F594.idx b/.cache/clangd/index/basic_stream_descriptor.hpp.801371792FF4F594.idx deleted file mode 100644 index 85aab78..0000000 Binary files a/.cache/clangd/index/basic_stream_descriptor.hpp.801371792FF4F594.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_stream_file.hpp.8D94B48B02F2C0FF.idx b/.cache/clangd/index/basic_stream_file.hpp.8D94B48B02F2C0FF.idx deleted file mode 100644 index bac186f..0000000 Binary files a/.cache/clangd/index/basic_stream_file.hpp.8D94B48B02F2C0FF.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_stream_handle.hpp.68EAECC86071E2F9.idx b/.cache/clangd/index/basic_stream_handle.hpp.68EAECC86071E2F9.idx deleted file mode 100644 index a9ec398..0000000 Binary files a/.cache/clangd/index/basic_stream_handle.hpp.68EAECC86071E2F9.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_stream_socket.hpp.C639A81F30C2567D.idx b/.cache/clangd/index/basic_stream_socket.hpp.C639A81F30C2567D.idx deleted file mode 100644 index b65aa15..0000000 Binary files a/.cache/clangd/index/basic_stream_socket.hpp.C639A81F30C2567D.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_streambuf.hpp.BF5DBAE0191BF273.idx b/.cache/clangd/index/basic_streambuf.hpp.BF5DBAE0191BF273.idx deleted file mode 100644 index fa10d33..0000000 Binary files a/.cache/clangd/index/basic_streambuf.hpp.BF5DBAE0191BF273.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_streambuf_fwd.hpp.A6808FCDE64E1742.idx b/.cache/clangd/index/basic_streambuf_fwd.hpp.A6808FCDE64E1742.idx deleted file mode 100644 index 7191df4..0000000 Binary files a/.cache/clangd/index/basic_streambuf_fwd.hpp.A6808FCDE64E1742.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_waitable_timer.hpp.35F3413445F6754E.idx b/.cache/clangd/index/basic_waitable_timer.hpp.35F3413445F6754E.idx deleted file mode 100644 index d037f09..0000000 Binary files a/.cache/clangd/index/basic_waitable_timer.hpp.35F3413445F6754E.idx and /dev/null differ diff --git a/.cache/clangd/index/basic_writable_pipe.hpp.6C8CA82D07C47846.idx b/.cache/clangd/index/basic_writable_pipe.hpp.6C8CA82D07C47846.idx deleted file mode 100644 index c425d55..0000000 Binary files a/.cache/clangd/index/basic_writable_pipe.hpp.6C8CA82D07C47846.idx and /dev/null differ diff --git a/.cache/clangd/index/bind_allocator.hpp.24F1C39F44894927.idx b/.cache/clangd/index/bind_allocator.hpp.24F1C39F44894927.idx deleted file mode 100644 index 1abaf20..0000000 Binary files a/.cache/clangd/index/bind_allocator.hpp.24F1C39F44894927.idx and /dev/null differ diff --git a/.cache/clangd/index/bind_cancellation_slot.hpp.61290C051911ED15.idx b/.cache/clangd/index/bind_cancellation_slot.hpp.61290C051911ED15.idx deleted file mode 100644 index 95cb031..0000000 Binary files a/.cache/clangd/index/bind_cancellation_slot.hpp.61290C051911ED15.idx and /dev/null differ diff --git a/.cache/clangd/index/bind_executor.hpp.D888804D761DFDCC.idx b/.cache/clangd/index/bind_executor.hpp.D888804D761DFDCC.idx deleted file mode 100644 index e055f1e..0000000 Binary files a/.cache/clangd/index/bind_executor.hpp.D888804D761DFDCC.idx and /dev/null differ diff --git a/.cache/clangd/index/bind_handler.hpp.8552216F87AB183F.idx b/.cache/clangd/index/bind_handler.hpp.8552216F87AB183F.idx deleted file mode 100644 index df108a8..0000000 Binary files a/.cache/clangd/index/bind_handler.hpp.8552216F87AB183F.idx and /dev/null differ diff --git a/.cache/clangd/index/bind_immediate_executor.hpp.A5FC53704EACF59D.idx b/.cache/clangd/index/bind_immediate_executor.hpp.A5FC53704EACF59D.idx deleted file mode 100644 index 976211c..0000000 Binary files a/.cache/clangd/index/bind_immediate_executor.hpp.A5FC53704EACF59D.idx and /dev/null differ diff --git a/.cache/clangd/index/blocking.hpp.1C8A0A8D4643936E.idx b/.cache/clangd/index/blocking.hpp.1C8A0A8D4643936E.idx deleted file mode 100644 index 4817045..0000000 Binary files a/.cache/clangd/index/blocking.hpp.1C8A0A8D4643936E.idx and /dev/null differ diff --git a/.cache/clangd/index/blocking_adaptation.hpp.9015C49C9F266914.idx b/.cache/clangd/index/blocking_adaptation.hpp.9015C49C9F266914.idx deleted file mode 100644 index a25d399..0000000 Binary files a/.cache/clangd/index/blocking_adaptation.hpp.9015C49C9F266914.idx and /dev/null differ diff --git a/.cache/clangd/index/blocking_executor_op.hpp.86A490FD617D8799.idx b/.cache/clangd/index/blocking_executor_op.hpp.86A490FD617D8799.idx deleted file mode 100644 index 2a2f83a..0000000 Binary files a/.cache/clangd/index/blocking_executor_op.hpp.86A490FD617D8799.idx and /dev/null differ diff --git a/.cache/clangd/index/boolobject.cpp.A82A6E578FE8A90E.idx b/.cache/clangd/index/boolobject.cpp.A82A6E578FE8A90E.idx deleted file mode 100644 index 4bc9742..0000000 Binary files a/.cache/clangd/index/boolobject.cpp.A82A6E578FE8A90E.idx and /dev/null differ diff --git a/.cache/clangd/index/boolobject.h.E63BB4FF9574A18C.idx b/.cache/clangd/index/boolobject.h.E63BB4FF9574A18C.idx deleted file mode 100644 index aaf0711..0000000 Binary files a/.cache/clangd/index/boolobject.h.E63BB4FF9574A18C.idx and /dev/null differ diff --git a/.cache/clangd/index/buffer.hpp.BE3679BFEB3F45CF.idx b/.cache/clangd/index/buffer.hpp.BE3679BFEB3F45CF.idx deleted file mode 100644 index 6fe5e3e..0000000 Binary files a/.cache/clangd/index/buffer.hpp.BE3679BFEB3F45CF.idx and /dev/null differ diff --git a/.cache/clangd/index/buffer_registration.hpp.995C664E6335DF81.idx b/.cache/clangd/index/buffer_registration.hpp.995C664E6335DF81.idx deleted file mode 100644 index 258b355..0000000 Binary files a/.cache/clangd/index/buffer_registration.hpp.995C664E6335DF81.idx and /dev/null differ diff --git a/.cache/clangd/index/buffer_resize_guard.hpp.B260FF5F7561A07D.idx b/.cache/clangd/index/buffer_resize_guard.hpp.B260FF5F7561A07D.idx deleted file mode 100644 index 3aeb13f..0000000 Binary files a/.cache/clangd/index/buffer_resize_guard.hpp.B260FF5F7561A07D.idx and /dev/null differ diff --git a/.cache/clangd/index/buffer_sequence_adapter.hpp.E4677C56FD1A0D67.idx b/.cache/clangd/index/buffer_sequence_adapter.hpp.E4677C56FD1A0D67.idx deleted file mode 100644 index f447203..0000000 Binary files a/.cache/clangd/index/buffer_sequence_adapter.hpp.E4677C56FD1A0D67.idx and /dev/null differ diff --git a/.cache/clangd/index/buffer_sequence_adapter.ipp.2FF8A888AC3A0DAC.idx b/.cache/clangd/index/buffer_sequence_adapter.ipp.2FF8A888AC3A0DAC.idx deleted file mode 100644 index dea21e7..0000000 Binary files a/.cache/clangd/index/buffer_sequence_adapter.ipp.2FF8A888AC3A0DAC.idx and /dev/null differ diff --git a/.cache/clangd/index/buffered_read_stream.hpp.B5B87F5EC46D5396.idx b/.cache/clangd/index/buffered_read_stream.hpp.B5B87F5EC46D5396.idx deleted file mode 100644 index f93064f..0000000 Binary files a/.cache/clangd/index/buffered_read_stream.hpp.B5B87F5EC46D5396.idx and /dev/null differ diff --git a/.cache/clangd/index/buffered_read_stream.hpp.FD2A1045FC845F86.idx b/.cache/clangd/index/buffered_read_stream.hpp.FD2A1045FC845F86.idx deleted file mode 100644 index fbff59b..0000000 Binary files a/.cache/clangd/index/buffered_read_stream.hpp.FD2A1045FC845F86.idx and /dev/null differ diff --git a/.cache/clangd/index/buffered_read_stream_fwd.hpp.404D4C946B20949A.idx b/.cache/clangd/index/buffered_read_stream_fwd.hpp.404D4C946B20949A.idx deleted file mode 100644 index 19e5bba..0000000 Binary files a/.cache/clangd/index/buffered_read_stream_fwd.hpp.404D4C946B20949A.idx and /dev/null differ diff --git a/.cache/clangd/index/buffered_stream.hpp.A8F907C6703FEA23.idx b/.cache/clangd/index/buffered_stream.hpp.A8F907C6703FEA23.idx deleted file mode 100644 index c0b71b9..0000000 Binary files a/.cache/clangd/index/buffered_stream.hpp.A8F907C6703FEA23.idx and /dev/null differ diff --git a/.cache/clangd/index/buffered_stream_fwd.hpp.F71DCD58DCECB3B9.idx b/.cache/clangd/index/buffered_stream_fwd.hpp.F71DCD58DCECB3B9.idx deleted file mode 100644 index ec8badb..0000000 Binary files a/.cache/clangd/index/buffered_stream_fwd.hpp.F71DCD58DCECB3B9.idx and /dev/null differ diff --git a/.cache/clangd/index/buffered_stream_storage.hpp.86AABE6B15C28912.idx b/.cache/clangd/index/buffered_stream_storage.hpp.86AABE6B15C28912.idx deleted file mode 100644 index 80265aa..0000000 Binary files a/.cache/clangd/index/buffered_stream_storage.hpp.86AABE6B15C28912.idx and /dev/null differ diff --git a/.cache/clangd/index/buffered_write_stream.hpp.12B4287400AFBF90.idx b/.cache/clangd/index/buffered_write_stream.hpp.12B4287400AFBF90.idx deleted file mode 100644 index be8de04..0000000 Binary files a/.cache/clangd/index/buffered_write_stream.hpp.12B4287400AFBF90.idx and /dev/null differ diff --git a/.cache/clangd/index/buffered_write_stream.hpp.89B02272B115257F.idx b/.cache/clangd/index/buffered_write_stream.hpp.89B02272B115257F.idx deleted file mode 100644 index 0e7351a..0000000 Binary files a/.cache/clangd/index/buffered_write_stream.hpp.89B02272B115257F.idx and /dev/null differ diff --git a/.cache/clangd/index/buffered_write_stream_fwd.hpp.2271054FAE9B86A6.idx b/.cache/clangd/index/buffered_write_stream_fwd.hpp.2271054FAE9B86A6.idx deleted file mode 100644 index 983a97a..0000000 Binary files a/.cache/clangd/index/buffered_write_stream_fwd.hpp.2271054FAE9B86A6.idx and /dev/null differ diff --git a/.cache/clangd/index/buffers_iterator.hpp.046598959D9FBD17.idx b/.cache/clangd/index/buffers_iterator.hpp.046598959D9FBD17.idx deleted file mode 100644 index 863f9b3..0000000 Binary files a/.cache/clangd/index/buffers_iterator.hpp.046598959D9FBD17.idx and /dev/null differ diff --git a/.cache/clangd/index/bulk_execute.hpp.1E9E38F0EB0601AE.idx b/.cache/clangd/index/bulk_execute.hpp.1E9E38F0EB0601AE.idx deleted file mode 100644 index cfc27ea..0000000 Binary files a/.cache/clangd/index/bulk_execute.hpp.1E9E38F0EB0601AE.idx and /dev/null differ diff --git a/.cache/clangd/index/bulk_execute_free.hpp.A61C4B3BCC87E3F2.idx b/.cache/clangd/index/bulk_execute_free.hpp.A61C4B3BCC87E3F2.idx deleted file mode 100644 index 1cd39d2..0000000 Binary files a/.cache/clangd/index/bulk_execute_free.hpp.A61C4B3BCC87E3F2.idx and /dev/null differ diff --git a/.cache/clangd/index/bulk_execute_member.hpp.C3E637259A3BA190.idx b/.cache/clangd/index/bulk_execute_member.hpp.C3E637259A3BA190.idx deleted file mode 100644 index 69a4ef7..0000000 Binary files a/.cache/clangd/index/bulk_execute_member.hpp.C3E637259A3BA190.idx and /dev/null differ diff --git a/.cache/clangd/index/bulk_executor_op.hpp.1ECE2131FA393773.idx b/.cache/clangd/index/bulk_executor_op.hpp.1ECE2131FA393773.idx deleted file mode 100644 index 2dbc38f..0000000 Binary files a/.cache/clangd/index/bulk_executor_op.hpp.1ECE2131FA393773.idx and /dev/null differ diff --git a/.cache/clangd/index/bulk_guarantee.hpp.867E35624EDD362A.idx b/.cache/clangd/index/bulk_guarantee.hpp.867E35624EDD362A.idx deleted file mode 100644 index 27a9012..0000000 Binary files a/.cache/clangd/index/bulk_guarantee.hpp.867E35624EDD362A.idx and /dev/null differ diff --git a/.cache/clangd/index/bulk_sender.hpp.0B4488F849F3CF8F.idx b/.cache/clangd/index/bulk_sender.hpp.0B4488F849F3CF8F.idx deleted file mode 100644 index 1113e89..0000000 Binary files a/.cache/clangd/index/bulk_sender.hpp.0B4488F849F3CF8F.idx and /dev/null differ diff --git a/.cache/clangd/index/bytecode.h.EF613C798E334774.idx b/.cache/clangd/index/bytecode.h.EF613C798E334774.idx deleted file mode 100644 index 02d1961..0000000 Binary files a/.cache/clangd/index/bytecode.h.EF613C798E334774.idx and /dev/null differ diff --git a/.cache/clangd/index/call_stack.hpp.9295F8A1A39F19FB.idx b/.cache/clangd/index/call_stack.hpp.9295F8A1A39F19FB.idx deleted file mode 100644 index 99b6fb9..0000000 Binary files a/.cache/clangd/index/call_stack.hpp.9295F8A1A39F19FB.idx and /dev/null differ diff --git a/.cache/clangd/index/callstack.cpp.7782D428D1AAE4E7.idx b/.cache/clangd/index/callstack.cpp.7782D428D1AAE4E7.idx deleted file mode 100644 index c08cbf9..0000000 Binary files a/.cache/clangd/index/callstack.cpp.7782D428D1AAE4E7.idx and /dev/null differ diff --git a/.cache/clangd/index/callstack.h.E4D8B0EB480CD311.idx b/.cache/clangd/index/callstack.h.E4D8B0EB480CD311.idx deleted file mode 100644 index c835f48..0000000 Binary files a/.cache/clangd/index/callstack.h.E4D8B0EB480CD311.idx and /dev/null differ diff --git a/.cache/clangd/index/cancellation_signal.hpp.ED059EE731B6ED58.idx b/.cache/clangd/index/cancellation_signal.hpp.ED059EE731B6ED58.idx deleted file mode 100644 index 94b388c..0000000 Binary files a/.cache/clangd/index/cancellation_signal.hpp.ED059EE731B6ED58.idx and /dev/null differ diff --git a/.cache/clangd/index/cancellation_signal.ipp.8D54FEF885A7B3FF.idx b/.cache/clangd/index/cancellation_signal.ipp.8D54FEF885A7B3FF.idx deleted file mode 100644 index 01f09e6..0000000 Binary files a/.cache/clangd/index/cancellation_signal.ipp.8D54FEF885A7B3FF.idx and /dev/null differ diff --git a/.cache/clangd/index/cancellation_state.hpp.AFE3D759B67404C4.idx b/.cache/clangd/index/cancellation_state.hpp.AFE3D759B67404C4.idx deleted file mode 100644 index 4c0c338..0000000 Binary files a/.cache/clangd/index/cancellation_state.hpp.AFE3D759B67404C4.idx and /dev/null differ diff --git a/.cache/clangd/index/cancellation_type.hpp.63FD9893F8750604.idx b/.cache/clangd/index/cancellation_type.hpp.63FD9893F8750604.idx deleted file mode 100644 index fd18087..0000000 Binary files a/.cache/clangd/index/cancellation_type.hpp.63FD9893F8750604.idx and /dev/null differ diff --git a/.cache/clangd/index/chrono.hpp.C0EA7E677B91191C.idx b/.cache/clangd/index/chrono.hpp.C0EA7E677B91191C.idx deleted file mode 100644 index 25f2bfc..0000000 Binary files a/.cache/clangd/index/chrono.hpp.C0EA7E677B91191C.idx and /dev/null differ diff --git a/.cache/clangd/index/chrono_time_traits.hpp.EC0C05B5B7B282C8.idx b/.cache/clangd/index/chrono_time_traits.hpp.EC0C05B5B7B282C8.idx deleted file mode 100644 index ebb2833..0000000 Binary files a/.cache/clangd/index/chrono_time_traits.hpp.EC0C05B5B7B282C8.idx and /dev/null differ diff --git a/.cache/clangd/index/classobject.cpp.CB1E73E40452C461.idx b/.cache/clangd/index/classobject.cpp.CB1E73E40452C461.idx deleted file mode 100644 index c432737..0000000 Binary files a/.cache/clangd/index/classobject.cpp.CB1E73E40452C461.idx and /dev/null differ diff --git a/.cache/clangd/index/classobject.h.38E83DBFF43EC0AE.idx b/.cache/clangd/index/classobject.h.38E83DBFF43EC0AE.idx deleted file mode 100644 index bb28427..0000000 Binary files a/.cache/clangd/index/classobject.h.38E83DBFF43EC0AE.idx and /dev/null differ diff --git a/.cache/clangd/index/co_spawn.hpp.11E2127C5EC62C67.idx b/.cache/clangd/index/co_spawn.hpp.11E2127C5EC62C67.idx deleted file mode 100644 index aeb4b40..0000000 Binary files a/.cache/clangd/index/co_spawn.hpp.11E2127C5EC62C67.idx and /dev/null differ diff --git a/.cache/clangd/index/co_spawn.hpp.FB14182F852907AD.idx b/.cache/clangd/index/co_spawn.hpp.FB14182F852907AD.idx deleted file mode 100644 index 5a0c65b..0000000 Binary files a/.cache/clangd/index/co_spawn.hpp.FB14182F852907AD.idx and /dev/null differ diff --git a/.cache/clangd/index/colorobject.cpp.A4EC9752984AC19C.idx b/.cache/clangd/index/colorobject.cpp.A4EC9752984AC19C.idx deleted file mode 100644 index c67b5f6..0000000 Binary files a/.cache/clangd/index/colorobject.cpp.A4EC9752984AC19C.idx and /dev/null differ diff --git a/.cache/clangd/index/colorobject.h.B16A62AC0EDE8CDB.idx b/.cache/clangd/index/colorobject.h.B16A62AC0EDE8CDB.idx deleted file mode 100644 index f164422..0000000 Binary files a/.cache/clangd/index/colorobject.h.B16A62AC0EDE8CDB.idx and /dev/null differ diff --git a/.cache/clangd/index/completion_condition.hpp.DBD5325F55FDC9C1.idx b/.cache/clangd/index/completion_condition.hpp.DBD5325F55FDC9C1.idx deleted file mode 100644 index 8c1417e..0000000 Binary files a/.cache/clangd/index/completion_condition.hpp.DBD5325F55FDC9C1.idx and /dev/null differ diff --git a/.cache/clangd/index/completion_handler.hpp.1DE9B090BA97E1B0.idx b/.cache/clangd/index/completion_handler.hpp.1DE9B090BA97E1B0.idx deleted file mode 100644 index d904a93..0000000 Binary files a/.cache/clangd/index/completion_handler.hpp.1DE9B090BA97E1B0.idx and /dev/null differ diff --git a/.cache/clangd/index/compose.hpp.694BE68652DD9E57.idx b/.cache/clangd/index/compose.hpp.694BE68652DD9E57.idx deleted file mode 100644 index 199a253..0000000 Binary files a/.cache/clangd/index/compose.hpp.694BE68652DD9E57.idx and /dev/null differ diff --git a/.cache/clangd/index/composed_work.hpp.E0A76399860780E7.idx b/.cache/clangd/index/composed_work.hpp.E0A76399860780E7.idx deleted file mode 100644 index 180c36a..0000000 Binary files a/.cache/clangd/index/composed_work.hpp.E0A76399860780E7.idx and /dev/null differ diff --git a/.cache/clangd/index/concurrency_hint.hpp.965C9B3FC4BC8A63.idx b/.cache/clangd/index/concurrency_hint.hpp.965C9B3FC4BC8A63.idx deleted file mode 100644 index d12150b..0000000 Binary files a/.cache/clangd/index/concurrency_hint.hpp.965C9B3FC4BC8A63.idx and /dev/null differ diff --git a/.cache/clangd/index/conditionally_enabled_event.hpp.74FF8FBC9B6AB260.idx b/.cache/clangd/index/conditionally_enabled_event.hpp.74FF8FBC9B6AB260.idx deleted file mode 100644 index bad6de9..0000000 Binary files a/.cache/clangd/index/conditionally_enabled_event.hpp.74FF8FBC9B6AB260.idx and /dev/null differ diff --git a/.cache/clangd/index/conditionally_enabled_mutex.hpp.AAE80E6EB56F0874.idx b/.cache/clangd/index/conditionally_enabled_mutex.hpp.AAE80E6EB56F0874.idx deleted file mode 100644 index 6f17d70..0000000 Binary files a/.cache/clangd/index/conditionally_enabled_mutex.hpp.AAE80E6EB56F0874.idx and /dev/null differ diff --git a/.cache/clangd/index/config.hpp.D793D374F13527C1.idx b/.cache/clangd/index/config.hpp.D793D374F13527C1.idx deleted file mode 100644 index 15d6f37..0000000 Binary files a/.cache/clangd/index/config.hpp.D793D374F13527C1.idx and /dev/null differ diff --git a/.cache/clangd/index/connect.hpp.0B45703239738476.idx b/.cache/clangd/index/connect.hpp.0B45703239738476.idx deleted file mode 100644 index 617f839..0000000 Binary files a/.cache/clangd/index/connect.hpp.0B45703239738476.idx and /dev/null differ diff --git a/.cache/clangd/index/connect.hpp.99B18824E3382691.idx b/.cache/clangd/index/connect.hpp.99B18824E3382691.idx deleted file mode 100644 index 0fc61b0..0000000 Binary files a/.cache/clangd/index/connect.hpp.99B18824E3382691.idx and /dev/null differ diff --git a/.cache/clangd/index/connect.hpp.EDD8917AA4DA0859.idx b/.cache/clangd/index/connect.hpp.EDD8917AA4DA0859.idx deleted file mode 100644 index e94889a..0000000 Binary files a/.cache/clangd/index/connect.hpp.EDD8917AA4DA0859.idx and /dev/null differ diff --git a/.cache/clangd/index/connect_free.hpp.E91A431C97EED12E.idx b/.cache/clangd/index/connect_free.hpp.E91A431C97EED12E.idx deleted file mode 100644 index f6ee5ea..0000000 Binary files a/.cache/clangd/index/connect_free.hpp.E91A431C97EED12E.idx and /dev/null differ diff --git a/.cache/clangd/index/connect_member.hpp.927FF975C0A2B2B9.idx b/.cache/clangd/index/connect_member.hpp.927FF975C0A2B2B9.idx deleted file mode 100644 index be4eb3a..0000000 Binary files a/.cache/clangd/index/connect_member.hpp.927FF975C0A2B2B9.idx and /dev/null differ diff --git a/.cache/clangd/index/connect_pair.hpp.6BBB1ED7946BF2CE.idx b/.cache/clangd/index/connect_pair.hpp.6BBB1ED7946BF2CE.idx deleted file mode 100644 index 22b9c6b..0000000 Binary files a/.cache/clangd/index/connect_pair.hpp.6BBB1ED7946BF2CE.idx and /dev/null differ diff --git a/.cache/clangd/index/connect_pipe.hpp.81F4B97D20A487D9.idx b/.cache/clangd/index/connect_pipe.hpp.81F4B97D20A487D9.idx deleted file mode 100644 index 8bd12e2..0000000 Binary files a/.cache/clangd/index/connect_pipe.hpp.81F4B97D20A487D9.idx and /dev/null differ diff --git a/.cache/clangd/index/connect_pipe.hpp.BF9C645C9E911CFE.idx b/.cache/clangd/index/connect_pipe.hpp.BF9C645C9E911CFE.idx deleted file mode 100644 index 553def6..0000000 Binary files a/.cache/clangd/index/connect_pipe.hpp.BF9C645C9E911CFE.idx and /dev/null differ diff --git a/.cache/clangd/index/connect_pipe.ipp.4C0C642AF2693494.idx b/.cache/clangd/index/connect_pipe.ipp.4C0C642AF2693494.idx deleted file mode 100644 index f392f31..0000000 Binary files a/.cache/clangd/index/connect_pipe.ipp.4C0C642AF2693494.idx and /dev/null differ diff --git a/.cache/clangd/index/consign.hpp.6CBACFE0F47CD166.idx b/.cache/clangd/index/consign.hpp.6CBACFE0F47CD166.idx deleted file mode 100644 index 7635600..0000000 Binary files a/.cache/clangd/index/consign.hpp.6CBACFE0F47CD166.idx and /dev/null differ diff --git a/.cache/clangd/index/consign.hpp.6D379FEC1FCC735F.idx b/.cache/clangd/index/consign.hpp.6D379FEC1FCC735F.idx deleted file mode 100644 index 843a182..0000000 Binary files a/.cache/clangd/index/consign.hpp.6D379FEC1FCC735F.idx and /dev/null differ diff --git a/.cache/clangd/index/constants.cpp.E18ADB7B115AA810.idx b/.cache/clangd/index/constants.cpp.E18ADB7B115AA810.idx deleted file mode 100644 index 95cdb54..0000000 Binary files a/.cache/clangd/index/constants.cpp.E18ADB7B115AA810.idx and /dev/null differ diff --git a/.cache/clangd/index/constants.h.273458F706A03177.idx b/.cache/clangd/index/constants.h.273458F706A03177.idx deleted file mode 100644 index a6eb011..0000000 Binary files a/.cache/clangd/index/constants.h.273458F706A03177.idx and /dev/null differ diff --git a/.cache/clangd/index/consuming_buffers.hpp.3AC1FB8614DB9AE2.idx b/.cache/clangd/index/consuming_buffers.hpp.3AC1FB8614DB9AE2.idx deleted file mode 100644 index c3f298f..0000000 Binary files a/.cache/clangd/index/consuming_buffers.hpp.3AC1FB8614DB9AE2.idx and /dev/null differ diff --git a/.cache/clangd/index/context.c.A91DD90348509010.idx b/.cache/clangd/index/context.c.A91DD90348509010.idx deleted file mode 100644 index 08c23b4..0000000 Binary files a/.cache/clangd/index/context.c.A91DD90348509010.idx and /dev/null differ diff --git a/.cache/clangd/index/context.hpp.F79A0D1856209999.idx b/.cache/clangd/index/context.hpp.F79A0D1856209999.idx deleted file mode 100644 index afd835d..0000000 Binary files a/.cache/clangd/index/context.hpp.F79A0D1856209999.idx and /dev/null differ diff --git a/.cache/clangd/index/context_as.hpp.39A21ABC05C43760.idx b/.cache/clangd/index/context_as.hpp.39A21ABC05C43760.idx deleted file mode 100644 index d051404..0000000 Binary files a/.cache/clangd/index/context_as.hpp.39A21ABC05C43760.idx and /dev/null differ diff --git a/.cache/clangd/index/coroutine.hpp.ED288021AA21BE51.idx b/.cache/clangd/index/coroutine.hpp.ED288021AA21BE51.idx deleted file mode 100644 index 488b813..0000000 Binary files a/.cache/clangd/index/coroutine.hpp.ED288021AA21BE51.idx and /dev/null differ diff --git a/.cache/clangd/index/cstddef.hpp.6DD3B5CA780BF50C.idx b/.cache/clangd/index/cstddef.hpp.6DD3B5CA780BF50C.idx deleted file mode 100644 index 83e5e6c..0000000 Binary files a/.cache/clangd/index/cstddef.hpp.6DD3B5CA780BF50C.idx and /dev/null differ diff --git a/.cache/clangd/index/cstdint.hpp.9A81DB689E3487C6.idx b/.cache/clangd/index/cstdint.hpp.9A81DB689E3487C6.idx deleted file mode 100644 index 0baa8e1..0000000 Binary files a/.cache/clangd/index/cstdint.hpp.9A81DB689E3487C6.idx and /dev/null differ diff --git a/.cache/clangd/index/datagram_protocol.hpp.94DE1F07F1F2A480.idx b/.cache/clangd/index/datagram_protocol.hpp.94DE1F07F1F2A480.idx deleted file mode 100644 index 6540f9e..0000000 Binary files a/.cache/clangd/index/datagram_protocol.hpp.94DE1F07F1F2A480.idx and /dev/null differ diff --git a/.cache/clangd/index/datagram_protocol.hpp.C7A7D510144D12F0.idx b/.cache/clangd/index/datagram_protocol.hpp.C7A7D510144D12F0.idx deleted file mode 100644 index 55b7060..0000000 Binary files a/.cache/clangd/index/datagram_protocol.hpp.C7A7D510144D12F0.idx and /dev/null differ diff --git a/.cache/clangd/index/date_time_fwd.hpp.A0A74C2F86858CEC.idx b/.cache/clangd/index/date_time_fwd.hpp.A0A74C2F86858CEC.idx deleted file mode 100644 index f1287e6..0000000 Binary files a/.cache/clangd/index/date_time_fwd.hpp.A0A74C2F86858CEC.idx and /dev/null differ diff --git a/.cache/clangd/index/deadline_timer.hpp.7152CD703F61EE8F.idx b/.cache/clangd/index/deadline_timer.hpp.7152CD703F61EE8F.idx deleted file mode 100644 index 80622c8..0000000 Binary files a/.cache/clangd/index/deadline_timer.hpp.7152CD703F61EE8F.idx and /dev/null differ diff --git a/.cache/clangd/index/deadline_timer_service.hpp.344B9F88B954F73D.idx b/.cache/clangd/index/deadline_timer_service.hpp.344B9F88B954F73D.idx deleted file mode 100644 index 5104942..0000000 Binary files a/.cache/clangd/index/deadline_timer_service.hpp.344B9F88B954F73D.idx and /dev/null differ diff --git a/.cache/clangd/index/defer.hpp.961DF5A9773C517B.idx b/.cache/clangd/index/defer.hpp.961DF5A9773C517B.idx deleted file mode 100644 index 78f1c6d..0000000 Binary files a/.cache/clangd/index/defer.hpp.961DF5A9773C517B.idx and /dev/null differ diff --git a/.cache/clangd/index/deferred.hpp.38408D0CEDE6EBE0.idx b/.cache/clangd/index/deferred.hpp.38408D0CEDE6EBE0.idx deleted file mode 100644 index 6ae0c74..0000000 Binary files a/.cache/clangd/index/deferred.hpp.38408D0CEDE6EBE0.idx and /dev/null differ diff --git a/.cache/clangd/index/deferred.hpp.9BB26542A3EA8DB8.idx b/.cache/clangd/index/deferred.hpp.9BB26542A3EA8DB8.idx deleted file mode 100644 index 19b41a8..0000000 Binary files a/.cache/clangd/index/deferred.hpp.9BB26542A3EA8DB8.idx and /dev/null differ diff --git a/.cache/clangd/index/dependent_type.hpp.E48A7A0A67774E4D.idx b/.cache/clangd/index/dependent_type.hpp.E48A7A0A67774E4D.idx deleted file mode 100644 index b45c6b8..0000000 Binary files a/.cache/clangd/index/dependent_type.hpp.E48A7A0A67774E4D.idx and /dev/null differ diff --git a/.cache/clangd/index/descriptor.hpp.D783DB267139C722.idx b/.cache/clangd/index/descriptor.hpp.D783DB267139C722.idx deleted file mode 100644 index 3c3c566..0000000 Binary files a/.cache/clangd/index/descriptor.hpp.D783DB267139C722.idx and /dev/null differ diff --git a/.cache/clangd/index/descriptor_base.hpp.CF32AE55D58EA831.idx b/.cache/clangd/index/descriptor_base.hpp.CF32AE55D58EA831.idx deleted file mode 100644 index a2a0e79..0000000 Binary files a/.cache/clangd/index/descriptor_base.hpp.CF32AE55D58EA831.idx and /dev/null differ diff --git a/.cache/clangd/index/descriptor_ops.hpp.F31D90809C712481.idx b/.cache/clangd/index/descriptor_ops.hpp.F31D90809C712481.idx deleted file mode 100644 index 79cb8af..0000000 Binary files a/.cache/clangd/index/descriptor_ops.hpp.F31D90809C712481.idx and /dev/null differ diff --git a/.cache/clangd/index/descriptor_ops.ipp.20FA64DED466C786.idx b/.cache/clangd/index/descriptor_ops.ipp.20FA64DED466C786.idx deleted file mode 100644 index c38fbc7..0000000 Binary files a/.cache/clangd/index/descriptor_ops.ipp.20FA64DED466C786.idx and /dev/null differ diff --git a/.cache/clangd/index/descriptor_read_op.hpp.55FC3C19779DB2DE.idx b/.cache/clangd/index/descriptor_read_op.hpp.55FC3C19779DB2DE.idx deleted file mode 100644 index 956b814..0000000 Binary files a/.cache/clangd/index/descriptor_read_op.hpp.55FC3C19779DB2DE.idx and /dev/null differ diff --git a/.cache/clangd/index/descriptor_write_op.hpp.CC1480F7D9CC43EC.idx b/.cache/clangd/index/descriptor_write_op.hpp.CC1480F7D9CC43EC.idx deleted file mode 100644 index bc2052b..0000000 Binary files a/.cache/clangd/index/descriptor_write_op.hpp.CC1480F7D9CC43EC.idx and /dev/null differ diff --git a/.cache/clangd/index/detached.hpp.C96914317806D0D0.idx b/.cache/clangd/index/detached.hpp.C96914317806D0D0.idx deleted file mode 100644 index cecd7bc..0000000 Binary files a/.cache/clangd/index/detached.hpp.C96914317806D0D0.idx and /dev/null differ diff --git a/.cache/clangd/index/detached.hpp.ED6782B36C79652B.idx b/.cache/clangd/index/detached.hpp.ED6782B36C79652B.idx deleted file mode 100644 index 59f7dda..0000000 Binary files a/.cache/clangd/index/detached.hpp.ED6782B36C79652B.idx and /dev/null differ diff --git a/.cache/clangd/index/dictobject.cpp.E491844243A233DA.idx b/.cache/clangd/index/dictobject.cpp.E491844243A233DA.idx deleted file mode 100644 index 86a89d5..0000000 Binary files a/.cache/clangd/index/dictobject.cpp.E491844243A233DA.idx and /dev/null differ diff --git a/.cache/clangd/index/dictobject.h.1293A29C3894F2D9.idx b/.cache/clangd/index/dictobject.h.1293A29C3894F2D9.idx deleted file mode 100644 index 349f361..0000000 Binary files a/.cache/clangd/index/dictobject.h.1293A29C3894F2D9.idx and /dev/null differ diff --git a/.cache/clangd/index/dispatch.hpp.F1FDEEFA0C39E662.idx b/.cache/clangd/index/dispatch.hpp.F1FDEEFA0C39E662.idx deleted file mode 100644 index 74cfd94..0000000 Binary files a/.cache/clangd/index/dispatch.hpp.F1FDEEFA0C39E662.idx and /dev/null differ diff --git a/.cache/clangd/index/egl_context.c.7C66A592B3435156.idx b/.cache/clangd/index/egl_context.c.7C66A592B3435156.idx deleted file mode 100644 index 3d2077d..0000000 Binary files a/.cache/clangd/index/egl_context.c.7C66A592B3435156.idx and /dev/null differ diff --git a/.cache/clangd/index/endpoint.hpp.CA3FC22C4119065B.idx b/.cache/clangd/index/endpoint.hpp.CA3FC22C4119065B.idx deleted file mode 100644 index ca4195d..0000000 Binary files a/.cache/clangd/index/endpoint.hpp.CA3FC22C4119065B.idx and /dev/null differ diff --git a/.cache/clangd/index/endpoint.hpp.FA4EDE4F3575EC3D.idx b/.cache/clangd/index/endpoint.hpp.FA4EDE4F3575EC3D.idx deleted file mode 100644 index 0788f9d..0000000 Binary files a/.cache/clangd/index/endpoint.hpp.FA4EDE4F3575EC3D.idx and /dev/null differ diff --git a/.cache/clangd/index/endpoint.hpp.FBF237E96C84A204.idx b/.cache/clangd/index/endpoint.hpp.FBF237E96C84A204.idx deleted file mode 100644 index 453f270..0000000 Binary files a/.cache/clangd/index/endpoint.hpp.FBF237E96C84A204.idx and /dev/null differ diff --git a/.cache/clangd/index/endpoint.ipp.28DECDEF0BCFFBD2.idx b/.cache/clangd/index/endpoint.ipp.28DECDEF0BCFFBD2.idx deleted file mode 100644 index eb31e3f..0000000 Binary files a/.cache/clangd/index/endpoint.ipp.28DECDEF0BCFFBD2.idx and /dev/null differ diff --git a/.cache/clangd/index/endpoint.ipp.FED89D1D9D1A0271.idx b/.cache/clangd/index/endpoint.ipp.FED89D1D9D1A0271.idx deleted file mode 100644 index 9c024db..0000000 Binary files a/.cache/clangd/index/endpoint.ipp.FED89D1D9D1A0271.idx and /dev/null differ diff --git a/.cache/clangd/index/endpoint.ipp.FFCE39E551180ED8.idx b/.cache/clangd/index/endpoint.ipp.FFCE39E551180ED8.idx deleted file mode 100644 index c0cc975..0000000 Binary files a/.cache/clangd/index/endpoint.ipp.FFCE39E551180ED8.idx and /dev/null differ diff --git a/.cache/clangd/index/enumobject.cpp.EC2F13C74E230B52.idx b/.cache/clangd/index/enumobject.cpp.EC2F13C74E230B52.idx deleted file mode 100644 index 592fa9f..0000000 Binary files a/.cache/clangd/index/enumobject.cpp.EC2F13C74E230B52.idx and /dev/null differ diff --git a/.cache/clangd/index/enumobject.h.D0C6FF836CD80A0A.idx b/.cache/clangd/index/enumobject.h.D0C6FF836CD80A0A.idx deleted file mode 100644 index f0661bc..0000000 Binary files a/.cache/clangd/index/enumobject.h.D0C6FF836CD80A0A.idx and /dev/null differ diff --git a/.cache/clangd/index/epoll_reactor.hpp.7A28B9E76CA6501A.idx b/.cache/clangd/index/epoll_reactor.hpp.7A28B9E76CA6501A.idx deleted file mode 100644 index 631cc53..0000000 Binary files a/.cache/clangd/index/epoll_reactor.hpp.7A28B9E76CA6501A.idx and /dev/null differ diff --git a/.cache/clangd/index/epoll_reactor.hpp.BF29AC3F19345017.idx b/.cache/clangd/index/epoll_reactor.hpp.BF29AC3F19345017.idx deleted file mode 100644 index c32e54d..0000000 Binary files a/.cache/clangd/index/epoll_reactor.hpp.BF29AC3F19345017.idx and /dev/null differ diff --git a/.cache/clangd/index/epoll_reactor.ipp.BE35BF2AAA1D0F3E.idx b/.cache/clangd/index/epoll_reactor.ipp.BE35BF2AAA1D0F3E.idx deleted file mode 100644 index e82452a..0000000 Binary files a/.cache/clangd/index/epoll_reactor.ipp.BE35BF2AAA1D0F3E.idx and /dev/null differ diff --git a/.cache/clangd/index/equality_comparable.hpp.2486F1A673357246.idx b/.cache/clangd/index/equality_comparable.hpp.2486F1A673357246.idx deleted file mode 100644 index 83beabb..0000000 Binary files a/.cache/clangd/index/equality_comparable.hpp.2486F1A673357246.idx and /dev/null differ diff --git a/.cache/clangd/index/error.hpp.55614401376C8406.idx b/.cache/clangd/index/error.hpp.55614401376C8406.idx deleted file mode 100644 index d059f10..0000000 Binary files a/.cache/clangd/index/error.hpp.55614401376C8406.idx and /dev/null differ diff --git a/.cache/clangd/index/error.ipp.E053731571C87824.idx b/.cache/clangd/index/error.ipp.E053731571C87824.idx deleted file mode 100644 index dbbee2d..0000000 Binary files a/.cache/clangd/index/error.ipp.E053731571C87824.idx and /dev/null differ diff --git a/.cache/clangd/index/error_code.hpp.B7D29D71D5FB1316.idx b/.cache/clangd/index/error_code.hpp.B7D29D71D5FB1316.idx deleted file mode 100644 index 650a51a..0000000 Binary files a/.cache/clangd/index/error_code.hpp.B7D29D71D5FB1316.idx and /dev/null differ diff --git a/.cache/clangd/index/error_code.ipp.48134E77BCD27358.idx b/.cache/clangd/index/error_code.ipp.48134E77BCD27358.idx deleted file mode 100644 index ec22082..0000000 Binary files a/.cache/clangd/index/error_code.ipp.48134E77BCD27358.idx and /dev/null differ diff --git a/.cache/clangd/index/event.hpp.0BFF540C2AF625E3.idx b/.cache/clangd/index/event.hpp.0BFF540C2AF625E3.idx deleted file mode 100644 index b4ae827..0000000 Binary files a/.cache/clangd/index/event.hpp.0BFF540C2AF625E3.idx and /dev/null differ diff --git a/.cache/clangd/index/eventfd_select_interrupter.hpp.F0DC0E411F727C15.idx b/.cache/clangd/index/eventfd_select_interrupter.hpp.F0DC0E411F727C15.idx deleted file mode 100644 index 6a52504..0000000 Binary files a/.cache/clangd/index/eventfd_select_interrupter.hpp.F0DC0E411F727C15.idx and /dev/null differ diff --git a/.cache/clangd/index/eventfd_select_interrupter.ipp.FE86E59B6A47701E.idx b/.cache/clangd/index/eventfd_select_interrupter.ipp.FE86E59B6A47701E.idx deleted file mode 100644 index 6ecf348..0000000 Binary files a/.cache/clangd/index/eventfd_select_interrupter.ipp.FE86E59B6A47701E.idx and /dev/null differ diff --git a/.cache/clangd/index/execute.hpp.BAC0C07BC1FCE513.idx b/.cache/clangd/index/execute.hpp.BAC0C07BC1FCE513.idx deleted file mode 100644 index 29a57c5..0000000 Binary files a/.cache/clangd/index/execute.hpp.BAC0C07BC1FCE513.idx and /dev/null differ diff --git a/.cache/clangd/index/execute_free.hpp.BEDDA1A53EC1FD8C.idx b/.cache/clangd/index/execute_free.hpp.BEDDA1A53EC1FD8C.idx deleted file mode 100644 index a69a89c..0000000 Binary files a/.cache/clangd/index/execute_free.hpp.BEDDA1A53EC1FD8C.idx and /dev/null differ diff --git a/.cache/clangd/index/execute_member.hpp.FF25DD1F78C7D2CC.idx b/.cache/clangd/index/execute_member.hpp.FF25DD1F78C7D2CC.idx deleted file mode 100644 index 552a183..0000000 Binary files a/.cache/clangd/index/execute_member.hpp.FF25DD1F78C7D2CC.idx and /dev/null differ diff --git a/.cache/clangd/index/execution.hpp.2F953B16981D0D6D.idx b/.cache/clangd/index/execution.hpp.2F953B16981D0D6D.idx deleted file mode 100644 index 7b6abdc..0000000 Binary files a/.cache/clangd/index/execution.hpp.2F953B16981D0D6D.idx and /dev/null differ diff --git a/.cache/clangd/index/execution_context.hpp.65E0E4224BCB84FB.idx b/.cache/clangd/index/execution_context.hpp.65E0E4224BCB84FB.idx deleted file mode 100644 index a936291..0000000 Binary files a/.cache/clangd/index/execution_context.hpp.65E0E4224BCB84FB.idx and /dev/null differ diff --git a/.cache/clangd/index/execution_context.hpp.EDE5AFA9A53E636A.idx b/.cache/clangd/index/execution_context.hpp.EDE5AFA9A53E636A.idx deleted file mode 100644 index f5e3223..0000000 Binary files a/.cache/clangd/index/execution_context.hpp.EDE5AFA9A53E636A.idx and /dev/null differ diff --git a/.cache/clangd/index/execution_context.ipp.C06CD3A163ED728F.idx b/.cache/clangd/index/execution_context.ipp.C06CD3A163ED728F.idx deleted file mode 100644 index 84968b9..0000000 Binary files a/.cache/clangd/index/execution_context.ipp.C06CD3A163ED728F.idx and /dev/null differ diff --git a/.cache/clangd/index/executor.hpp.46476B7A0D9915B7.idx b/.cache/clangd/index/executor.hpp.46476B7A0D9915B7.idx deleted file mode 100644 index 53d8c45..0000000 Binary files a/.cache/clangd/index/executor.hpp.46476B7A0D9915B7.idx and /dev/null differ diff --git a/.cache/clangd/index/executor.hpp.5D36958A2256A470.idx b/.cache/clangd/index/executor.hpp.5D36958A2256A470.idx deleted file mode 100644 index 91ae92f..0000000 Binary files a/.cache/clangd/index/executor.hpp.5D36958A2256A470.idx and /dev/null differ diff --git a/.cache/clangd/index/executor.hpp.DFFDCAEFF9B55B9E.idx b/.cache/clangd/index/executor.hpp.DFFDCAEFF9B55B9E.idx deleted file mode 100644 index f449bde..0000000 Binary files a/.cache/clangd/index/executor.hpp.DFFDCAEFF9B55B9E.idx and /dev/null differ diff --git a/.cache/clangd/index/executor.ipp.C472226F07B9A26C.idx b/.cache/clangd/index/executor.ipp.C472226F07B9A26C.idx deleted file mode 100644 index 3f0f879..0000000 Binary files a/.cache/clangd/index/executor.ipp.C472226F07B9A26C.idx and /dev/null differ diff --git a/.cache/clangd/index/executor_function.hpp.FFDA674A0E0685AE.idx b/.cache/clangd/index/executor_function.hpp.FFDA674A0E0685AE.idx deleted file mode 100644 index ce345e5..0000000 Binary files a/.cache/clangd/index/executor_function.hpp.FFDA674A0E0685AE.idx and /dev/null differ diff --git a/.cache/clangd/index/executor_op.hpp.178056310CEEE7E6.idx b/.cache/clangd/index/executor_op.hpp.178056310CEEE7E6.idx deleted file mode 100644 index df3caf3..0000000 Binary files a/.cache/clangd/index/executor_op.hpp.178056310CEEE7E6.idx and /dev/null differ diff --git a/.cache/clangd/index/executor_work_guard.hpp.28DB064B7B7351A0.idx b/.cache/clangd/index/executor_work_guard.hpp.28DB064B7B7351A0.idx deleted file mode 100644 index 5de29db..0000000 Binary files a/.cache/clangd/index/executor_work_guard.hpp.28DB064B7B7351A0.idx and /dev/null differ diff --git a/.cache/clangd/index/expression.cpp.4A5999781636F030.idx b/.cache/clangd/index/expression.cpp.4A5999781636F030.idx deleted file mode 100644 index 10d5cff..0000000 Binary files a/.cache/clangd/index/expression.cpp.4A5999781636F030.idx and /dev/null differ diff --git a/.cache/clangd/index/expression.h.93E8D40F85C343AC.idx b/.cache/clangd/index/expression.h.93E8D40F85C343AC.idx deleted file mode 100644 index ea3ba4a..0000000 Binary files a/.cache/clangd/index/expression.h.93E8D40F85C343AC.idx and /dev/null differ diff --git a/.cache/clangd/index/fenced_block.hpp.E0C431296F8BB1BC.idx b/.cache/clangd/index/fenced_block.hpp.E0C431296F8BB1BC.idx deleted file mode 100644 index 6bdab89..0000000 Binary files a/.cache/clangd/index/fenced_block.hpp.E0C431296F8BB1BC.idx and /dev/null differ diff --git a/.cache/clangd/index/file_base.hpp.42B6792C95A7EAA7.idx b/.cache/clangd/index/file_base.hpp.42B6792C95A7EAA7.idx deleted file mode 100644 index bc5a184..0000000 Binary files a/.cache/clangd/index/file_base.hpp.42B6792C95A7EAA7.idx and /dev/null differ diff --git a/.cache/clangd/index/floatobject.cpp.5C01EBA34E49739D.idx b/.cache/clangd/index/floatobject.cpp.5C01EBA34E49739D.idx deleted file mode 100644 index 48d3363..0000000 Binary files a/.cache/clangd/index/floatobject.cpp.5C01EBA34E49739D.idx and /dev/null differ diff --git a/.cache/clangd/index/floatobject.h.F18B2FF416EAB2DE.idx b/.cache/clangd/index/floatobject.h.F18B2FF416EAB2DE.idx deleted file mode 100644 index 764bc90..0000000 Binary files a/.cache/clangd/index/floatobject.h.F18B2FF416EAB2DE.idx and /dev/null differ diff --git a/.cache/clangd/index/fontstash.h.3EFE0EB5BBDD0951.idx b/.cache/clangd/index/fontstash.h.3EFE0EB5BBDD0951.idx deleted file mode 100644 index 5fc53c4..0000000 Binary files a/.cache/clangd/index/fontstash.h.3EFE0EB5BBDD0951.idx and /dev/null differ diff --git a/.cache/clangd/index/function.cpp.54E814C19908B2C7.idx b/.cache/clangd/index/function.cpp.54E814C19908B2C7.idx deleted file mode 100644 index 2f14ee6..0000000 Binary files a/.cache/clangd/index/function.cpp.54E814C19908B2C7.idx and /dev/null differ diff --git a/.cache/clangd/index/function.h.C6AE8BD1A71287DE.idx b/.cache/clangd/index/function.h.C6AE8BD1A71287DE.idx deleted file mode 100644 index 6c1bad7..0000000 Binary files a/.cache/clangd/index/function.h.C6AE8BD1A71287DE.idx and /dev/null differ diff --git a/.cache/clangd/index/functional.hpp.7F4A3A52693C7D23.idx b/.cache/clangd/index/functional.hpp.7F4A3A52693C7D23.idx deleted file mode 100644 index f30f0ea..0000000 Binary files a/.cache/clangd/index/functional.hpp.7F4A3A52693C7D23.idx and /dev/null differ diff --git a/.cache/clangd/index/future.hpp.E952F1DCCBE21FB8.idx b/.cache/clangd/index/future.hpp.E952F1DCCBE21FB8.idx deleted file mode 100644 index 56eadb6..0000000 Binary files a/.cache/clangd/index/future.hpp.E952F1DCCBE21FB8.idx and /dev/null differ diff --git a/.cache/clangd/index/glew.c.174F3D308103FC14.idx b/.cache/clangd/index/glew.c.174F3D308103FC14.idx deleted file mode 100644 index 77bd264..0000000 Binary files a/.cache/clangd/index/glew.c.174F3D308103FC14.idx and /dev/null differ diff --git a/.cache/clangd/index/glew.h.63A43253758605C9.idx b/.cache/clangd/index/glew.h.63A43253758605C9.idx deleted file mode 100644 index 21b4b83..0000000 Binary files a/.cache/clangd/index/glew.h.63A43253758605C9.idx and /dev/null differ diff --git a/.cache/clangd/index/glewinfo.c.15F3617CF6420CC8.idx b/.cache/clangd/index/glewinfo.c.15F3617CF6420CC8.idx deleted file mode 100644 index 1f88a15..0000000 Binary files a/.cache/clangd/index/glewinfo.c.15F3617CF6420CC8.idx and /dev/null differ diff --git a/.cache/clangd/index/glfw3.h.03A53DB3B7D4D44A.idx b/.cache/clangd/index/glfw3.h.03A53DB3B7D4D44A.idx deleted file mode 100644 index c0fb07d..0000000 Binary files a/.cache/clangd/index/glfw3.h.03A53DB3B7D4D44A.idx and /dev/null differ diff --git a/.cache/clangd/index/global.hpp.789D5D14A3DE7E7E.idx b/.cache/clangd/index/global.hpp.789D5D14A3DE7E7E.idx deleted file mode 100644 index fe99fa7..0000000 Binary files a/.cache/clangd/index/global.hpp.789D5D14A3DE7E7E.idx and /dev/null differ diff --git a/.cache/clangd/index/glx_context.c.959200A8E8FFD131.idx b/.cache/clangd/index/glx_context.c.959200A8E8FFD131.idx deleted file mode 100644 index 0f57048..0000000 Binary files a/.cache/clangd/index/glx_context.c.959200A8E8FFD131.idx and /dev/null differ diff --git a/.cache/clangd/index/glxew.h.22AC3F51DC419748.idx b/.cache/clangd/index/glxew.h.22AC3F51DC419748.idx deleted file mode 100644 index 6d0e056..0000000 Binary files a/.cache/clangd/index/glxew.h.22AC3F51DC419748.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_alloc_helpers.hpp.B987BF726BFE346B.idx b/.cache/clangd/index/handler_alloc_helpers.hpp.B987BF726BFE346B.idx deleted file mode 100644 index 460598e..0000000 Binary files a/.cache/clangd/index/handler_alloc_helpers.hpp.B987BF726BFE346B.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_alloc_hook.hpp.9F0E5DEECB33780B.idx b/.cache/clangd/index/handler_alloc_hook.hpp.9F0E5DEECB33780B.idx deleted file mode 100644 index 72f08cb..0000000 Binary files a/.cache/clangd/index/handler_alloc_hook.hpp.9F0E5DEECB33780B.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_alloc_hook.ipp.FDB27899494A8DB9.idx b/.cache/clangd/index/handler_alloc_hook.ipp.FDB27899494A8DB9.idx deleted file mode 100644 index 2ee00c6..0000000 Binary files a/.cache/clangd/index/handler_alloc_hook.ipp.FDB27899494A8DB9.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_cont_helpers.hpp.13638422D33AF902.idx b/.cache/clangd/index/handler_cont_helpers.hpp.13638422D33AF902.idx deleted file mode 100644 index 67963e9..0000000 Binary files a/.cache/clangd/index/handler_cont_helpers.hpp.13638422D33AF902.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_continuation_hook.hpp.9D85344757384480.idx b/.cache/clangd/index/handler_continuation_hook.hpp.9D85344757384480.idx deleted file mode 100644 index 674c891..0000000 Binary files a/.cache/clangd/index/handler_continuation_hook.hpp.9D85344757384480.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_invoke_helpers.hpp.AC47703D46439BF4.idx b/.cache/clangd/index/handler_invoke_helpers.hpp.AC47703D46439BF4.idx deleted file mode 100644 index a583143..0000000 Binary files a/.cache/clangd/index/handler_invoke_helpers.hpp.AC47703D46439BF4.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_invoke_hook.hpp.360F03D78BD6E026.idx b/.cache/clangd/index/handler_invoke_hook.hpp.360F03D78BD6E026.idx deleted file mode 100644 index 14f30e5..0000000 Binary files a/.cache/clangd/index/handler_invoke_hook.hpp.360F03D78BD6E026.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_tracking.hpp.EBBF06A044B6C1EA.idx b/.cache/clangd/index/handler_tracking.hpp.EBBF06A044B6C1EA.idx deleted file mode 100644 index 908d539..0000000 Binary files a/.cache/clangd/index/handler_tracking.hpp.EBBF06A044B6C1EA.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_tracking.ipp.7FF2B2179B96FC5A.idx b/.cache/clangd/index/handler_tracking.ipp.7FF2B2179B96FC5A.idx deleted file mode 100644 index 9b288cd..0000000 Binary files a/.cache/clangd/index/handler_tracking.ipp.7FF2B2179B96FC5A.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_type_requirements.hpp.76200875F37A160E.idx b/.cache/clangd/index/handler_type_requirements.hpp.76200875F37A160E.idx deleted file mode 100644 index f609dbc..0000000 Binary files a/.cache/clangd/index/handler_type_requirements.hpp.76200875F37A160E.idx and /dev/null differ diff --git a/.cache/clangd/index/handler_work.hpp.1AFF7B4AB91B7585.idx b/.cache/clangd/index/handler_work.hpp.1AFF7B4AB91B7585.idx deleted file mode 100644 index 2316889..0000000 Binary files a/.cache/clangd/index/handler_work.hpp.1AFF7B4AB91B7585.idx and /dev/null differ diff --git a/.cache/clangd/index/high_resolution_timer.hpp.1DD1A8037608ACD1.idx b/.cache/clangd/index/high_resolution_timer.hpp.1DD1A8037608ACD1.idx deleted file mode 100644 index 5ef0e38..0000000 Binary files a/.cache/clangd/index/high_resolution_timer.hpp.1DD1A8037608ACD1.idx and /dev/null differ diff --git a/.cache/clangd/index/host_name.hpp.F3CE022939F77A8A.idx b/.cache/clangd/index/host_name.hpp.F3CE022939F77A8A.idx deleted file mode 100644 index 65a5cd7..0000000 Binary files a/.cache/clangd/index/host_name.hpp.F3CE022939F77A8A.idx and /dev/null differ diff --git a/.cache/clangd/index/host_name.ipp.C26D9554D6EAB59C.idx b/.cache/clangd/index/host_name.ipp.C26D9554D6EAB59C.idx deleted file mode 100644 index 710d90c..0000000 Binary files a/.cache/clangd/index/host_name.ipp.C26D9554D6EAB59C.idx and /dev/null differ diff --git a/.cache/clangd/index/icmp.hpp.D4B5328F72423E8E.idx b/.cache/clangd/index/icmp.hpp.D4B5328F72423E8E.idx deleted file mode 100644 index fff8598..0000000 Binary files a/.cache/clangd/index/icmp.hpp.D4B5328F72423E8E.idx and /dev/null differ diff --git a/.cache/clangd/index/imconfig.h.E9519912E0B8E7EE.idx b/.cache/clangd/index/imconfig.h.E9519912E0B8E7EE.idx deleted file mode 100644 index 6903525..0000000 Binary files a/.cache/clangd/index/imconfig.h.E9519912E0B8E7EE.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui.cpp.1E517C9A6C590000.idx b/.cache/clangd/index/imgui.cpp.1E517C9A6C590000.idx deleted file mode 100644 index b404762..0000000 Binary files a/.cache/clangd/index/imgui.cpp.1E517C9A6C590000.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui.h.D4500CAC88CB5604.idx b/.cache/clangd/index/imgui.h.D4500CAC88CB5604.idx deleted file mode 100644 index 7cb44e8..0000000 Binary files a/.cache/clangd/index/imgui.h.D4500CAC88CB5604.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui_draw.cpp.7237740F19661BD7.idx b/.cache/clangd/index/imgui_draw.cpp.7237740F19661BD7.idx deleted file mode 100644 index 07bb8c1..0000000 Binary files a/.cache/clangd/index/imgui_draw.cpp.7237740F19661BD7.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui_impl_glfw.cpp.4DD50F89E465FFF6.idx b/.cache/clangd/index/imgui_impl_glfw.cpp.4DD50F89E465FFF6.idx deleted file mode 100644 index 4d4f576..0000000 Binary files a/.cache/clangd/index/imgui_impl_glfw.cpp.4DD50F89E465FFF6.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui_impl_glfw.h.A00E7AA3E6A2EC63.idx b/.cache/clangd/index/imgui_impl_glfw.h.A00E7AA3E6A2EC63.idx deleted file mode 100644 index c8536e0..0000000 Binary files a/.cache/clangd/index/imgui_impl_glfw.h.A00E7AA3E6A2EC63.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui_impl_opengl3.cpp.33BDD2DF7E23B615.idx b/.cache/clangd/index/imgui_impl_opengl3.cpp.33BDD2DF7E23B615.idx deleted file mode 100644 index e0e5880..0000000 Binary files a/.cache/clangd/index/imgui_impl_opengl3.cpp.33BDD2DF7E23B615.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui_impl_opengl3.h.CEECAD52C8CD27B9.idx b/.cache/clangd/index/imgui_impl_opengl3.h.CEECAD52C8CD27B9.idx deleted file mode 100644 index 8001254..0000000 Binary files a/.cache/clangd/index/imgui_impl_opengl3.h.CEECAD52C8CD27B9.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui_impl_opengl3_loader.h.8B437C8215C2D0B2.idx b/.cache/clangd/index/imgui_impl_opengl3_loader.h.8B437C8215C2D0B2.idx deleted file mode 100644 index ef68742..0000000 Binary files a/.cache/clangd/index/imgui_impl_opengl3_loader.h.8B437C8215C2D0B2.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui_internal.h.FDAAE7C28D94AB51.idx b/.cache/clangd/index/imgui_internal.h.FDAAE7C28D94AB51.idx deleted file mode 100644 index f2b2111..0000000 Binary files a/.cache/clangd/index/imgui_internal.h.FDAAE7C28D94AB51.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui_tables.cpp.D80F79740ABFC443.idx b/.cache/clangd/index/imgui_tables.cpp.D80F79740ABFC443.idx deleted file mode 100644 index ab5ae03..0000000 Binary files a/.cache/clangd/index/imgui_tables.cpp.D80F79740ABFC443.idx and /dev/null differ diff --git a/.cache/clangd/index/imgui_widgets.cpp.C8061931B9D3C7F1.idx b/.cache/clangd/index/imgui_widgets.cpp.C8061931B9D3C7F1.idx deleted file mode 100644 index 86c172f..0000000 Binary files a/.cache/clangd/index/imgui_widgets.cpp.C8061931B9D3C7F1.idx and /dev/null differ diff --git a/.cache/clangd/index/imstb_rectpack.h.821CB0183867613A.idx b/.cache/clangd/index/imstb_rectpack.h.821CB0183867613A.idx deleted file mode 100644 index 28bfa89..0000000 Binary files a/.cache/clangd/index/imstb_rectpack.h.821CB0183867613A.idx and /dev/null differ diff --git a/.cache/clangd/index/imstb_textedit.h.31F7BDD393CD1DE0.idx b/.cache/clangd/index/imstb_textedit.h.31F7BDD393CD1DE0.idx deleted file mode 100644 index a200b8b..0000000 Binary files a/.cache/clangd/index/imstb_textedit.h.31F7BDD393CD1DE0.idx and /dev/null differ diff --git a/.cache/clangd/index/imstb_truetype.h.3A8376510F52C7AD.idx b/.cache/clangd/index/imstb_truetype.h.3A8376510F52C7AD.idx deleted file mode 100644 index 117e966..0000000 Binary files a/.cache/clangd/index/imstb_truetype.h.3A8376510F52C7AD.idx and /dev/null differ diff --git a/.cache/clangd/index/init.c.340166C52FF8F762.idx b/.cache/clangd/index/init.c.340166C52FF8F762.idx deleted file mode 100644 index b298a89..0000000 Binary files a/.cache/clangd/index/init.c.340166C52FF8F762.idx and /dev/null differ diff --git a/.cache/clangd/index/initiate_defer.hpp.545650BE6036F429.idx b/.cache/clangd/index/initiate_defer.hpp.545650BE6036F429.idx deleted file mode 100644 index 6f77c10..0000000 Binary files a/.cache/clangd/index/initiate_defer.hpp.545650BE6036F429.idx and /dev/null differ diff --git a/.cache/clangd/index/initiate_dispatch.hpp.B191C11D6ECDA034.idx b/.cache/clangd/index/initiate_dispatch.hpp.B191C11D6ECDA034.idx deleted file mode 100644 index fded3ae..0000000 Binary files a/.cache/clangd/index/initiate_dispatch.hpp.B191C11D6ECDA034.idx and /dev/null differ diff --git a/.cache/clangd/index/initiate_post.hpp.110F1D8EBFE3CB1C.idx b/.cache/clangd/index/initiate_post.hpp.110F1D8EBFE3CB1C.idx deleted file mode 100644 index 67ca85a..0000000 Binary files a/.cache/clangd/index/initiate_post.hpp.110F1D8EBFE3CB1C.idx and /dev/null differ diff --git a/.cache/clangd/index/input.c.D318104A3967CF4B.idx b/.cache/clangd/index/input.c.D318104A3967CF4B.idx deleted file mode 100644 index e1f5bb9..0000000 Binary files a/.cache/clangd/index/input.c.D318104A3967CF4B.idx and /dev/null differ diff --git a/.cache/clangd/index/instruction.cpp.C0916F6DB73A748E.idx b/.cache/clangd/index/instruction.cpp.C0916F6DB73A748E.idx deleted file mode 100644 index 0603754..0000000 Binary files a/.cache/clangd/index/instruction.cpp.C0916F6DB73A748E.idx and /dev/null differ diff --git a/.cache/clangd/index/instruction.h.E155EE8564E3B6F8.idx b/.cache/clangd/index/instruction.h.E155EE8564E3B6F8.idx deleted file mode 100644 index 23bd06e..0000000 Binary files a/.cache/clangd/index/instruction.h.E155EE8564E3B6F8.idx and /dev/null differ diff --git a/.cache/clangd/index/internal.h.39B0C6F39B39A8DF.idx b/.cache/clangd/index/internal.h.39B0C6F39B39A8DF.idx deleted file mode 100644 index b7a34af..0000000 Binary files a/.cache/clangd/index/internal.h.39B0C6F39B39A8DF.idx and /dev/null differ diff --git a/.cache/clangd/index/interpreter.cpp.8DD67C8078A5F329.idx b/.cache/clangd/index/interpreter.cpp.8DD67C8078A5F329.idx deleted file mode 100644 index 8d36ac2..0000000 Binary files a/.cache/clangd/index/interpreter.cpp.8DD67C8078A5F329.idx and /dev/null differ diff --git a/.cache/clangd/index/interpreter.h.19113160F97DA8AB.idx b/.cache/clangd/index/interpreter.h.19113160F97DA8AB.idx deleted file mode 100644 index ea71947..0000000 Binary files a/.cache/clangd/index/interpreter.h.19113160F97DA8AB.idx and /dev/null differ diff --git a/.cache/clangd/index/interpreterobject.cpp.96BFC88D0DA2C6B1.idx b/.cache/clangd/index/interpreterobject.cpp.96BFC88D0DA2C6B1.idx deleted file mode 100644 index 6bfccb3..0000000 Binary files a/.cache/clangd/index/interpreterobject.cpp.96BFC88D0DA2C6B1.idx and /dev/null differ diff --git a/.cache/clangd/index/interpreterobject.h.9A2D68CA2B809D60.idx b/.cache/clangd/index/interpreterobject.h.9A2D68CA2B809D60.idx deleted file mode 100644 index f63c46e..0000000 Binary files a/.cache/clangd/index/interpreterobject.h.9A2D68CA2B809D60.idx and /dev/null differ diff --git a/.cache/clangd/index/intobject.cpp.0E8667B74503ACF5.idx b/.cache/clangd/index/intobject.cpp.0E8667B74503ACF5.idx deleted file mode 100644 index 5f9adc8..0000000 Binary files a/.cache/clangd/index/intobject.cpp.0E8667B74503ACF5.idx and /dev/null differ diff --git a/.cache/clangd/index/intobject.h.CE1336062D9BA15D.idx b/.cache/clangd/index/intobject.h.CE1336062D9BA15D.idx deleted file mode 100644 index 874185e..0000000 Binary files a/.cache/clangd/index/intobject.h.CE1336062D9BA15D.idx and /dev/null differ diff --git a/.cache/clangd/index/invocable_archetype.hpp.169B926EF5696C76.idx b/.cache/clangd/index/invocable_archetype.hpp.169B926EF5696C76.idx deleted file mode 100644 index 5999efa..0000000 Binary files a/.cache/clangd/index/invocable_archetype.hpp.169B926EF5696C76.idx and /dev/null differ diff --git a/.cache/clangd/index/io_context.hpp.83C0BB84FCDB4040.idx b/.cache/clangd/index/io_context.hpp.83C0BB84FCDB4040.idx deleted file mode 100644 index ff19567..0000000 Binary files a/.cache/clangd/index/io_context.hpp.83C0BB84FCDB4040.idx and /dev/null differ diff --git a/.cache/clangd/index/io_context.hpp.A71291C91FF52004.idx b/.cache/clangd/index/io_context.hpp.A71291C91FF52004.idx deleted file mode 100644 index 1ddd6e0..0000000 Binary files a/.cache/clangd/index/io_context.hpp.A71291C91FF52004.idx and /dev/null differ diff --git a/.cache/clangd/index/io_context.ipp.965414FCEB89012F.idx b/.cache/clangd/index/io_context.ipp.965414FCEB89012F.idx deleted file mode 100644 index 6e9753f..0000000 Binary files a/.cache/clangd/index/io_context.ipp.965414FCEB89012F.idx and /dev/null differ diff --git a/.cache/clangd/index/io_context_strand.hpp.DF951CCB2FBDC437.idx b/.cache/clangd/index/io_context_strand.hpp.DF951CCB2FBDC437.idx deleted file mode 100644 index 763bd8e..0000000 Binary files a/.cache/clangd/index/io_context_strand.hpp.DF951CCB2FBDC437.idx and /dev/null differ diff --git a/.cache/clangd/index/io_control.hpp.6702609BE5ADFFA6.idx b/.cache/clangd/index/io_control.hpp.6702609BE5ADFFA6.idx deleted file mode 100644 index 838640d..0000000 Binary files a/.cache/clangd/index/io_control.hpp.6702609BE5ADFFA6.idx and /dev/null differ diff --git a/.cache/clangd/index/io_object_impl.hpp.936FF49F74307DAD.idx b/.cache/clangd/index/io_object_impl.hpp.936FF49F74307DAD.idx deleted file mode 100644 index c577015..0000000 Binary files a/.cache/clangd/index/io_object_impl.hpp.936FF49F74307DAD.idx and /dev/null differ diff --git a/.cache/clangd/index/io_service.hpp.64291F846EFA23E2.idx b/.cache/clangd/index/io_service.hpp.64291F846EFA23E2.idx deleted file mode 100644 index 6a4736c..0000000 Binary files a/.cache/clangd/index/io_service.hpp.64291F846EFA23E2.idx and /dev/null differ diff --git a/.cache/clangd/index/io_service_strand.hpp.1D2FEF9EF0C76574.idx b/.cache/clangd/index/io_service_strand.hpp.1D2FEF9EF0C76574.idx deleted file mode 100644 index 4eb7731..0000000 Binary files a/.cache/clangd/index/io_service_strand.hpp.1D2FEF9EF0C76574.idx and /dev/null differ diff --git a/.cache/clangd/index/is_applicable_property.hpp.736F82997A2AB1AB.idx b/.cache/clangd/index/is_applicable_property.hpp.736F82997A2AB1AB.idx deleted file mode 100644 index b51d464..0000000 Binary files a/.cache/clangd/index/is_applicable_property.hpp.736F82997A2AB1AB.idx and /dev/null differ diff --git a/.cache/clangd/index/is_buffer_sequence.hpp.4845CF21AC156821.idx b/.cache/clangd/index/is_buffer_sequence.hpp.4845CF21AC156821.idx deleted file mode 100644 index 9913cd4..0000000 Binary files a/.cache/clangd/index/is_buffer_sequence.hpp.4845CF21AC156821.idx and /dev/null differ diff --git a/.cache/clangd/index/is_contiguous_iterator.hpp.9331A3EDF79B2E09.idx b/.cache/clangd/index/is_contiguous_iterator.hpp.9331A3EDF79B2E09.idx deleted file mode 100644 index 25285bb..0000000 Binary files a/.cache/clangd/index/is_contiguous_iterator.hpp.9331A3EDF79B2E09.idx and /dev/null differ diff --git a/.cache/clangd/index/is_executor.hpp.0424D41B125AFF32.idx b/.cache/clangd/index/is_executor.hpp.0424D41B125AFF32.idx deleted file mode 100644 index 4386647..0000000 Binary files a/.cache/clangd/index/is_executor.hpp.0424D41B125AFF32.idx and /dev/null differ diff --git a/.cache/clangd/index/is_executor.hpp.36FBA1130C38565B.idx b/.cache/clangd/index/is_executor.hpp.36FBA1130C38565B.idx deleted file mode 100644 index 317c6c2..0000000 Binary files a/.cache/clangd/index/is_executor.hpp.36FBA1130C38565B.idx and /dev/null differ diff --git a/.cache/clangd/index/is_read_buffered.hpp.6718F646876737D6.idx b/.cache/clangd/index/is_read_buffered.hpp.6718F646876737D6.idx deleted file mode 100644 index a36c24d..0000000 Binary files a/.cache/clangd/index/is_read_buffered.hpp.6718F646876737D6.idx and /dev/null differ diff --git a/.cache/clangd/index/is_write_buffered.hpp.CD6F137E466EC1E5.idx b/.cache/clangd/index/is_write_buffered.hpp.CD6F137E466EC1E5.idx deleted file mode 100644 index 96a2fd9..0000000 Binary files a/.cache/clangd/index/is_write_buffered.hpp.CD6F137E466EC1E5.idx and /dev/null differ diff --git a/.cache/clangd/index/keyword_tss_ptr.hpp.01518D3E85AA63A4.idx b/.cache/clangd/index/keyword_tss_ptr.hpp.01518D3E85AA63A4.idx deleted file mode 100644 index bcf3586..0000000 Binary files a/.cache/clangd/index/keyword_tss_ptr.hpp.01518D3E85AA63A4.idx and /dev/null differ diff --git a/.cache/clangd/index/limits.hpp.64FE73A800789CA8.idx b/.cache/clangd/index/limits.hpp.64FE73A800789CA8.idx deleted file mode 100644 index 06647a7..0000000 Binary files a/.cache/clangd/index/limits.hpp.64FE73A800789CA8.idx and /dev/null differ diff --git a/.cache/clangd/index/linkobject.cpp.78485F3B7B09B967.idx b/.cache/clangd/index/linkobject.cpp.78485F3B7B09B967.idx deleted file mode 100644 index 5231bd0..0000000 Binary files a/.cache/clangd/index/linkobject.cpp.78485F3B7B09B967.idx and /dev/null differ diff --git a/.cache/clangd/index/linkobject.h.2A4BB697BF1DD713.idx b/.cache/clangd/index/linkobject.h.2A4BB697BF1DD713.idx deleted file mode 100644 index be047c4..0000000 Binary files a/.cache/clangd/index/linkobject.h.2A4BB697BF1DD713.idx and /dev/null differ diff --git a/.cache/clangd/index/linux_joystick.c.16EEF972B4E292FC.idx b/.cache/clangd/index/linux_joystick.c.16EEF972B4E292FC.idx deleted file mode 100644 index 2746194..0000000 Binary files a/.cache/clangd/index/linux_joystick.c.16EEF972B4E292FC.idx and /dev/null differ diff --git a/.cache/clangd/index/linux_joystick.h.DBD5A3089F503290.idx b/.cache/clangd/index/linux_joystick.h.DBD5A3089F503290.idx deleted file mode 100644 index 0b644ee..0000000 Binary files a/.cache/clangd/index/linux_joystick.h.DBD5A3089F503290.idx and /dev/null differ diff --git a/.cache/clangd/index/listobject.cpp.FCC5E6DBBFD70F07.idx b/.cache/clangd/index/listobject.cpp.FCC5E6DBBFD70F07.idx deleted file mode 100644 index fc51293..0000000 Binary files a/.cache/clangd/index/listobject.cpp.FCC5E6DBBFD70F07.idx and /dev/null differ diff --git a/.cache/clangd/index/listobject.h.E55983F442E7A88A.idx b/.cache/clangd/index/listobject.h.E55983F442E7A88A.idx deleted file mode 100644 index 7c4bb03..0000000 Binary files a/.cache/clangd/index/listobject.h.E55983F442E7A88A.idx and /dev/null differ diff --git a/.cache/clangd/index/local_free_on_block_exit.hpp.59491AFBFC9C1E5E.idx b/.cache/clangd/index/local_free_on_block_exit.hpp.59491AFBFC9C1E5E.idx deleted file mode 100644 index 4af90eb..0000000 Binary files a/.cache/clangd/index/local_free_on_block_exit.hpp.59491AFBFC9C1E5E.idx and /dev/null differ diff --git a/.cache/clangd/index/mapping.hpp.E06A118D8D135FA4.idx b/.cache/clangd/index/mapping.hpp.E06A118D8D135FA4.idx deleted file mode 100644 index dd69ef8..0000000 Binary files a/.cache/clangd/index/mapping.hpp.E06A118D8D135FA4.idx and /dev/null differ diff --git a/.cache/clangd/index/mappings.h.0ED9776694C41033.idx b/.cache/clangd/index/mappings.h.0ED9776694C41033.idx deleted file mode 100644 index bd69877..0000000 Binary files a/.cache/clangd/index/mappings.h.0ED9776694C41033.idx and /dev/null differ diff --git a/.cache/clangd/index/memory.hpp.BF5532DF6498CCFF.idx b/.cache/clangd/index/memory.hpp.BF5532DF6498CCFF.idx deleted file mode 100644 index b30c423..0000000 Binary files a/.cache/clangd/index/memory.hpp.BF5532DF6498CCFF.idx and /dev/null differ diff --git a/.cache/clangd/index/methodobject.cpp.98BD9180FEDDFF8B.idx b/.cache/clangd/index/methodobject.cpp.98BD9180FEDDFF8B.idx deleted file mode 100644 index 9dec667..0000000 Binary files a/.cache/clangd/index/methodobject.cpp.98BD9180FEDDFF8B.idx and /dev/null differ diff --git a/.cache/clangd/index/methodobject.h.B5476B63E0E7EB0E.idx b/.cache/clangd/index/methodobject.h.B5476B63E0E7EB0E.idx deleted file mode 100644 index 82775b4..0000000 Binary files a/.cache/clangd/index/methodobject.h.B5476B63E0E7EB0E.idx and /dev/null differ diff --git a/.cache/clangd/index/module.cpp.10ABE84461B1A96E.idx b/.cache/clangd/index/module.cpp.10ABE84461B1A96E.idx deleted file mode 100644 index 2eaeb63..0000000 Binary files a/.cache/clangd/index/module.cpp.10ABE84461B1A96E.idx and /dev/null differ diff --git a/.cache/clangd/index/monitor.c.AF6C5EEDF3F29672.idx b/.cache/clangd/index/monitor.c.AF6C5EEDF3F29672.idx deleted file mode 100644 index 1a430ca..0000000 Binary files a/.cache/clangd/index/monitor.c.AF6C5EEDF3F29672.idx and /dev/null differ diff --git a/.cache/clangd/index/multicast.hpp.668EEDF323385785.idx b/.cache/clangd/index/multicast.hpp.668EEDF323385785.idx deleted file mode 100644 index bfc1d2d..0000000 Binary files a/.cache/clangd/index/multicast.hpp.668EEDF323385785.idx and /dev/null differ diff --git a/.cache/clangd/index/multiple_exceptions.hpp.A70C64B4AF29AAE4.idx b/.cache/clangd/index/multiple_exceptions.hpp.A70C64B4AF29AAE4.idx deleted file mode 100644 index 0a06059..0000000 Binary files a/.cache/clangd/index/multiple_exceptions.hpp.A70C64B4AF29AAE4.idx and /dev/null differ diff --git a/.cache/clangd/index/multiple_exceptions.ipp.A39042C05AC8D55A.idx b/.cache/clangd/index/multiple_exceptions.ipp.A39042C05AC8D55A.idx deleted file mode 100644 index 1c62773..0000000 Binary files a/.cache/clangd/index/multiple_exceptions.ipp.A39042C05AC8D55A.idx and /dev/null differ diff --git a/.cache/clangd/index/mutex.hpp.3F81F5FAC55623A1.idx b/.cache/clangd/index/mutex.hpp.3F81F5FAC55623A1.idx deleted file mode 100644 index d454ed5..0000000 Binary files a/.cache/clangd/index/mutex.hpp.3F81F5FAC55623A1.idx and /dev/null differ diff --git a/.cache/clangd/index/nanovg.c.CE64C1F15FD2C8A5.idx b/.cache/clangd/index/nanovg.c.CE64C1F15FD2C8A5.idx deleted file mode 100644 index 99e38d5..0000000 Binary files a/.cache/clangd/index/nanovg.c.CE64C1F15FD2C8A5.idx and /dev/null differ diff --git a/.cache/clangd/index/nanovg.h.6640925FA16888A8.idx b/.cache/clangd/index/nanovg.h.6640925FA16888A8.idx deleted file mode 100644 index aa240e1..0000000 Binary files a/.cache/clangd/index/nanovg.h.6640925FA16888A8.idx and /dev/null differ diff --git a/.cache/clangd/index/nanovg_gl.h.CEA1371D6A9BCA48.idx b/.cache/clangd/index/nanovg_gl.h.CEA1371D6A9BCA48.idx deleted file mode 100644 index e696269..0000000 Binary files a/.cache/clangd/index/nanovg_gl.h.CEA1371D6A9BCA48.idx and /dev/null differ diff --git a/.cache/clangd/index/network_v4.hpp.3E6023898AC82F62.idx b/.cache/clangd/index/network_v4.hpp.3E6023898AC82F62.idx deleted file mode 100644 index 882f34a..0000000 Binary files a/.cache/clangd/index/network_v4.hpp.3E6023898AC82F62.idx and /dev/null differ diff --git a/.cache/clangd/index/network_v4.hpp.C55A4D334DB1F9FD.idx b/.cache/clangd/index/network_v4.hpp.C55A4D334DB1F9FD.idx deleted file mode 100644 index f20ac7c..0000000 Binary files a/.cache/clangd/index/network_v4.hpp.C55A4D334DB1F9FD.idx and /dev/null differ diff --git a/.cache/clangd/index/network_v4.ipp.B5D4B4673BE1BD36.idx b/.cache/clangd/index/network_v4.ipp.B5D4B4673BE1BD36.idx deleted file mode 100644 index 77825f0..0000000 Binary files a/.cache/clangd/index/network_v4.ipp.B5D4B4673BE1BD36.idx and /dev/null differ diff --git a/.cache/clangd/index/network_v6.hpp.3EAF1664E8EAB84D.idx b/.cache/clangd/index/network_v6.hpp.3EAF1664E8EAB84D.idx deleted file mode 100644 index 59c852a..0000000 Binary files a/.cache/clangd/index/network_v6.hpp.3EAF1664E8EAB84D.idx and /dev/null differ diff --git a/.cache/clangd/index/network_v6.hpp.B4CDAD263DADD967.idx b/.cache/clangd/index/network_v6.hpp.B4CDAD263DADD967.idx deleted file mode 100644 index 3c2597c..0000000 Binary files a/.cache/clangd/index/network_v6.hpp.B4CDAD263DADD967.idx and /dev/null differ diff --git a/.cache/clangd/index/network_v6.ipp.432D51F5B3ADF81C.idx b/.cache/clangd/index/network_v6.ipp.432D51F5B3ADF81C.idx deleted file mode 100644 index 858690e..0000000 Binary files a/.cache/clangd/index/network_v6.ipp.432D51F5B3ADF81C.idx and /dev/null differ diff --git a/.cache/clangd/index/non_const_lvalue.hpp.0BCF2E1013A983D2.idx b/.cache/clangd/index/non_const_lvalue.hpp.0BCF2E1013A983D2.idx deleted file mode 100644 index 4b47ec9..0000000 Binary files a/.cache/clangd/index/non_const_lvalue.hpp.0BCF2E1013A983D2.idx and /dev/null differ diff --git a/.cache/clangd/index/noncopyable.hpp.10768939D8992A13.idx b/.cache/clangd/index/noncopyable.hpp.10768939D8992A13.idx deleted file mode 100644 index f33159c..0000000 Binary files a/.cache/clangd/index/noncopyable.hpp.10768939D8992A13.idx and /dev/null differ diff --git a/.cache/clangd/index/null_event.hpp.E40D4B559793B197.idx b/.cache/clangd/index/null_event.hpp.E40D4B559793B197.idx deleted file mode 100644 index 5086adf..0000000 Binary files a/.cache/clangd/index/null_event.hpp.E40D4B559793B197.idx and /dev/null differ diff --git a/.cache/clangd/index/null_event.ipp.14F1D1331530639F.idx b/.cache/clangd/index/null_event.ipp.14F1D1331530639F.idx deleted file mode 100644 index 064b2b9..0000000 Binary files a/.cache/clangd/index/null_event.ipp.14F1D1331530639F.idx and /dev/null differ diff --git a/.cache/clangd/index/null_init.c.DFBD0A3B087629E5.idx b/.cache/clangd/index/null_init.c.DFBD0A3B087629E5.idx deleted file mode 100644 index a219eb6..0000000 Binary files a/.cache/clangd/index/null_init.c.DFBD0A3B087629E5.idx and /dev/null differ diff --git a/.cache/clangd/index/null_joystick.c.E54B534D0E0C4F5B.idx b/.cache/clangd/index/null_joystick.c.E54B534D0E0C4F5B.idx deleted file mode 100644 index 1cc4ebf..0000000 Binary files a/.cache/clangd/index/null_joystick.c.E54B534D0E0C4F5B.idx and /dev/null differ diff --git a/.cache/clangd/index/null_joystick.h.F2C5F604E838A45E.idx b/.cache/clangd/index/null_joystick.h.F2C5F604E838A45E.idx deleted file mode 100644 index 529ba62..0000000 Binary files a/.cache/clangd/index/null_joystick.h.F2C5F604E838A45E.idx and /dev/null differ diff --git a/.cache/clangd/index/null_monitor.c.24A876F3811B8A4D.idx b/.cache/clangd/index/null_monitor.c.24A876F3811B8A4D.idx deleted file mode 100644 index 48d9c80..0000000 Binary files a/.cache/clangd/index/null_monitor.c.24A876F3811B8A4D.idx and /dev/null differ diff --git a/.cache/clangd/index/null_platform.h.F31C40275B643587.idx b/.cache/clangd/index/null_platform.h.F31C40275B643587.idx deleted file mode 100644 index 9aea7a0..0000000 Binary files a/.cache/clangd/index/null_platform.h.F31C40275B643587.idx and /dev/null differ diff --git a/.cache/clangd/index/null_window.c.8B97313342167961.idx b/.cache/clangd/index/null_window.c.8B97313342167961.idx deleted file mode 100644 index 8566daf..0000000 Binary files a/.cache/clangd/index/null_window.c.8B97313342167961.idx and /dev/null differ diff --git a/.cache/clangd/index/nullobject.cpp.438D916671238506.idx b/.cache/clangd/index/nullobject.cpp.438D916671238506.idx deleted file mode 100644 index 6233cac..0000000 Binary files a/.cache/clangd/index/nullobject.cpp.438D916671238506.idx and /dev/null differ diff --git a/.cache/clangd/index/nullobject.h.3EB46406395F4D9A.idx b/.cache/clangd/index/nullobject.h.3EB46406395F4D9A.idx deleted file mode 100644 index a4966e3..0000000 Binary files a/.cache/clangd/index/nullobject.h.3EB46406395F4D9A.idx and /dev/null differ diff --git a/.cache/clangd/index/object.cpp.F79F0C3FB2311B5C.idx b/.cache/clangd/index/object.cpp.F79F0C3FB2311B5C.idx deleted file mode 100644 index 46c842d..0000000 Binary files a/.cache/clangd/index/object.cpp.F79F0C3FB2311B5C.idx and /dev/null differ diff --git a/.cache/clangd/index/object.h.C17423CF79DF16D1.idx b/.cache/clangd/index/object.h.C17423CF79DF16D1.idx deleted file mode 100644 index 138bcf9..0000000 Binary files a/.cache/clangd/index/object.h.C17423CF79DF16D1.idx and /dev/null differ diff --git a/.cache/clangd/index/object_handle.hpp.EA3830EC10F52728.idx b/.cache/clangd/index/object_handle.hpp.EA3830EC10F52728.idx deleted file mode 100644 index 5d160f3..0000000 Binary files a/.cache/clangd/index/object_handle.hpp.EA3830EC10F52728.idx and /dev/null differ diff --git a/.cache/clangd/index/object_pool.hpp.90292DE173EA3E5A.idx b/.cache/clangd/index/object_pool.hpp.90292DE173EA3E5A.idx deleted file mode 100644 index a8422b9..0000000 Binary files a/.cache/clangd/index/object_pool.hpp.90292DE173EA3E5A.idx and /dev/null differ diff --git a/.cache/clangd/index/objectsave.cpp.EF0E7554A963E6F8.idx b/.cache/clangd/index/objectsave.cpp.EF0E7554A963E6F8.idx deleted file mode 100644 index deb20b0..0000000 Binary files a/.cache/clangd/index/objectsave.cpp.EF0E7554A963E6F8.idx and /dev/null differ diff --git a/.cache/clangd/index/occupancy.hpp.6BC1F1E2F9C99E7B.idx b/.cache/clangd/index/occupancy.hpp.6BC1F1E2F9C99E7B.idx deleted file mode 100644 index 77fec4e..0000000 Binary files a/.cache/clangd/index/occupancy.hpp.6BC1F1E2F9C99E7B.idx and /dev/null differ diff --git a/.cache/clangd/index/op_queue.hpp.DEDAFD0365446D65.idx b/.cache/clangd/index/op_queue.hpp.DEDAFD0365446D65.idx deleted file mode 100644 index b18d86a..0000000 Binary files a/.cache/clangd/index/op_queue.hpp.DEDAFD0365446D65.idx and /dev/null differ diff --git a/.cache/clangd/index/opcodes.cpp.C0140E006E7F9748.idx b/.cache/clangd/index/opcodes.cpp.C0140E006E7F9748.idx deleted file mode 100644 index 08c4f5b..0000000 Binary files a/.cache/clangd/index/opcodes.cpp.C0140E006E7F9748.idx and /dev/null differ diff --git a/.cache/clangd/index/opcodes.h.515F3C4479D28001.idx b/.cache/clangd/index/opcodes.h.515F3C4479D28001.idx deleted file mode 100644 index 0106711..0000000 Binary files a/.cache/clangd/index/opcodes.h.515F3C4479D28001.idx and /dev/null differ diff --git a/.cache/clangd/index/operandsstack.cpp.4C3CE8958DE5D912.idx b/.cache/clangd/index/operandsstack.cpp.4C3CE8958DE5D912.idx deleted file mode 100644 index 67e6a31..0000000 Binary files a/.cache/clangd/index/operandsstack.cpp.4C3CE8958DE5D912.idx and /dev/null differ diff --git a/.cache/clangd/index/operandsstack.h.A9BBDB08C6E1C544.idx b/.cache/clangd/index/operandsstack.h.A9BBDB08C6E1C544.idx deleted file mode 100644 index 515b57a..0000000 Binary files a/.cache/clangd/index/operandsstack.h.A9BBDB08C6E1C544.idx and /dev/null differ diff --git a/.cache/clangd/index/operation.hpp.AAA42C8136FE5DC4.idx b/.cache/clangd/index/operation.hpp.AAA42C8136FE5DC4.idx deleted file mode 100644 index 2f4eca7..0000000 Binary files a/.cache/clangd/index/operation.hpp.AAA42C8136FE5DC4.idx and /dev/null differ diff --git a/.cache/clangd/index/operation_state.hpp.AADABC9115815DAC.idx b/.cache/clangd/index/operation_state.hpp.AADABC9115815DAC.idx deleted file mode 100644 index 4f605e8..0000000 Binary files a/.cache/clangd/index/operation_state.hpp.AADABC9115815DAC.idx and /dev/null differ diff --git a/.cache/clangd/index/osmesa_context.c.B67442D332DD7B88.idx b/.cache/clangd/index/osmesa_context.c.B67442D332DD7B88.idx deleted file mode 100644 index 0b7631f..0000000 Binary files a/.cache/clangd/index/osmesa_context.c.B67442D332DD7B88.idx and /dev/null differ diff --git a/.cache/clangd/index/outstanding_work.hpp.EED66AEA4FF57B2F.idx b/.cache/clangd/index/outstanding_work.hpp.EED66AEA4FF57B2F.idx deleted file mode 100644 index 3307bb6..0000000 Binary files a/.cache/clangd/index/outstanding_work.hpp.EED66AEA4FF57B2F.idx and /dev/null differ diff --git a/.cache/clangd/index/overlapped_handle.hpp.6B84E464B83F01CC.idx b/.cache/clangd/index/overlapped_handle.hpp.6B84E464B83F01CC.idx deleted file mode 100644 index 8de9ed9..0000000 Binary files a/.cache/clangd/index/overlapped_handle.hpp.6B84E464B83F01CC.idx and /dev/null differ diff --git a/.cache/clangd/index/overlapped_ptr.hpp.B78DB36CF1FA16CC.idx b/.cache/clangd/index/overlapped_ptr.hpp.B78DB36CF1FA16CC.idx deleted file mode 100644 index 1d1a817..0000000 Binary files a/.cache/clangd/index/overlapped_ptr.hpp.B78DB36CF1FA16CC.idx and /dev/null differ diff --git a/.cache/clangd/index/packaged_task.hpp.E45F36E257DF1968.idx b/.cache/clangd/index/packaged_task.hpp.E45F36E257DF1968.idx deleted file mode 100644 index 79f5fdb..0000000 Binary files a/.cache/clangd/index/packaged_task.hpp.E45F36E257DF1968.idx and /dev/null differ diff --git a/.cache/clangd/index/parser.cpp.084EBF0A201167D2.idx b/.cache/clangd/index/parser.cpp.084EBF0A201167D2.idx deleted file mode 100644 index fbc0147..0000000 Binary files a/.cache/clangd/index/parser.cpp.084EBF0A201167D2.idx and /dev/null differ diff --git a/.cache/clangd/index/parser.h.A4D048FD9FF66E2B.idx b/.cache/clangd/index/parser.h.A4D048FD9FF66E2B.idx deleted file mode 100644 index 5c34dc1..0000000 Binary files a/.cache/clangd/index/parser.h.A4D048FD9FF66E2B.idx and /dev/null differ diff --git a/.cache/clangd/index/placeholders.hpp.A8554B98B663AD06.idx b/.cache/clangd/index/placeholders.hpp.A8554B98B663AD06.idx deleted file mode 100644 index 11e1918..0000000 Binary files a/.cache/clangd/index/placeholders.hpp.A8554B98B663AD06.idx and /dev/null differ diff --git a/.cache/clangd/index/platform.c.441611E1070C0D1A.idx b/.cache/clangd/index/platform.c.441611E1070C0D1A.idx deleted file mode 100644 index 97c0ed4..0000000 Binary files a/.cache/clangd/index/platform.c.441611E1070C0D1A.idx and /dev/null differ diff --git a/.cache/clangd/index/platform.h.83FDEA02A0F864B5.idx b/.cache/clangd/index/platform.h.83FDEA02A0F864B5.idx deleted file mode 100644 index 4aa8b17..0000000 Binary files a/.cache/clangd/index/platform.h.83FDEA02A0F864B5.idx and /dev/null differ diff --git a/.cache/clangd/index/pop_options.hpp.5071F7A79208CE84.idx b/.cache/clangd/index/pop_options.hpp.5071F7A79208CE84.idx deleted file mode 100644 index 99df5eb..0000000 Binary files a/.cache/clangd/index/pop_options.hpp.5071F7A79208CE84.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_event.hpp.A3D3C0046F8F5273.idx b/.cache/clangd/index/posix_event.hpp.A3D3C0046F8F5273.idx deleted file mode 100644 index 54c8fd5..0000000 Binary files a/.cache/clangd/index/posix_event.hpp.A3D3C0046F8F5273.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_event.ipp.D5462366081DE876.idx b/.cache/clangd/index/posix_event.ipp.D5462366081DE876.idx deleted file mode 100644 index 878d3af..0000000 Binary files a/.cache/clangd/index/posix_event.ipp.D5462366081DE876.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_global.hpp.32F6E143D0A79881.idx b/.cache/clangd/index/posix_global.hpp.32F6E143D0A79881.idx deleted file mode 100644 index 885819c..0000000 Binary files a/.cache/clangd/index/posix_global.hpp.32F6E143D0A79881.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_module.c.809BBAC4B99E7FBA.idx b/.cache/clangd/index/posix_module.c.809BBAC4B99E7FBA.idx deleted file mode 100644 index 602102b..0000000 Binary files a/.cache/clangd/index/posix_module.c.809BBAC4B99E7FBA.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_mutex.hpp.B59E89CF96C21101.idx b/.cache/clangd/index/posix_mutex.hpp.B59E89CF96C21101.idx deleted file mode 100644 index 9571243..0000000 Binary files a/.cache/clangd/index/posix_mutex.hpp.B59E89CF96C21101.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_mutex.ipp.1E3F9B67A846A249.idx b/.cache/clangd/index/posix_mutex.ipp.1E3F9B67A846A249.idx deleted file mode 100644 index d1fe26c..0000000 Binary files a/.cache/clangd/index/posix_mutex.ipp.1E3F9B67A846A249.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_poll.c.0B5BC8FA8F93CF7B.idx b/.cache/clangd/index/posix_poll.c.0B5BC8FA8F93CF7B.idx deleted file mode 100644 index 6a9dc08..0000000 Binary files a/.cache/clangd/index/posix_poll.c.0B5BC8FA8F93CF7B.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_poll.h.1C13112E50876B53.idx b/.cache/clangd/index/posix_poll.h.1C13112E50876B53.idx deleted file mode 100644 index 1a9d383..0000000 Binary files a/.cache/clangd/index/posix_poll.h.1C13112E50876B53.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_serial_port_service.hpp.879A858F3C81CDBD.idx b/.cache/clangd/index/posix_serial_port_service.hpp.879A858F3C81CDBD.idx deleted file mode 100644 index 430af3d..0000000 Binary files a/.cache/clangd/index/posix_serial_port_service.hpp.879A858F3C81CDBD.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_serial_port_service.ipp.1B126C57A1D1906B.idx b/.cache/clangd/index/posix_serial_port_service.ipp.1B126C57A1D1906B.idx deleted file mode 100644 index 1988f89..0000000 Binary files a/.cache/clangd/index/posix_serial_port_service.ipp.1B126C57A1D1906B.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_signal_blocker.hpp.788468099DABE638.idx b/.cache/clangd/index/posix_signal_blocker.hpp.788468099DABE638.idx deleted file mode 100644 index 3850d93..0000000 Binary files a/.cache/clangd/index/posix_signal_blocker.hpp.788468099DABE638.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_static_mutex.hpp.C5486DB80043EAAB.idx b/.cache/clangd/index/posix_static_mutex.hpp.C5486DB80043EAAB.idx deleted file mode 100644 index b2e1536..0000000 Binary files a/.cache/clangd/index/posix_static_mutex.hpp.C5486DB80043EAAB.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_thread.c.70CE64D3940506CE.idx b/.cache/clangd/index/posix_thread.c.70CE64D3940506CE.idx deleted file mode 100644 index 64cadfa..0000000 Binary files a/.cache/clangd/index/posix_thread.c.70CE64D3940506CE.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_thread.h.86EEDE30A3E8F2F3.idx b/.cache/clangd/index/posix_thread.h.86EEDE30A3E8F2F3.idx deleted file mode 100644 index 089ae4d..0000000 Binary files a/.cache/clangd/index/posix_thread.h.86EEDE30A3E8F2F3.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_thread.hpp.399B7A231B80AB92.idx b/.cache/clangd/index/posix_thread.hpp.399B7A231B80AB92.idx deleted file mode 100644 index 3c720a0..0000000 Binary files a/.cache/clangd/index/posix_thread.hpp.399B7A231B80AB92.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_thread.ipp.4EE890F4E58A1E3E.idx b/.cache/clangd/index/posix_thread.ipp.4EE890F4E58A1E3E.idx deleted file mode 100644 index 5d1d25a..0000000 Binary files a/.cache/clangd/index/posix_thread.ipp.4EE890F4E58A1E3E.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_time.c.00549467F9F25105.idx b/.cache/clangd/index/posix_time.c.00549467F9F25105.idx deleted file mode 100644 index 4263b8e..0000000 Binary files a/.cache/clangd/index/posix_time.c.00549467F9F25105.idx and /dev/null differ diff --git a/.cache/clangd/index/posix_time.h.66399854F81EE134.idx b/.cache/clangd/index/posix_time.h.66399854F81EE134.idx deleted file mode 100644 index e43d8d0..0000000 Binary files a/.cache/clangd/index/posix_time.h.66399854F81EE134.idx and /dev/null differ diff --git a/.cache/clangd/index/post.hpp.22D30B5CFE386655.idx b/.cache/clangd/index/post.hpp.22D30B5CFE386655.idx deleted file mode 100644 index 3166baf..0000000 Binary files a/.cache/clangd/index/post.hpp.22D30B5CFE386655.idx and /dev/null differ diff --git a/.cache/clangd/index/prefer.hpp.A0B44A767E59BFCD.idx b/.cache/clangd/index/prefer.hpp.A0B44A767E59BFCD.idx deleted file mode 100644 index 9754789..0000000 Binary files a/.cache/clangd/index/prefer.hpp.A0B44A767E59BFCD.idx and /dev/null differ diff --git a/.cache/clangd/index/prefer_free.hpp.2E44AAA9436304B5.idx b/.cache/clangd/index/prefer_free.hpp.2E44AAA9436304B5.idx deleted file mode 100644 index 7a21be3..0000000 Binary files a/.cache/clangd/index/prefer_free.hpp.2E44AAA9436304B5.idx and /dev/null differ diff --git a/.cache/clangd/index/prefer_member.hpp.AB51ED9DEEFF2287.idx b/.cache/clangd/index/prefer_member.hpp.AB51ED9DEEFF2287.idx deleted file mode 100644 index 4a3873d..0000000 Binary files a/.cache/clangd/index/prefer_member.hpp.AB51ED9DEEFF2287.idx and /dev/null differ diff --git a/.cache/clangd/index/prefer_only.hpp.63FA3C65F9D95F48.idx b/.cache/clangd/index/prefer_only.hpp.63FA3C65F9D95F48.idx deleted file mode 100644 index cb2ecfe..0000000 Binary files a/.cache/clangd/index/prefer_only.hpp.63FA3C65F9D95F48.idx and /dev/null differ diff --git a/.cache/clangd/index/prepend.hpp.28D2B171F02944B4.idx b/.cache/clangd/index/prepend.hpp.28D2B171F02944B4.idx deleted file mode 100644 index e13afa1..0000000 Binary files a/.cache/clangd/index/prepend.hpp.28D2B171F02944B4.idx and /dev/null differ diff --git a/.cache/clangd/index/prepend.hpp.FF37B83050A7FD8A.idx b/.cache/clangd/index/prepend.hpp.FF37B83050A7FD8A.idx deleted file mode 100644 index f084bf0..0000000 Binary files a/.cache/clangd/index/prepend.hpp.FF37B83050A7FD8A.idx and /dev/null differ diff --git a/.cache/clangd/index/primitives.h.867CD070B6D3D77D.idx b/.cache/clangd/index/primitives.h.867CD070B6D3D77D.idx deleted file mode 100644 index 7360daa..0000000 Binary files a/.cache/clangd/index/primitives.h.867CD070B6D3D77D.idx and /dev/null differ diff --git a/.cache/clangd/index/push_options.hpp.8C7D253B62A24561.idx b/.cache/clangd/index/push_options.hpp.8C7D253B62A24561.idx deleted file mode 100644 index 5a0e282..0000000 Binary files a/.cache/clangd/index/push_options.hpp.8C7D253B62A24561.idx and /dev/null differ diff --git a/.cache/clangd/index/query.hpp.985CC8606FE59F3F.idx b/.cache/clangd/index/query.hpp.985CC8606FE59F3F.idx deleted file mode 100644 index 7ab1416..0000000 Binary files a/.cache/clangd/index/query.hpp.985CC8606FE59F3F.idx and /dev/null differ diff --git a/.cache/clangd/index/query_free.hpp.8C3315B1EEFD53BE.idx b/.cache/clangd/index/query_free.hpp.8C3315B1EEFD53BE.idx deleted file mode 100644 index 03eace1..0000000 Binary files a/.cache/clangd/index/query_free.hpp.8C3315B1EEFD53BE.idx and /dev/null differ diff --git a/.cache/clangd/index/query_member.hpp.EA840D59835A0211.idx b/.cache/clangd/index/query_member.hpp.EA840D59835A0211.idx deleted file mode 100644 index 690c6ac..0000000 Binary files a/.cache/clangd/index/query_member.hpp.EA840D59835A0211.idx and /dev/null differ diff --git a/.cache/clangd/index/query_static_constexpr_member.hpp.71E0EB2E38CD25CC.idx b/.cache/clangd/index/query_static_constexpr_member.hpp.71E0EB2E38CD25CC.idx deleted file mode 100644 index bf5a911..0000000 Binary files a/.cache/clangd/index/query_static_constexpr_member.hpp.71E0EB2E38CD25CC.idx and /dev/null differ diff --git a/.cache/clangd/index/random_access_file.hpp.8BCF5E8C1E09A032.idx b/.cache/clangd/index/random_access_file.hpp.8BCF5E8C1E09A032.idx deleted file mode 100644 index 1da2b21..0000000 Binary files a/.cache/clangd/index/random_access_file.hpp.8BCF5E8C1E09A032.idx and /dev/null differ diff --git a/.cache/clangd/index/random_access_handle.hpp.587A18025EAEF314.idx b/.cache/clangd/index/random_access_handle.hpp.587A18025EAEF314.idx deleted file mode 100644 index a1e5467..0000000 Binary files a/.cache/clangd/index/random_access_handle.hpp.587A18025EAEF314.idx and /dev/null differ diff --git a/.cache/clangd/index/raw_protocol.hpp.ADCBC578487EE8C9.idx b/.cache/clangd/index/raw_protocol.hpp.ADCBC578487EE8C9.idx deleted file mode 100644 index ceb54f5..0000000 Binary files a/.cache/clangd/index/raw_protocol.hpp.ADCBC578487EE8C9.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_descriptor_service.hpp.B6FF9A011C21328A.idx b/.cache/clangd/index/reactive_descriptor_service.hpp.B6FF9A011C21328A.idx deleted file mode 100644 index 72f4235..0000000 Binary files a/.cache/clangd/index/reactive_descriptor_service.hpp.B6FF9A011C21328A.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_descriptor_service.ipp.42EA15C79557CA93.idx b/.cache/clangd/index/reactive_descriptor_service.ipp.42EA15C79557CA93.idx deleted file mode 100644 index cb3e66a..0000000 Binary files a/.cache/clangd/index/reactive_descriptor_service.ipp.42EA15C79557CA93.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_null_buffers_op.hpp.33DF80A1F7CF6054.idx b/.cache/clangd/index/reactive_null_buffers_op.hpp.33DF80A1F7CF6054.idx deleted file mode 100644 index 23470eb..0000000 Binary files a/.cache/clangd/index/reactive_null_buffers_op.hpp.33DF80A1F7CF6054.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_accept_op.hpp.00ABD3FDFA393123.idx b/.cache/clangd/index/reactive_socket_accept_op.hpp.00ABD3FDFA393123.idx deleted file mode 100644 index d06f43e..0000000 Binary files a/.cache/clangd/index/reactive_socket_accept_op.hpp.00ABD3FDFA393123.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_connect_op.hpp.7192E5FB49548436.idx b/.cache/clangd/index/reactive_socket_connect_op.hpp.7192E5FB49548436.idx deleted file mode 100644 index 226de33..0000000 Binary files a/.cache/clangd/index/reactive_socket_connect_op.hpp.7192E5FB49548436.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_recv_op.hpp.351C4B9281D838D6.idx b/.cache/clangd/index/reactive_socket_recv_op.hpp.351C4B9281D838D6.idx deleted file mode 100644 index fb50c99..0000000 Binary files a/.cache/clangd/index/reactive_socket_recv_op.hpp.351C4B9281D838D6.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_recvfrom_op.hpp.A9B5BE4B094D5869.idx b/.cache/clangd/index/reactive_socket_recvfrom_op.hpp.A9B5BE4B094D5869.idx deleted file mode 100644 index 6d2e544..0000000 Binary files a/.cache/clangd/index/reactive_socket_recvfrom_op.hpp.A9B5BE4B094D5869.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_recvmsg_op.hpp.E042E03FAB2C196D.idx b/.cache/clangd/index/reactive_socket_recvmsg_op.hpp.E042E03FAB2C196D.idx deleted file mode 100644 index 04f2c75..0000000 Binary files a/.cache/clangd/index/reactive_socket_recvmsg_op.hpp.E042E03FAB2C196D.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_send_op.hpp.24A76D5A007D4024.idx b/.cache/clangd/index/reactive_socket_send_op.hpp.24A76D5A007D4024.idx deleted file mode 100644 index b563e50..0000000 Binary files a/.cache/clangd/index/reactive_socket_send_op.hpp.24A76D5A007D4024.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_sendto_op.hpp.92901601F278C7EC.idx b/.cache/clangd/index/reactive_socket_sendto_op.hpp.92901601F278C7EC.idx deleted file mode 100644 index 3f45310..0000000 Binary files a/.cache/clangd/index/reactive_socket_sendto_op.hpp.92901601F278C7EC.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_service.hpp.6C6E6E325897AEAB.idx b/.cache/clangd/index/reactive_socket_service.hpp.6C6E6E325897AEAB.idx deleted file mode 100644 index 91290e2..0000000 Binary files a/.cache/clangd/index/reactive_socket_service.hpp.6C6E6E325897AEAB.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_service_base.hpp.98D9F4243D38E78A.idx b/.cache/clangd/index/reactive_socket_service_base.hpp.98D9F4243D38E78A.idx deleted file mode 100644 index b454637..0000000 Binary files a/.cache/clangd/index/reactive_socket_service_base.hpp.98D9F4243D38E78A.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_socket_service_base.ipp.49AB5C696AFDFA4F.idx b/.cache/clangd/index/reactive_socket_service_base.ipp.49AB5C696AFDFA4F.idx deleted file mode 100644 index 348671c..0000000 Binary files a/.cache/clangd/index/reactive_socket_service_base.ipp.49AB5C696AFDFA4F.idx and /dev/null differ diff --git a/.cache/clangd/index/reactive_wait_op.hpp.DBB1E72F06A64A1E.idx b/.cache/clangd/index/reactive_wait_op.hpp.DBB1E72F06A64A1E.idx deleted file mode 100644 index 537a4f6..0000000 Binary files a/.cache/clangd/index/reactive_wait_op.hpp.DBB1E72F06A64A1E.idx and /dev/null differ diff --git a/.cache/clangd/index/reactor.hpp.ED5E212A997C4BB7.idx b/.cache/clangd/index/reactor.hpp.ED5E212A997C4BB7.idx deleted file mode 100644 index 2fc2030..0000000 Binary files a/.cache/clangd/index/reactor.hpp.ED5E212A997C4BB7.idx and /dev/null differ diff --git a/.cache/clangd/index/reactor_op.hpp.DD1401E0DE24ABF7.idx b/.cache/clangd/index/reactor_op.hpp.DD1401E0DE24ABF7.idx deleted file mode 100644 index 2b52b17..0000000 Binary files a/.cache/clangd/index/reactor_op.hpp.DD1401E0DE24ABF7.idx and /dev/null differ diff --git a/.cache/clangd/index/read.hpp.58D2F16E1B40B7EC.idx b/.cache/clangd/index/read.hpp.58D2F16E1B40B7EC.idx deleted file mode 100644 index 77652f5..0000000 Binary files a/.cache/clangd/index/read.hpp.58D2F16E1B40B7EC.idx and /dev/null differ diff --git a/.cache/clangd/index/read.hpp.F3DC6F5D6508C873.idx b/.cache/clangd/index/read.hpp.F3DC6F5D6508C873.idx deleted file mode 100644 index 408658c..0000000 Binary files a/.cache/clangd/index/read.hpp.F3DC6F5D6508C873.idx and /dev/null differ diff --git a/.cache/clangd/index/read_at.hpp.904654D36F77F8F5.idx b/.cache/clangd/index/read_at.hpp.904654D36F77F8F5.idx deleted file mode 100644 index 499d3dc..0000000 Binary files a/.cache/clangd/index/read_at.hpp.904654D36F77F8F5.idx and /dev/null differ diff --git a/.cache/clangd/index/read_at.hpp.E5E30F8C2BB280EA.idx b/.cache/clangd/index/read_at.hpp.E5E30F8C2BB280EA.idx deleted file mode 100644 index 9499718..0000000 Binary files a/.cache/clangd/index/read_at.hpp.E5E30F8C2BB280EA.idx and /dev/null differ diff --git a/.cache/clangd/index/read_until.hpp.1249EDC4298D73A4.idx b/.cache/clangd/index/read_until.hpp.1249EDC4298D73A4.idx deleted file mode 100644 index 519b8c0..0000000 Binary files a/.cache/clangd/index/read_until.hpp.1249EDC4298D73A4.idx and /dev/null differ diff --git a/.cache/clangd/index/read_until.hpp.E0C444F8EC9059B1.idx b/.cache/clangd/index/read_until.hpp.E0C444F8EC9059B1.idx deleted file mode 100644 index d901833..0000000 Binary files a/.cache/clangd/index/read_until.hpp.E0C444F8EC9059B1.idx and /dev/null differ diff --git a/.cache/clangd/index/readable_pipe.hpp.4882300A55637051.idx b/.cache/clangd/index/readable_pipe.hpp.4882300A55637051.idx deleted file mode 100644 index b9cb192..0000000 Binary files a/.cache/clangd/index/readable_pipe.hpp.4882300A55637051.idx and /dev/null differ diff --git a/.cache/clangd/index/receiver.hpp.311515B0CE8C0465.idx b/.cache/clangd/index/receiver.hpp.311515B0CE8C0465.idx deleted file mode 100644 index d63ca2d..0000000 Binary files a/.cache/clangd/index/receiver.hpp.311515B0CE8C0465.idx and /dev/null differ diff --git a/.cache/clangd/index/receiver_invocation_error.hpp.A7EEA8311171A625.idx b/.cache/clangd/index/receiver_invocation_error.hpp.A7EEA8311171A625.idx deleted file mode 100644 index ae7e796..0000000 Binary files a/.cache/clangd/index/receiver_invocation_error.hpp.A7EEA8311171A625.idx and /dev/null differ diff --git a/.cache/clangd/index/receiver_invocation_error.ipp.114FC487DF7A5AA2.idx b/.cache/clangd/index/receiver_invocation_error.ipp.114FC487DF7A5AA2.idx deleted file mode 100644 index 4b4d63c..0000000 Binary files a/.cache/clangd/index/receiver_invocation_error.ipp.114FC487DF7A5AA2.idx and /dev/null differ diff --git a/.cache/clangd/index/recycling_allocator.hpp.5161461526B09C13.idx b/.cache/clangd/index/recycling_allocator.hpp.5161461526B09C13.idx deleted file mode 100644 index 1d8dbf0..0000000 Binary files a/.cache/clangd/index/recycling_allocator.hpp.5161461526B09C13.idx and /dev/null differ diff --git a/.cache/clangd/index/recycling_allocator.hpp.F5DCCA167B8704A8.idx b/.cache/clangd/index/recycling_allocator.hpp.F5DCCA167B8704A8.idx deleted file mode 100644 index 73a82f2..0000000 Binary files a/.cache/clangd/index/recycling_allocator.hpp.F5DCCA167B8704A8.idx and /dev/null differ diff --git a/.cache/clangd/index/redirect_error.hpp.AE490C8DBE660FEB.idx b/.cache/clangd/index/redirect_error.hpp.AE490C8DBE660FEB.idx deleted file mode 100644 index 11d96e3..0000000 Binary files a/.cache/clangd/index/redirect_error.hpp.AE490C8DBE660FEB.idx and /dev/null differ diff --git a/.cache/clangd/index/redirect_error.hpp.DF111A320F8B81D0.idx b/.cache/clangd/index/redirect_error.hpp.DF111A320F8B81D0.idx deleted file mode 100644 index a5a32a9..0000000 Binary files a/.cache/clangd/index/redirect_error.hpp.DF111A320F8B81D0.idx and /dev/null differ diff --git a/.cache/clangd/index/regex_fwd.hpp.7690750BD8982718.idx b/.cache/clangd/index/regex_fwd.hpp.7690750BD8982718.idx deleted file mode 100644 index 1677251..0000000 Binary files a/.cache/clangd/index/regex_fwd.hpp.7690750BD8982718.idx and /dev/null differ diff --git a/.cache/clangd/index/registered_buffer.hpp.CCEE5794315FA281.idx b/.cache/clangd/index/registered_buffer.hpp.CCEE5794315FA281.idx deleted file mode 100644 index df891a4..0000000 Binary files a/.cache/clangd/index/registered_buffer.hpp.CCEE5794315FA281.idx and /dev/null differ diff --git a/.cache/clangd/index/relationship.hpp.146DBCC91967D0DE.idx b/.cache/clangd/index/relationship.hpp.146DBCC91967D0DE.idx deleted file mode 100644 index 27e7931..0000000 Binary files a/.cache/clangd/index/relationship.hpp.146DBCC91967D0DE.idx and /dev/null differ diff --git a/.cache/clangd/index/require.hpp.AF3B948DCACF5FBE.idx b/.cache/clangd/index/require.hpp.AF3B948DCACF5FBE.idx deleted file mode 100644 index d793a88..0000000 Binary files a/.cache/clangd/index/require.hpp.AF3B948DCACF5FBE.idx and /dev/null differ diff --git a/.cache/clangd/index/require_concept.hpp.F105626E83B2F342.idx b/.cache/clangd/index/require_concept.hpp.F105626E83B2F342.idx deleted file mode 100644 index 2a243de..0000000 Binary files a/.cache/clangd/index/require_concept.hpp.F105626E83B2F342.idx and /dev/null differ diff --git a/.cache/clangd/index/require_concept_free.hpp.3FA513138A972D9F.idx b/.cache/clangd/index/require_concept_free.hpp.3FA513138A972D9F.idx deleted file mode 100644 index d3566ed..0000000 Binary files a/.cache/clangd/index/require_concept_free.hpp.3FA513138A972D9F.idx and /dev/null differ diff --git a/.cache/clangd/index/require_concept_member.hpp.E36BECD944ACB9B1.idx b/.cache/clangd/index/require_concept_member.hpp.E36BECD944ACB9B1.idx deleted file mode 100644 index d65258b..0000000 Binary files a/.cache/clangd/index/require_concept_member.hpp.E36BECD944ACB9B1.idx and /dev/null differ diff --git a/.cache/clangd/index/require_free.hpp.7F0780F6E5EE9785.idx b/.cache/clangd/index/require_free.hpp.7F0780F6E5EE9785.idx deleted file mode 100644 index 0781c50..0000000 Binary files a/.cache/clangd/index/require_free.hpp.7F0780F6E5EE9785.idx and /dev/null differ diff --git a/.cache/clangd/index/require_member.hpp.50E8D4CC8FA84E8F.idx b/.cache/clangd/index/require_member.hpp.50E8D4CC8FA84E8F.idx deleted file mode 100644 index c3f6710..0000000 Binary files a/.cache/clangd/index/require_member.hpp.50E8D4CC8FA84E8F.idx and /dev/null differ diff --git a/.cache/clangd/index/resolve_endpoint_op.hpp.E0DCCDE560259CD0.idx b/.cache/clangd/index/resolve_endpoint_op.hpp.E0DCCDE560259CD0.idx deleted file mode 100644 index ad80abc..0000000 Binary files a/.cache/clangd/index/resolve_endpoint_op.hpp.E0DCCDE560259CD0.idx and /dev/null differ diff --git a/.cache/clangd/index/resolve_op.hpp.9D844A763D73DE82.idx b/.cache/clangd/index/resolve_op.hpp.9D844A763D73DE82.idx deleted file mode 100644 index 4cb0bfd..0000000 Binary files a/.cache/clangd/index/resolve_op.hpp.9D844A763D73DE82.idx and /dev/null differ diff --git a/.cache/clangd/index/resolve_query_op.hpp.5CC2A6A1031AE386.idx b/.cache/clangd/index/resolve_query_op.hpp.5CC2A6A1031AE386.idx deleted file mode 100644 index 492d354..0000000 Binary files a/.cache/clangd/index/resolve_query_op.hpp.5CC2A6A1031AE386.idx and /dev/null differ diff --git a/.cache/clangd/index/resolver_base.hpp.D55064E1C7919614.idx b/.cache/clangd/index/resolver_base.hpp.D55064E1C7919614.idx deleted file mode 100644 index a86a4af..0000000 Binary files a/.cache/clangd/index/resolver_base.hpp.D55064E1C7919614.idx and /dev/null differ diff --git a/.cache/clangd/index/resolver_query_base.hpp.53011F9B5F440D59.idx b/.cache/clangd/index/resolver_query_base.hpp.53011F9B5F440D59.idx deleted file mode 100644 index 8be533a..0000000 Binary files a/.cache/clangd/index/resolver_query_base.hpp.53011F9B5F440D59.idx and /dev/null differ diff --git a/.cache/clangd/index/resolver_service.hpp.5909B1CEC27C70A6.idx b/.cache/clangd/index/resolver_service.hpp.5909B1CEC27C70A6.idx deleted file mode 100644 index caa9afb..0000000 Binary files a/.cache/clangd/index/resolver_service.hpp.5909B1CEC27C70A6.idx and /dev/null differ diff --git a/.cache/clangd/index/resolver_service_base.hpp.47939E4F8FEBB565.idx b/.cache/clangd/index/resolver_service_base.hpp.47939E4F8FEBB565.idx deleted file mode 100644 index 16092be..0000000 Binary files a/.cache/clangd/index/resolver_service_base.hpp.47939E4F8FEBB565.idx and /dev/null differ diff --git a/.cache/clangd/index/resolver_service_base.ipp.98BE24CDEAE35B67.idx b/.cache/clangd/index/resolver_service_base.ipp.98BE24CDEAE35B67.idx deleted file mode 100644 index da6f556..0000000 Binary files a/.cache/clangd/index/resolver_service_base.ipp.98BE24CDEAE35B67.idx and /dev/null differ diff --git a/.cache/clangd/index/schedule.hpp.9DAC9406FF44683C.idx b/.cache/clangd/index/schedule.hpp.9DAC9406FF44683C.idx deleted file mode 100644 index 98462ec..0000000 Binary files a/.cache/clangd/index/schedule.hpp.9DAC9406FF44683C.idx and /dev/null differ diff --git a/.cache/clangd/index/schedule_free.hpp.2CBDAE8BD0034787.idx b/.cache/clangd/index/schedule_free.hpp.2CBDAE8BD0034787.idx deleted file mode 100644 index 931ac16..0000000 Binary files a/.cache/clangd/index/schedule_free.hpp.2CBDAE8BD0034787.idx and /dev/null differ diff --git a/.cache/clangd/index/schedule_member.hpp.6CBCE88007D35B9A.idx b/.cache/clangd/index/schedule_member.hpp.6CBCE88007D35B9A.idx deleted file mode 100644 index 954d34f..0000000 Binary files a/.cache/clangd/index/schedule_member.hpp.6CBCE88007D35B9A.idx and /dev/null differ diff --git a/.cache/clangd/index/scheduler.hpp.59F12B417A213B6F.idx b/.cache/clangd/index/scheduler.hpp.59F12B417A213B6F.idx deleted file mode 100644 index 711569c..0000000 Binary files a/.cache/clangd/index/scheduler.hpp.59F12B417A213B6F.idx and /dev/null differ diff --git a/.cache/clangd/index/scheduler.hpp.9770595873B381F9.idx b/.cache/clangd/index/scheduler.hpp.9770595873B381F9.idx deleted file mode 100644 index 9b86a90..0000000 Binary files a/.cache/clangd/index/scheduler.hpp.9770595873B381F9.idx and /dev/null differ diff --git a/.cache/clangd/index/scheduler.ipp.72CBD707B6C0BE2A.idx b/.cache/clangd/index/scheduler.ipp.72CBD707B6C0BE2A.idx deleted file mode 100644 index 3695828..0000000 Binary files a/.cache/clangd/index/scheduler.ipp.72CBD707B6C0BE2A.idx and /dev/null differ diff --git a/.cache/clangd/index/scheduler_operation.hpp.D58DD859375FA6FC.idx b/.cache/clangd/index/scheduler_operation.hpp.D58DD859375FA6FC.idx deleted file mode 100644 index e695653..0000000 Binary files a/.cache/clangd/index/scheduler_operation.hpp.D58DD859375FA6FC.idx and /dev/null differ diff --git a/.cache/clangd/index/scheduler_task.hpp.995555388D1750AA.idx b/.cache/clangd/index/scheduler_task.hpp.995555388D1750AA.idx deleted file mode 100644 index 940e3e1..0000000 Binary files a/.cache/clangd/index/scheduler_task.hpp.995555388D1750AA.idx and /dev/null differ diff --git a/.cache/clangd/index/scheduler_thread_info.hpp.CA08FDF55BE9060A.idx b/.cache/clangd/index/scheduler_thread_info.hpp.CA08FDF55BE9060A.idx deleted file mode 100644 index bc80f5e..0000000 Binary files a/.cache/clangd/index/scheduler_thread_info.hpp.CA08FDF55BE9060A.idx and /dev/null differ diff --git a/.cache/clangd/index/scoped_lock.hpp.9206AF85CA74211D.idx b/.cache/clangd/index/scoped_lock.hpp.9206AF85CA74211D.idx deleted file mode 100644 index d38f66e..0000000 Binary files a/.cache/clangd/index/scoped_lock.hpp.9206AF85CA74211D.idx and /dev/null differ diff --git a/.cache/clangd/index/scoped_ptr.hpp.6102BAE2A70CF721.idx b/.cache/clangd/index/scoped_ptr.hpp.6102BAE2A70CF721.idx deleted file mode 100644 index bfa291a..0000000 Binary files a/.cache/clangd/index/scoped_ptr.hpp.6102BAE2A70CF721.idx and /dev/null differ diff --git a/.cache/clangd/index/scopestack.cpp.F1A3B5BEC0B49FA6.idx b/.cache/clangd/index/scopestack.cpp.F1A3B5BEC0B49FA6.idx deleted file mode 100644 index adc0824..0000000 Binary files a/.cache/clangd/index/scopestack.cpp.F1A3B5BEC0B49FA6.idx and /dev/null differ diff --git a/.cache/clangd/index/scopestack.h.2EFC46A33BEC83E5.idx b/.cache/clangd/index/scopestack.h.2EFC46A33BEC83E5.idx deleted file mode 100644 index d05627c..0000000 Binary files a/.cache/clangd/index/scopestack.h.2EFC46A33BEC83E5.idx and /dev/null differ diff --git a/.cache/clangd/index/script.h.C248FE8CD99881D2.idx b/.cache/clangd/index/script.h.C248FE8CD99881D2.idx deleted file mode 100644 index 7ae7ae0..0000000 Binary files a/.cache/clangd/index/script.h.C248FE8CD99881D2.idx and /dev/null differ diff --git a/.cache/clangd/index/scriptsection.cpp.DFB83F538C736A1B.idx b/.cache/clangd/index/scriptsection.cpp.DFB83F538C736A1B.idx deleted file mode 100644 index 519d4eb..0000000 Binary files a/.cache/clangd/index/scriptsection.cpp.DFB83F538C736A1B.idx and /dev/null differ diff --git a/.cache/clangd/index/scriptsection.h.F62E80F6A6CC4955.idx b/.cache/clangd/index/scriptsection.h.F62E80F6A6CC4955.idx deleted file mode 100644 index 22f5866..0000000 Binary files a/.cache/clangd/index/scriptsection.h.F62E80F6A6CC4955.idx and /dev/null differ diff --git a/.cache/clangd/index/select_interrupter.hpp.AB7E8640DF1DD54D.idx b/.cache/clangd/index/select_interrupter.hpp.AB7E8640DF1DD54D.idx deleted file mode 100644 index 7f74309..0000000 Binary files a/.cache/clangd/index/select_interrupter.hpp.AB7E8640DF1DD54D.idx and /dev/null differ diff --git a/.cache/clangd/index/sender.hpp.EEF30BB2C6970A97.idx b/.cache/clangd/index/sender.hpp.EEF30BB2C6970A97.idx deleted file mode 100644 index 420228e..0000000 Binary files a/.cache/clangd/index/sender.hpp.EEF30BB2C6970A97.idx and /dev/null differ diff --git a/.cache/clangd/index/seq_packet_protocol.hpp.78D398E1A1D6F6C7.idx b/.cache/clangd/index/seq_packet_protocol.hpp.78D398E1A1D6F6C7.idx deleted file mode 100644 index 85b14ed..0000000 Binary files a/.cache/clangd/index/seq_packet_protocol.hpp.78D398E1A1D6F6C7.idx and /dev/null differ diff --git a/.cache/clangd/index/seq_packet_protocol.hpp.8FE69449787F92CA.idx b/.cache/clangd/index/seq_packet_protocol.hpp.8FE69449787F92CA.idx deleted file mode 100644 index 342c4d4..0000000 Binary files a/.cache/clangd/index/seq_packet_protocol.hpp.8FE69449787F92CA.idx and /dev/null differ diff --git a/.cache/clangd/index/serial_port.hpp.F8FE53EC6797360A.idx b/.cache/clangd/index/serial_port.hpp.F8FE53EC6797360A.idx deleted file mode 100644 index 777b3eb..0000000 Binary files a/.cache/clangd/index/serial_port.hpp.F8FE53EC6797360A.idx and /dev/null differ diff --git a/.cache/clangd/index/serial_port_base.hpp.6280945A4D9C32B3.idx b/.cache/clangd/index/serial_port_base.hpp.6280945A4D9C32B3.idx deleted file mode 100644 index acf7cf5..0000000 Binary files a/.cache/clangd/index/serial_port_base.hpp.6280945A4D9C32B3.idx and /dev/null differ diff --git a/.cache/clangd/index/serial_port_base.hpp.8E1A19CF091DCF63.idx b/.cache/clangd/index/serial_port_base.hpp.8E1A19CF091DCF63.idx deleted file mode 100644 index 15f5e4d..0000000 Binary files a/.cache/clangd/index/serial_port_base.hpp.8E1A19CF091DCF63.idx and /dev/null differ diff --git a/.cache/clangd/index/serial_port_base.ipp.3A18028A3B0DF5BE.idx b/.cache/clangd/index/serial_port_base.ipp.3A18028A3B0DF5BE.idx deleted file mode 100644 index cfc92ed..0000000 Binary files a/.cache/clangd/index/serial_port_base.ipp.3A18028A3B0DF5BE.idx and /dev/null differ diff --git a/.cache/clangd/index/service_registry.hpp.01AFB5B927793888.idx b/.cache/clangd/index/service_registry.hpp.01AFB5B927793888.idx deleted file mode 100644 index 01c2433..0000000 Binary files a/.cache/clangd/index/service_registry.hpp.01AFB5B927793888.idx and /dev/null differ diff --git a/.cache/clangd/index/service_registry.hpp.EAB7026293A43C0C.idx b/.cache/clangd/index/service_registry.hpp.EAB7026293A43C0C.idx deleted file mode 100644 index 873865e..0000000 Binary files a/.cache/clangd/index/service_registry.hpp.EAB7026293A43C0C.idx and /dev/null differ diff --git a/.cache/clangd/index/service_registry.ipp.F7238A2CD7BB8676.idx b/.cache/clangd/index/service_registry.ipp.F7238A2CD7BB8676.idx deleted file mode 100644 index 0dcd6e8..0000000 Binary files a/.cache/clangd/index/service_registry.ipp.F7238A2CD7BB8676.idx and /dev/null differ diff --git a/.cache/clangd/index/set_done.hpp.8A1BA704FAFB5397.idx b/.cache/clangd/index/set_done.hpp.8A1BA704FAFB5397.idx deleted file mode 100644 index f547933..0000000 Binary files a/.cache/clangd/index/set_done.hpp.8A1BA704FAFB5397.idx and /dev/null differ diff --git a/.cache/clangd/index/set_done_free.hpp.B5733C49A66E3DE4.idx b/.cache/clangd/index/set_done_free.hpp.B5733C49A66E3DE4.idx deleted file mode 100644 index 3a2d99d..0000000 Binary files a/.cache/clangd/index/set_done_free.hpp.B5733C49A66E3DE4.idx and /dev/null differ diff --git a/.cache/clangd/index/set_done_member.hpp.32EC1DA1B7AA2C77.idx b/.cache/clangd/index/set_done_member.hpp.32EC1DA1B7AA2C77.idx deleted file mode 100644 index 41ad83d..0000000 Binary files a/.cache/clangd/index/set_done_member.hpp.32EC1DA1B7AA2C77.idx and /dev/null differ diff --git a/.cache/clangd/index/set_error.hpp.22BE3B57334ED0FB.idx b/.cache/clangd/index/set_error.hpp.22BE3B57334ED0FB.idx deleted file mode 100644 index 346f87b..0000000 Binary files a/.cache/clangd/index/set_error.hpp.22BE3B57334ED0FB.idx and /dev/null differ diff --git a/.cache/clangd/index/set_error_free.hpp.F42F351543DC26CF.idx b/.cache/clangd/index/set_error_free.hpp.F42F351543DC26CF.idx deleted file mode 100644 index 8932357..0000000 Binary files a/.cache/clangd/index/set_error_free.hpp.F42F351543DC26CF.idx and /dev/null differ diff --git a/.cache/clangd/index/set_error_member.hpp.21A5C4DEA0298C8D.idx b/.cache/clangd/index/set_error_member.hpp.21A5C4DEA0298C8D.idx deleted file mode 100644 index d4d362f..0000000 Binary files a/.cache/clangd/index/set_error_member.hpp.21A5C4DEA0298C8D.idx and /dev/null differ diff --git a/.cache/clangd/index/set_value.hpp.3F5D9A531578D2C8.idx b/.cache/clangd/index/set_value.hpp.3F5D9A531578D2C8.idx deleted file mode 100644 index e2b5aa9..0000000 Binary files a/.cache/clangd/index/set_value.hpp.3F5D9A531578D2C8.idx and /dev/null differ diff --git a/.cache/clangd/index/set_value_free.hpp.BD2F6BE457E9228E.idx b/.cache/clangd/index/set_value_free.hpp.BD2F6BE457E9228E.idx deleted file mode 100644 index 9a26845..0000000 Binary files a/.cache/clangd/index/set_value_free.hpp.BD2F6BE457E9228E.idx and /dev/null differ diff --git a/.cache/clangd/index/set_value_member.hpp.0F79734F323F4263.idx b/.cache/clangd/index/set_value_member.hpp.0F79734F323F4263.idx deleted file mode 100644 index d389917..0000000 Binary files a/.cache/clangd/index/set_value_member.hpp.0F79734F323F4263.idx and /dev/null differ diff --git a/.cache/clangd/index/signal_blocker.hpp.4DD8491DE2DA33F5.idx b/.cache/clangd/index/signal_blocker.hpp.4DD8491DE2DA33F5.idx deleted file mode 100644 index 29023f4..0000000 Binary files a/.cache/clangd/index/signal_blocker.hpp.4DD8491DE2DA33F5.idx and /dev/null differ diff --git a/.cache/clangd/index/signal_handler.hpp.F4A2D8F1EC9123B6.idx b/.cache/clangd/index/signal_handler.hpp.F4A2D8F1EC9123B6.idx deleted file mode 100644 index 4cf3227..0000000 Binary files a/.cache/clangd/index/signal_handler.hpp.F4A2D8F1EC9123B6.idx and /dev/null differ diff --git a/.cache/clangd/index/signal_op.hpp.4805B8345D03097E.idx b/.cache/clangd/index/signal_op.hpp.4805B8345D03097E.idx deleted file mode 100644 index 6370875..0000000 Binary files a/.cache/clangd/index/signal_op.hpp.4805B8345D03097E.idx and /dev/null differ diff --git a/.cache/clangd/index/signal_set.hpp.D95494EA76D48B00.idx b/.cache/clangd/index/signal_set.hpp.D95494EA76D48B00.idx deleted file mode 100644 index 54411f0..0000000 Binary files a/.cache/clangd/index/signal_set.hpp.D95494EA76D48B00.idx and /dev/null differ diff --git a/.cache/clangd/index/signal_set_base.hpp.70FB995F451D06DA.idx b/.cache/clangd/index/signal_set_base.hpp.70FB995F451D06DA.idx deleted file mode 100644 index 9e8e287..0000000 Binary files a/.cache/clangd/index/signal_set_base.hpp.70FB995F451D06DA.idx and /dev/null differ diff --git a/.cache/clangd/index/signal_set_service.hpp.2362CFA560546A16.idx b/.cache/clangd/index/signal_set_service.hpp.2362CFA560546A16.idx deleted file mode 100644 index 3abb013..0000000 Binary files a/.cache/clangd/index/signal_set_service.hpp.2362CFA560546A16.idx and /dev/null differ diff --git a/.cache/clangd/index/signal_set_service.ipp.A5CE58B0A6C6E3EB.idx b/.cache/clangd/index/signal_set_service.ipp.A5CE58B0A6C6E3EB.idx deleted file mode 100644 index 5686bca..0000000 Binary files a/.cache/clangd/index/signal_set_service.ipp.A5CE58B0A6C6E3EB.idx and /dev/null differ diff --git a/.cache/clangd/index/socket_base.hpp.AA19CB10A5CFA2EB.idx b/.cache/clangd/index/socket_base.hpp.AA19CB10A5CFA2EB.idx deleted file mode 100644 index e3dbd43..0000000 Binary files a/.cache/clangd/index/socket_base.hpp.AA19CB10A5CFA2EB.idx and /dev/null differ diff --git a/.cache/clangd/index/socket_holder.hpp.715FDF3163E48944.idx b/.cache/clangd/index/socket_holder.hpp.715FDF3163E48944.idx deleted file mode 100644 index d19d8d1..0000000 Binary files a/.cache/clangd/index/socket_holder.hpp.715FDF3163E48944.idx and /dev/null differ diff --git a/.cache/clangd/index/socket_ops.hpp.01D5F5756F406A93.idx b/.cache/clangd/index/socket_ops.hpp.01D5F5756F406A93.idx deleted file mode 100644 index 0666ae4..0000000 Binary files a/.cache/clangd/index/socket_ops.hpp.01D5F5756F406A93.idx and /dev/null differ diff --git a/.cache/clangd/index/socket_ops.ipp.7F1FEFA56F42D19A.idx b/.cache/clangd/index/socket_ops.ipp.7F1FEFA56F42D19A.idx deleted file mode 100644 index f7bb149..0000000 Binary files a/.cache/clangd/index/socket_ops.ipp.7F1FEFA56F42D19A.idx and /dev/null differ diff --git a/.cache/clangd/index/socket_option.hpp.16466EFEDDEC1FD8.idx b/.cache/clangd/index/socket_option.hpp.16466EFEDDEC1FD8.idx deleted file mode 100644 index 828d34d..0000000 Binary files a/.cache/clangd/index/socket_option.hpp.16466EFEDDEC1FD8.idx and /dev/null differ diff --git a/.cache/clangd/index/socket_option.hpp.86D3F172BAFC1B09.idx b/.cache/clangd/index/socket_option.hpp.86D3F172BAFC1B09.idx deleted file mode 100644 index 0ab0b14..0000000 Binary files a/.cache/clangd/index/socket_option.hpp.86D3F172BAFC1B09.idx and /dev/null differ diff --git a/.cache/clangd/index/socket_types.hpp.48F104BCAEE46D39.idx b/.cache/clangd/index/socket_types.hpp.48F104BCAEE46D39.idx deleted file mode 100644 index 1eaf7a3..0000000 Binary files a/.cache/clangd/index/socket_types.hpp.48F104BCAEE46D39.idx and /dev/null differ diff --git a/.cache/clangd/index/start.hpp.1D29EB9BA6781D47.idx b/.cache/clangd/index/start.hpp.1D29EB9BA6781D47.idx deleted file mode 100644 index 6d38f14..0000000 Binary files a/.cache/clangd/index/start.hpp.1D29EB9BA6781D47.idx and /dev/null differ diff --git a/.cache/clangd/index/start_free.hpp.FD3E18E97AA2CA0B.idx b/.cache/clangd/index/start_free.hpp.FD3E18E97AA2CA0B.idx deleted file mode 100644 index 126ca3a..0000000 Binary files a/.cache/clangd/index/start_free.hpp.FD3E18E97AA2CA0B.idx and /dev/null differ diff --git a/.cache/clangd/index/start_member.hpp.C55D1E2386E47E67.idx b/.cache/clangd/index/start_member.hpp.C55D1E2386E47E67.idx deleted file mode 100644 index 896d071..0000000 Binary files a/.cache/clangd/index/start_member.hpp.C55D1E2386E47E67.idx and /dev/null differ diff --git a/.cache/clangd/index/statement.cpp.F3E3A3CB1F131E7E.idx b/.cache/clangd/index/statement.cpp.F3E3A3CB1F131E7E.idx deleted file mode 100644 index 76df6de..0000000 Binary files a/.cache/clangd/index/statement.cpp.F3E3A3CB1F131E7E.idx and /dev/null differ diff --git a/.cache/clangd/index/statement.h.6DB0FB53F2F1D921.idx b/.cache/clangd/index/statement.h.6DB0FB53F2F1D921.idx deleted file mode 100644 index b97d7fb..0000000 Binary files a/.cache/clangd/index/statement.h.6DB0FB53F2F1D921.idx and /dev/null differ diff --git a/.cache/clangd/index/static_mutex.hpp.7362DF3B9A6C6AF0.idx b/.cache/clangd/index/static_mutex.hpp.7362DF3B9A6C6AF0.idx deleted file mode 100644 index 2a7d1e0..0000000 Binary files a/.cache/clangd/index/static_mutex.hpp.7362DF3B9A6C6AF0.idx and /dev/null differ diff --git a/.cache/clangd/index/static_query.hpp.E754D01BBC6AA7BD.idx b/.cache/clangd/index/static_query.hpp.E754D01BBC6AA7BD.idx deleted file mode 100644 index 88bdc1b..0000000 Binary files a/.cache/clangd/index/static_query.hpp.E754D01BBC6AA7BD.idx and /dev/null differ diff --git a/.cache/clangd/index/static_require.hpp.83B9B61AF91CB346.idx b/.cache/clangd/index/static_require.hpp.83B9B61AF91CB346.idx deleted file mode 100644 index 7e14b97..0000000 Binary files a/.cache/clangd/index/static_require.hpp.83B9B61AF91CB346.idx and /dev/null differ diff --git a/.cache/clangd/index/static_require_concept.hpp.F362C1353FA235A9.idx b/.cache/clangd/index/static_require_concept.hpp.F362C1353FA235A9.idx deleted file mode 100644 index d098e4e..0000000 Binary files a/.cache/clangd/index/static_require_concept.hpp.F362C1353FA235A9.idx and /dev/null differ diff --git a/.cache/clangd/index/static_thread_pool.hpp.21214286797CB8CD.idx b/.cache/clangd/index/static_thread_pool.hpp.21214286797CB8CD.idx deleted file mode 100644 index 070e620..0000000 Binary files a/.cache/clangd/index/static_thread_pool.hpp.21214286797CB8CD.idx and /dev/null differ diff --git a/.cache/clangd/index/stb_image.h.78CCE9C3F167FEC9.idx b/.cache/clangd/index/stb_image.h.78CCE9C3F167FEC9.idx deleted file mode 100644 index a7b145f..0000000 Binary files a/.cache/clangd/index/stb_image.h.78CCE9C3F167FEC9.idx and /dev/null differ diff --git a/.cache/clangd/index/stb_image_write.h.A01860ADBAC27AA1.idx b/.cache/clangd/index/stb_image_write.h.A01860ADBAC27AA1.idx deleted file mode 100644 index c7f8a0b..0000000 Binary files a/.cache/clangd/index/stb_image_write.h.A01860ADBAC27AA1.idx and /dev/null differ diff --git a/.cache/clangd/index/stb_truetype.h.EB7113F901AB6B1F.idx b/.cache/clangd/index/stb_truetype.h.EB7113F901AB6B1F.idx deleted file mode 100644 index 82570f0..0000000 Binary files a/.cache/clangd/index/stb_truetype.h.EB7113F901AB6B1F.idx and /dev/null differ diff --git a/.cache/clangd/index/std_fenced_block.hpp.E043D72E02478B96.idx b/.cache/clangd/index/std_fenced_block.hpp.E043D72E02478B96.idx deleted file mode 100644 index 7992902..0000000 Binary files a/.cache/clangd/index/std_fenced_block.hpp.E043D72E02478B96.idx and /dev/null differ diff --git a/.cache/clangd/index/steady_timer.hpp.5A475A2415125CD2.idx b/.cache/clangd/index/steady_timer.hpp.5A475A2415125CD2.idx deleted file mode 100644 index aebb974..0000000 Binary files a/.cache/clangd/index/steady_timer.hpp.5A475A2415125CD2.idx and /dev/null differ diff --git a/.cache/clangd/index/strand.hpp.41BC87091B29225E.idx b/.cache/clangd/index/strand.hpp.41BC87091B29225E.idx deleted file mode 100644 index 5ba3c3a..0000000 Binary files a/.cache/clangd/index/strand.hpp.41BC87091B29225E.idx and /dev/null differ diff --git a/.cache/clangd/index/strand_executor_service.hpp.19583A94A880EB65.idx b/.cache/clangd/index/strand_executor_service.hpp.19583A94A880EB65.idx deleted file mode 100644 index b0288f6..0000000 Binary files a/.cache/clangd/index/strand_executor_service.hpp.19583A94A880EB65.idx and /dev/null differ diff --git a/.cache/clangd/index/strand_executor_service.hpp.EE84685F2F772FD0.idx b/.cache/clangd/index/strand_executor_service.hpp.EE84685F2F772FD0.idx deleted file mode 100644 index d1a6734..0000000 Binary files a/.cache/clangd/index/strand_executor_service.hpp.EE84685F2F772FD0.idx and /dev/null differ diff --git a/.cache/clangd/index/strand_executor_service.ipp.6EFDC1223F2514BA.idx b/.cache/clangd/index/strand_executor_service.ipp.6EFDC1223F2514BA.idx deleted file mode 100644 index 592e299..0000000 Binary files a/.cache/clangd/index/strand_executor_service.ipp.6EFDC1223F2514BA.idx and /dev/null differ diff --git a/.cache/clangd/index/strand_service.hpp.CB6CF94C7CAA6A05.idx b/.cache/clangd/index/strand_service.hpp.CB6CF94C7CAA6A05.idx deleted file mode 100644 index 84f4514..0000000 Binary files a/.cache/clangd/index/strand_service.hpp.CB6CF94C7CAA6A05.idx and /dev/null differ diff --git a/.cache/clangd/index/strand_service.hpp.E7CDB62A57C047F8.idx b/.cache/clangd/index/strand_service.hpp.E7CDB62A57C047F8.idx deleted file mode 100644 index f58ca0c..0000000 Binary files a/.cache/clangd/index/strand_service.hpp.E7CDB62A57C047F8.idx and /dev/null differ diff --git a/.cache/clangd/index/strand_service.ipp.21BDD6CF484D5B53.idx b/.cache/clangd/index/strand_service.ipp.21BDD6CF484D5B53.idx deleted file mode 100644 index c7be460..0000000 Binary files a/.cache/clangd/index/strand_service.ipp.21BDD6CF484D5B53.idx and /dev/null differ diff --git a/.cache/clangd/index/stream_descriptor.hpp.0A8FEC60D080063B.idx b/.cache/clangd/index/stream_descriptor.hpp.0A8FEC60D080063B.idx deleted file mode 100644 index 6cb4f7b..0000000 Binary files a/.cache/clangd/index/stream_descriptor.hpp.0A8FEC60D080063B.idx and /dev/null differ diff --git a/.cache/clangd/index/stream_file.hpp.30E2E48E33E28B85.idx b/.cache/clangd/index/stream_file.hpp.30E2E48E33E28B85.idx deleted file mode 100644 index 70aeca4..0000000 Binary files a/.cache/clangd/index/stream_file.hpp.30E2E48E33E28B85.idx and /dev/null differ diff --git a/.cache/clangd/index/stream_handle.hpp.F8892E16E70C6792.idx b/.cache/clangd/index/stream_handle.hpp.F8892E16E70C6792.idx deleted file mode 100644 index efcd6b8..0000000 Binary files a/.cache/clangd/index/stream_handle.hpp.F8892E16E70C6792.idx and /dev/null differ diff --git a/.cache/clangd/index/stream_protocol.hpp.5D4FBC2F43454774.idx b/.cache/clangd/index/stream_protocol.hpp.5D4FBC2F43454774.idx deleted file mode 100644 index 3b746d6..0000000 Binary files a/.cache/clangd/index/stream_protocol.hpp.5D4FBC2F43454774.idx and /dev/null differ diff --git a/.cache/clangd/index/stream_protocol.hpp.AB7AE64E55EABC44.idx b/.cache/clangd/index/stream_protocol.hpp.AB7AE64E55EABC44.idx deleted file mode 100644 index abc711f..0000000 Binary files a/.cache/clangd/index/stream_protocol.hpp.AB7AE64E55EABC44.idx and /dev/null differ diff --git a/.cache/clangd/index/streambuf.hpp.A2D83567A5950B41.idx b/.cache/clangd/index/streambuf.hpp.A2D83567A5950B41.idx deleted file mode 100644 index f71e4a6..0000000 Binary files a/.cache/clangd/index/streambuf.hpp.A2D83567A5950B41.idx and /dev/null differ diff --git a/.cache/clangd/index/string_view.hpp.F042FAE87611DA68.idx b/.cache/clangd/index/string_view.hpp.F042FAE87611DA68.idx deleted file mode 100644 index c422120..0000000 Binary files a/.cache/clangd/index/string_view.hpp.F042FAE87611DA68.idx and /dev/null differ diff --git a/.cache/clangd/index/stringobject.cpp.37B3331525B253D7.idx b/.cache/clangd/index/stringobject.cpp.37B3331525B253D7.idx deleted file mode 100644 index 04cbb26..0000000 Binary files a/.cache/clangd/index/stringobject.cpp.37B3331525B253D7.idx and /dev/null differ diff --git a/.cache/clangd/index/stringobject.h.52F1B3DD0F589D6A.idx b/.cache/clangd/index/stringobject.h.52F1B3DD0F589D6A.idx deleted file mode 100644 index 497a34f..0000000 Binary files a/.cache/clangd/index/stringobject.h.52F1B3DD0F589D6A.idx and /dev/null differ diff --git a/.cache/clangd/index/submit.hpp.402724E3F9EC51C4.idx b/.cache/clangd/index/submit.hpp.402724E3F9EC51C4.idx deleted file mode 100644 index 7a5d771..0000000 Binary files a/.cache/clangd/index/submit.hpp.402724E3F9EC51C4.idx and /dev/null differ diff --git a/.cache/clangd/index/submit_free.hpp.F138876B5D0EA1F3.idx b/.cache/clangd/index/submit_free.hpp.F138876B5D0EA1F3.idx deleted file mode 100644 index 9f49e51..0000000 Binary files a/.cache/clangd/index/submit_free.hpp.F138876B5D0EA1F3.idx and /dev/null differ diff --git a/.cache/clangd/index/submit_member.hpp.33DD78B71CA82197.idx b/.cache/clangd/index/submit_member.hpp.33DD78B71CA82197.idx deleted file mode 100644 index a711824..0000000 Binary files a/.cache/clangd/index/submit_member.hpp.33DD78B71CA82197.idx and /dev/null differ diff --git a/.cache/clangd/index/submit_receiver.hpp.988815CB2D3F8124.idx b/.cache/clangd/index/submit_receiver.hpp.988815CB2D3F8124.idx deleted file mode 100644 index b8ceac2..0000000 Binary files a/.cache/clangd/index/submit_receiver.hpp.988815CB2D3F8124.idx and /dev/null differ diff --git a/.cache/clangd/index/system_context.hpp.958721E2F2101BC5.idx b/.cache/clangd/index/system_context.hpp.958721E2F2101BC5.idx deleted file mode 100644 index 49883e9..0000000 Binary files a/.cache/clangd/index/system_context.hpp.958721E2F2101BC5.idx and /dev/null differ diff --git a/.cache/clangd/index/system_context.hpp.A97162DE132E6A64.idx b/.cache/clangd/index/system_context.hpp.A97162DE132E6A64.idx deleted file mode 100644 index 1eb406d..0000000 Binary files a/.cache/clangd/index/system_context.hpp.A97162DE132E6A64.idx and /dev/null differ diff --git a/.cache/clangd/index/system_context.ipp.DF16AB10FEA65577.idx b/.cache/clangd/index/system_context.ipp.DF16AB10FEA65577.idx deleted file mode 100644 index 87b50d5..0000000 Binary files a/.cache/clangd/index/system_context.ipp.DF16AB10FEA65577.idx and /dev/null differ diff --git a/.cache/clangd/index/system_error.hpp.869B8F4A55EF51DB.idx b/.cache/clangd/index/system_error.hpp.869B8F4A55EF51DB.idx deleted file mode 100644 index d78b843..0000000 Binary files a/.cache/clangd/index/system_error.hpp.869B8F4A55EF51DB.idx and /dev/null differ diff --git a/.cache/clangd/index/system_executor.hpp.EABE8ACE9A6327D1.idx b/.cache/clangd/index/system_executor.hpp.EABE8ACE9A6327D1.idx deleted file mode 100644 index ea17848..0000000 Binary files a/.cache/clangd/index/system_executor.hpp.EABE8ACE9A6327D1.idx and /dev/null differ diff --git a/.cache/clangd/index/system_executor.hpp.FB14D8AEA17033C1.idx b/.cache/clangd/index/system_executor.hpp.FB14D8AEA17033C1.idx deleted file mode 100644 index effbd6f..0000000 Binary files a/.cache/clangd/index/system_executor.hpp.FB14D8AEA17033C1.idx and /dev/null differ diff --git a/.cache/clangd/index/system_timer.hpp.6D3018AF01444569.idx b/.cache/clangd/index/system_timer.hpp.6D3018AF01444569.idx deleted file mode 100644 index b493b4c..0000000 Binary files a/.cache/clangd/index/system_timer.hpp.6D3018AF01444569.idx and /dev/null differ diff --git a/.cache/clangd/index/tcp.hpp.C15ADE2D2DAD009D.idx b/.cache/clangd/index/tcp.hpp.C15ADE2D2DAD009D.idx deleted file mode 100644 index f20f90d..0000000 Binary files a/.cache/clangd/index/tcp.hpp.C15ADE2D2DAD009D.idx and /dev/null differ diff --git a/.cache/clangd/index/tests.cpp.44A6395692BCAA0C.idx b/.cache/clangd/index/tests.cpp.44A6395692BCAA0C.idx deleted file mode 100644 index 625a931..0000000 Binary files a/.cache/clangd/index/tests.cpp.44A6395692BCAA0C.idx and /dev/null differ diff --git a/.cache/clangd/index/tests.cpp.FF3E298D5A8FE185.idx b/.cache/clangd/index/tests.cpp.FF3E298D5A8FE185.idx deleted file mode 100644 index 30883af..0000000 Binary files a/.cache/clangd/index/tests.cpp.FF3E298D5A8FE185.idx and /dev/null differ diff --git a/.cache/clangd/index/this_coro.hpp.803B45BE01709B42.idx b/.cache/clangd/index/this_coro.hpp.803B45BE01709B42.idx deleted file mode 100644 index d5340a5..0000000 Binary files a/.cache/clangd/index/this_coro.hpp.803B45BE01709B42.idx and /dev/null differ diff --git a/.cache/clangd/index/thread.hpp.64F20E438BCA7E10.idx b/.cache/clangd/index/thread.hpp.64F20E438BCA7E10.idx deleted file mode 100644 index 08fc693..0000000 Binary files a/.cache/clangd/index/thread.hpp.64F20E438BCA7E10.idx and /dev/null differ diff --git a/.cache/clangd/index/thread.hpp.E95B1944D22B078B.idx b/.cache/clangd/index/thread.hpp.E95B1944D22B078B.idx deleted file mode 100644 index 5339d75..0000000 Binary files a/.cache/clangd/index/thread.hpp.E95B1944D22B078B.idx and /dev/null differ diff --git a/.cache/clangd/index/thread_context.hpp.6364BF97627923FF.idx b/.cache/clangd/index/thread_context.hpp.6364BF97627923FF.idx deleted file mode 100644 index a5542f8..0000000 Binary files a/.cache/clangd/index/thread_context.hpp.6364BF97627923FF.idx and /dev/null differ diff --git a/.cache/clangd/index/thread_context.ipp.250BD45E9147660A.idx b/.cache/clangd/index/thread_context.ipp.250BD45E9147660A.idx deleted file mode 100644 index 4e75d27..0000000 Binary files a/.cache/clangd/index/thread_context.ipp.250BD45E9147660A.idx and /dev/null differ diff --git a/.cache/clangd/index/thread_group.hpp.1AA72A1287F60095.idx b/.cache/clangd/index/thread_group.hpp.1AA72A1287F60095.idx deleted file mode 100644 index 474cd07..0000000 Binary files a/.cache/clangd/index/thread_group.hpp.1AA72A1287F60095.idx and /dev/null differ diff --git a/.cache/clangd/index/thread_info_base.hpp.400DD8F9552F1DA8.idx b/.cache/clangd/index/thread_info_base.hpp.400DD8F9552F1DA8.idx deleted file mode 100644 index 4206b7d..0000000 Binary files a/.cache/clangd/index/thread_info_base.hpp.400DD8F9552F1DA8.idx and /dev/null differ diff --git a/.cache/clangd/index/thread_pool.hpp.02E95F89998A66E8.idx b/.cache/clangd/index/thread_pool.hpp.02E95F89998A66E8.idx deleted file mode 100644 index 2a3cad2..0000000 Binary files a/.cache/clangd/index/thread_pool.hpp.02E95F89998A66E8.idx and /dev/null differ diff --git a/.cache/clangd/index/thread_pool.hpp.E7D5F6AD5997A58B.idx b/.cache/clangd/index/thread_pool.hpp.E7D5F6AD5997A58B.idx deleted file mode 100644 index ca45690..0000000 Binary files a/.cache/clangd/index/thread_pool.hpp.E7D5F6AD5997A58B.idx and /dev/null differ diff --git a/.cache/clangd/index/thread_pool.ipp.D187EAB02B5A1B67.idx b/.cache/clangd/index/thread_pool.ipp.D187EAB02B5A1B67.idx deleted file mode 100644 index 8f3508d..0000000 Binary files a/.cache/clangd/index/thread_pool.ipp.D187EAB02B5A1B67.idx and /dev/null differ diff --git a/.cache/clangd/index/throw_error.hpp.09573B81CE9999A4.idx b/.cache/clangd/index/throw_error.hpp.09573B81CE9999A4.idx deleted file mode 100644 index 19a8155..0000000 Binary files a/.cache/clangd/index/throw_error.hpp.09573B81CE9999A4.idx and /dev/null differ diff --git a/.cache/clangd/index/throw_error.ipp.394B17FC3A771F24.idx b/.cache/clangd/index/throw_error.ipp.394B17FC3A771F24.idx deleted file mode 100644 index c5029c0..0000000 Binary files a/.cache/clangd/index/throw_error.ipp.394B17FC3A771F24.idx and /dev/null differ diff --git a/.cache/clangd/index/throw_exception.hpp.2B274F8D9B452B81.idx b/.cache/clangd/index/throw_exception.hpp.2B274F8D9B452B81.idx deleted file mode 100644 index 0519d23..0000000 Binary files a/.cache/clangd/index/throw_exception.hpp.2B274F8D9B452B81.idx and /dev/null differ diff --git a/.cache/clangd/index/time_traits.hpp.BE76721F77A0C7D1.idx b/.cache/clangd/index/time_traits.hpp.BE76721F77A0C7D1.idx deleted file mode 100644 index 8c63eeb..0000000 Binary files a/.cache/clangd/index/time_traits.hpp.BE76721F77A0C7D1.idx and /dev/null differ diff --git a/.cache/clangd/index/timer_queue.hpp.BC8A6DF809B4BA52.idx b/.cache/clangd/index/timer_queue.hpp.BC8A6DF809B4BA52.idx deleted file mode 100644 index a667012..0000000 Binary files a/.cache/clangd/index/timer_queue.hpp.BC8A6DF809B4BA52.idx and /dev/null differ diff --git a/.cache/clangd/index/timer_queue_base.hpp.050881478C4D9390.idx b/.cache/clangd/index/timer_queue_base.hpp.050881478C4D9390.idx deleted file mode 100644 index 6e8a985..0000000 Binary files a/.cache/clangd/index/timer_queue_base.hpp.050881478C4D9390.idx and /dev/null differ diff --git a/.cache/clangd/index/timer_queue_ptime.hpp.08450BCAD0614122.idx b/.cache/clangd/index/timer_queue_ptime.hpp.08450BCAD0614122.idx deleted file mode 100644 index 112bffc..0000000 Binary files a/.cache/clangd/index/timer_queue_ptime.hpp.08450BCAD0614122.idx and /dev/null differ diff --git a/.cache/clangd/index/timer_queue_set.hpp.87A8EA24B7A50FDA.idx b/.cache/clangd/index/timer_queue_set.hpp.87A8EA24B7A50FDA.idx deleted file mode 100644 index 1169977..0000000 Binary files a/.cache/clangd/index/timer_queue_set.hpp.87A8EA24B7A50FDA.idx and /dev/null differ diff --git a/.cache/clangd/index/timer_queue_set.ipp.2860B6981A5ACE3B.idx b/.cache/clangd/index/timer_queue_set.ipp.2860B6981A5ACE3B.idx deleted file mode 100644 index 9ec447f..0000000 Binary files a/.cache/clangd/index/timer_queue_set.ipp.2860B6981A5ACE3B.idx and /dev/null differ diff --git a/.cache/clangd/index/timer_scheduler.hpp.241E89C42BEF3817.idx b/.cache/clangd/index/timer_scheduler.hpp.241E89C42BEF3817.idx deleted file mode 100644 index bc67302..0000000 Binary files a/.cache/clangd/index/timer_scheduler.hpp.241E89C42BEF3817.idx and /dev/null differ diff --git a/.cache/clangd/index/timer_scheduler_fwd.hpp.7CDCE190AC64DD75.idx b/.cache/clangd/index/timer_scheduler_fwd.hpp.7CDCE190AC64DD75.idx deleted file mode 100644 index 1642240..0000000 Binary files a/.cache/clangd/index/timer_scheduler_fwd.hpp.7CDCE190AC64DD75.idx and /dev/null differ diff --git a/.cache/clangd/index/tss_ptr.hpp.42378DFB43F5AF58.idx b/.cache/clangd/index/tss_ptr.hpp.42378DFB43F5AF58.idx deleted file mode 100644 index fca30cf..0000000 Binary files a/.cache/clangd/index/tss_ptr.hpp.42378DFB43F5AF58.idx and /dev/null differ diff --git a/.cache/clangd/index/type_traits.hpp.A01DF4342CD7EC7A.idx b/.cache/clangd/index/type_traits.hpp.A01DF4342CD7EC7A.idx deleted file mode 100644 index 6d5ae4e..0000000 Binary files a/.cache/clangd/index/type_traits.hpp.A01DF4342CD7EC7A.idx and /dev/null differ diff --git a/.cache/clangd/index/typegroups.cpp.08272E5986DE29D1.idx b/.cache/clangd/index/typegroups.cpp.08272E5986DE29D1.idx deleted file mode 100644 index cb8f87a..0000000 Binary files a/.cache/clangd/index/typegroups.cpp.08272E5986DE29D1.idx and /dev/null differ diff --git a/.cache/clangd/index/typegroups.h.63F0CFA5E17D84C2.idx b/.cache/clangd/index/typegroups.h.63F0CFA5E17D84C2.idx deleted file mode 100644 index edfecaa..0000000 Binary files a/.cache/clangd/index/typegroups.h.63F0CFA5E17D84C2.idx and /dev/null differ diff --git a/.cache/clangd/index/typemethods.cpp.76BF8B67FE768929.idx b/.cache/clangd/index/typemethods.cpp.76BF8B67FE768929.idx deleted file mode 100644 index 30f374f..0000000 Binary files a/.cache/clangd/index/typemethods.cpp.76BF8B67FE768929.idx and /dev/null differ diff --git a/.cache/clangd/index/typemethods.h.7AB10F8B7B848BCE.idx b/.cache/clangd/index/typemethods.h.7AB10F8B7B848BCE.idx deleted file mode 100644 index a6f7ad4..0000000 Binary files a/.cache/clangd/index/typemethods.h.7AB10F8B7B848BCE.idx and /dev/null differ diff --git a/.cache/clangd/index/typeobject.cpp.EA5AB19CD4B8D320.idx b/.cache/clangd/index/typeobject.cpp.EA5AB19CD4B8D320.idx deleted file mode 100644 index a32bedb..0000000 Binary files a/.cache/clangd/index/typeobject.cpp.EA5AB19CD4B8D320.idx and /dev/null differ diff --git a/.cache/clangd/index/typeobject.h.AD6C272E9AB3AD97.idx b/.cache/clangd/index/typeobject.h.AD6C272E9AB3AD97.idx deleted file mode 100644 index 5515a78..0000000 Binary files a/.cache/clangd/index/typeobject.h.AD6C272E9AB3AD97.idx and /dev/null differ diff --git a/.cache/clangd/index/udp.hpp.62263B6B1939E8DE.idx b/.cache/clangd/index/udp.hpp.62263B6B1939E8DE.idx deleted file mode 100644 index 79973a1..0000000 Binary files a/.cache/clangd/index/udp.hpp.62263B6B1939E8DE.idx and /dev/null differ diff --git a/.cache/clangd/index/unicast.hpp.0EC31E123B8A41E0.idx b/.cache/clangd/index/unicast.hpp.0EC31E123B8A41E0.idx deleted file mode 100644 index 9a7a7a8..0000000 Binary files a/.cache/clangd/index/unicast.hpp.0EC31E123B8A41E0.idx and /dev/null differ diff --git a/.cache/clangd/index/use_awaitable.hpp.A56CAD6AA344A565.idx b/.cache/clangd/index/use_awaitable.hpp.A56CAD6AA344A565.idx deleted file mode 100644 index dd8de1f..0000000 Binary files a/.cache/clangd/index/use_awaitable.hpp.A56CAD6AA344A565.idx and /dev/null differ diff --git a/.cache/clangd/index/use_awaitable.hpp.E72837693E82C277.idx b/.cache/clangd/index/use_awaitable.hpp.E72837693E82C277.idx deleted file mode 100644 index 1e8dda8..0000000 Binary files a/.cache/clangd/index/use_awaitable.hpp.E72837693E82C277.idx and /dev/null differ diff --git a/.cache/clangd/index/use_future.hpp.424B6583474980B0.idx b/.cache/clangd/index/use_future.hpp.424B6583474980B0.idx deleted file mode 100644 index 677ed24..0000000 Binary files a/.cache/clangd/index/use_future.hpp.424B6583474980B0.idx and /dev/null differ diff --git a/.cache/clangd/index/use_future.hpp.AB86FE12777A1205.idx b/.cache/clangd/index/use_future.hpp.AB86FE12777A1205.idx deleted file mode 100644 index 4269a26..0000000 Binary files a/.cache/clangd/index/use_future.hpp.AB86FE12777A1205.idx and /dev/null differ diff --git a/.cache/clangd/index/uses_executor.hpp.525249EFE73D40D3.idx b/.cache/clangd/index/uses_executor.hpp.525249EFE73D40D3.idx deleted file mode 100644 index a76e8f4..0000000 Binary files a/.cache/clangd/index/uses_executor.hpp.525249EFE73D40D3.idx and /dev/null differ diff --git a/.cache/clangd/index/utility.hpp.F9C8F4117AD1FB21.idx b/.cache/clangd/index/utility.hpp.F9C8F4117AD1FB21.idx deleted file mode 100644 index eff3047..0000000 Binary files a/.cache/clangd/index/utility.hpp.F9C8F4117AD1FB21.idx and /dev/null differ diff --git a/.cache/clangd/index/v6_only.hpp.0577DFC561EC74D3.idx b/.cache/clangd/index/v6_only.hpp.0577DFC561EC74D3.idx deleted file mode 100644 index b830e41..0000000 Binary files a/.cache/clangd/index/v6_only.hpp.0577DFC561EC74D3.idx and /dev/null differ diff --git a/.cache/clangd/index/variadic_templates.hpp.EDBCF42B189DB1C2.idx b/.cache/clangd/index/variadic_templates.hpp.EDBCF42B189DB1C2.idx deleted file mode 100644 index ccaee5d..0000000 Binary files a/.cache/clangd/index/variadic_templates.hpp.EDBCF42B189DB1C2.idx and /dev/null differ diff --git a/.cache/clangd/index/version.hpp.79F63F4E4FC643CC.idx b/.cache/clangd/index/version.hpp.79F63F4E4FC643CC.idx deleted file mode 100644 index 22fd824..0000000 Binary files a/.cache/clangd/index/version.hpp.79F63F4E4FC643CC.idx and /dev/null differ diff --git a/.cache/clangd/index/visualinfo.c.56725BF56C40AC5F.idx b/.cache/clangd/index/visualinfo.c.56725BF56C40AC5F.idx deleted file mode 100644 index 04488f8..0000000 Binary files a/.cache/clangd/index/visualinfo.c.56725BF56C40AC5F.idx and /dev/null differ diff --git a/.cache/clangd/index/void_receiver.hpp.D9099744B3B1A50A.idx b/.cache/clangd/index/void_receiver.hpp.D9099744B3B1A50A.idx deleted file mode 100644 index f6d9856..0000000 Binary files a/.cache/clangd/index/void_receiver.hpp.D9099744B3B1A50A.idx and /dev/null differ diff --git a/.cache/clangd/index/vulkan.c.EB64EA4FBCE518B2.idx b/.cache/clangd/index/vulkan.c.EB64EA4FBCE518B2.idx deleted file mode 100644 index e0a6cb3..0000000 Binary files a/.cache/clangd/index/vulkan.c.EB64EA4FBCE518B2.idx and /dev/null differ diff --git a/.cache/clangd/index/wait_handler.hpp.02597297B3D35AFB.idx b/.cache/clangd/index/wait_handler.hpp.02597297B3D35AFB.idx deleted file mode 100644 index f700050..0000000 Binary files a/.cache/clangd/index/wait_handler.hpp.02597297B3D35AFB.idx and /dev/null differ diff --git a/.cache/clangd/index/wait_op.hpp.14EEC4F5A5614656.idx b/.cache/clangd/index/wait_op.hpp.14EEC4F5A5614656.idx deleted file mode 100644 index 58ab9fc..0000000 Binary files a/.cache/clangd/index/wait_op.hpp.14EEC4F5A5614656.idx and /dev/null differ diff --git a/.cache/clangd/index/wait_traits.hpp.49711483A892CABA.idx b/.cache/clangd/index/wait_traits.hpp.49711483A892CABA.idx deleted file mode 100644 index 83fbf6d..0000000 Binary files a/.cache/clangd/index/wait_traits.hpp.49711483A892CABA.idx and /dev/null differ diff --git a/.cache/clangd/index/window.c.AC8B296286C10B1A.idx b/.cache/clangd/index/window.c.AC8B296286C10B1A.idx deleted file mode 100644 index ebda1c9..0000000 Binary files a/.cache/clangd/index/window.c.AC8B296286C10B1A.idx and /dev/null differ diff --git a/.cache/clangd/index/winsock_init.hpp.48FB7DD19A356684.idx b/.cache/clangd/index/winsock_init.hpp.48FB7DD19A356684.idx deleted file mode 100644 index cc27bfd..0000000 Binary files a/.cache/clangd/index/winsock_init.hpp.48FB7DD19A356684.idx and /dev/null differ diff --git a/.cache/clangd/index/work_dispatcher.hpp.3C6AC6E1AB1E8BBB.idx b/.cache/clangd/index/work_dispatcher.hpp.3C6AC6E1AB1E8BBB.idx deleted file mode 100644 index b71f7b3..0000000 Binary files a/.cache/clangd/index/work_dispatcher.hpp.3C6AC6E1AB1E8BBB.idx and /dev/null differ diff --git a/.cache/clangd/index/wrapped_handler.hpp.D25FFEE7DC438665.idx b/.cache/clangd/index/wrapped_handler.hpp.D25FFEE7DC438665.idx deleted file mode 100644 index e735fd0..0000000 Binary files a/.cache/clangd/index/wrapped_handler.hpp.D25FFEE7DC438665.idx and /dev/null differ diff --git a/.cache/clangd/index/writable_pipe.hpp.EAC451F164DD95BF.idx b/.cache/clangd/index/writable_pipe.hpp.EAC451F164DD95BF.idx deleted file mode 100644 index cd04056..0000000 Binary files a/.cache/clangd/index/writable_pipe.hpp.EAC451F164DD95BF.idx and /dev/null differ diff --git a/.cache/clangd/index/write.hpp.50D74AA774A152D2.idx b/.cache/clangd/index/write.hpp.50D74AA774A152D2.idx deleted file mode 100644 index 36d9f2c..0000000 Binary files a/.cache/clangd/index/write.hpp.50D74AA774A152D2.idx and /dev/null differ diff --git a/.cache/clangd/index/write.hpp.AFBBA4DA6D5FA570.idx b/.cache/clangd/index/write.hpp.AFBBA4DA6D5FA570.idx deleted file mode 100644 index 3b77751..0000000 Binary files a/.cache/clangd/index/write.hpp.AFBBA4DA6D5FA570.idx and /dev/null differ diff --git a/.cache/clangd/index/write_at.hpp.11BF8131CFC5F013.idx b/.cache/clangd/index/write_at.hpp.11BF8131CFC5F013.idx deleted file mode 100644 index c72ee80..0000000 Binary files a/.cache/clangd/index/write_at.hpp.11BF8131CFC5F013.idx and /dev/null differ diff --git a/.cache/clangd/index/write_at.hpp.314A7708AEF370E0.idx b/.cache/clangd/index/write_at.hpp.314A7708AEF370E0.idx deleted file mode 100644 index 838a7ba..0000000 Binary files a/.cache/clangd/index/write_at.hpp.314A7708AEF370E0.idx and /dev/null differ diff --git a/.cache/clangd/index/x11_init.c.2A258B7044B8D5EC.idx b/.cache/clangd/index/x11_init.c.2A258B7044B8D5EC.idx deleted file mode 100644 index 8a4ae15..0000000 Binary files a/.cache/clangd/index/x11_init.c.2A258B7044B8D5EC.idx and /dev/null differ diff --git a/.cache/clangd/index/x11_monitor.c.498D78B41E9D4C8F.idx b/.cache/clangd/index/x11_monitor.c.498D78B41E9D4C8F.idx deleted file mode 100644 index 5e925ea..0000000 Binary files a/.cache/clangd/index/x11_monitor.c.498D78B41E9D4C8F.idx and /dev/null differ diff --git a/.cache/clangd/index/x11_platform.h.342EFF7EE177AE50.idx b/.cache/clangd/index/x11_platform.h.342EFF7EE177AE50.idx deleted file mode 100644 index a5313cc..0000000 Binary files a/.cache/clangd/index/x11_platform.h.342EFF7EE177AE50.idx and /dev/null differ diff --git a/.cache/clangd/index/x11_window.c.8E8C4AB2AFA031FE.idx b/.cache/clangd/index/x11_window.c.8E8C4AB2AFA031FE.idx deleted file mode 100644 index a27a8db..0000000 Binary files a/.cache/clangd/index/x11_window.c.8E8C4AB2AFA031FE.idx and /dev/null differ diff --git a/.cache/clangd/index/xkb_unicode.c.EE6E7507462EBF1F.idx b/.cache/clangd/index/xkb_unicode.c.EE6E7507462EBF1F.idx deleted file mode 100644 index f50eb1e..0000000 Binary files a/.cache/clangd/index/xkb_unicode.c.EE6E7507462EBF1F.idx and /dev/null differ diff --git a/.cache/clangd/index/xkb_unicode.h.F546049AF1328BFD.idx b/.cache/clangd/index/xkb_unicode.h.F546049AF1328BFD.idx deleted file mode 100644 index dea2585..0000000 Binary files a/.cache/clangd/index/xkb_unicode.h.F546049AF1328BFD.idx and /dev/null differ diff --git a/.clang-format b/.clang-format index 6270299..e5e9a2b 100644 --- a/.clang-format +++ b/.clang-format @@ -1,14 +1,14 @@ --- BasedOnStyle: LLVM AccessModifierOffset: -2 -AlignAfterOpenBracket: Align -AlignArrayOfStructures: Left +AlignAfterOpenBracket: BlockIndent +AlignArrayOfStructures: None AlignConsecutiveAssignments: Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCompound: false - PadOperators: true + PadOperators: false AlignConsecutiveBitFields: Enabled: false AcrossEmptyLines: false @@ -22,23 +22,22 @@ AlignConsecutiveDeclarations: AlignCompound: false PadOperators: false AlignConsecutiveMacros: - Enabled: true + Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCompound: false PadOperators: false AlignEscapedNewlines: Left AlignOperands: Align -AlignTrailingComments: - Kind: Always - OverEmptyLines: 0 +AlignTrailingComments: true AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: Always +AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: true AllowShortEnumsOnASingleLine: true AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: Never +AllowShortIfStatementsOnASingleLine: AllIfsAndElse AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None @@ -47,13 +46,13 @@ AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: Yes AttributeMacros: - __capability -BinPackArguments: true -BinPackParameters: true +BinPackArguments: false +BinPackParameters: false BitFieldColonSpacing: Both BraceWrapping: - AfterCaseLabel: false - AfterClass: false - AfterControlStatement: Never + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: Always AfterEnum: false AfterFunction: false AfterNamespace: false @@ -69,29 +68,28 @@ BraceWrapping: SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true -BreakAfterAttributes: Never BreakAfterJavaFieldAnnotations: false -BreakArrays: true BreakBeforeBinaryOperators: None BreakBeforeBraces: Attach BreakBeforeConceptDeclarations: Always -BreakBeforeInlineASMColon: OnlyMultiline BreakBeforeTernaryOperators: true -BreakConstructorInitializers: BeforeColon +BreakConstructorInitializers: AfterColon BreakInheritanceList: BeforeColon BreakStringLiterals: true -ColumnLimit: 180 +ColumnLimit: 400 CommentPragmas: "^ IWYU pragma:" CompactNamespaces: false -ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 4 -Cpp11BracedListStyle: true +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 2 +ContinuationIndentWidth: 2 +Cpp11BracedListStyle: false +DeriveLineEnding: true DerivePointerAlignment: false DisableFormat: false EmptyLineAfterAccessModifier: Never EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false -FixNamespaceComments: true +FixNamespaceComments: false ForEachMacros: - foreach - Q_FOREACH @@ -117,28 +115,19 @@ IncludeIsMainSourceRegex: "" IndentAccessModifiers: false IndentCaseBlocks: true IndentCaseLabels: true -IndentExternBlock: Indent +IndentExternBlock: AfterExternBlock IndentGotoLabels: true -IndentPPDirectives: BeforeHash +IndentPPDirectives: None IndentRequiresClause: true IndentWidth: 2 IndentWrappedFunctionNames: false -InsertBraces: true -InsertNewlineAtEOF: true +InsertBraces: false InsertTrailingCommas: None -IntegerLiteralSeparator: - Binary: 0 - BinaryMinDigits: 0 - Decimal: 0 - DecimalMinDigits: 0 - Hex: 0 - HexMinDigits: 0 JavaScriptQuotes: Leave JavaScriptWrapImports: true -KeepEmptyLinesAtTheStartOfBlocks: false +KeepEmptyLinesAtTheStartOfBlocks: true LambdaBodyIndentation: Signature Language: Cpp -LineEnding: DeriveLF MacroBlockBegin: "" MacroBlockEnd: "" MaxEmptyLinesToKeep: 1 @@ -149,7 +138,7 @@ ObjCBreakBeforeNestedBlockParam: true ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true PPIndentWidth: -1 -PackConstructorInitializers: CurrentLine +PackConstructorInitializers: Never PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 @@ -161,25 +150,23 @@ PenaltyExcessCharacter: 1000000 PenaltyIndentedWhitespace: 0 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Left -QualifierAlignment: Custom +QualifierAlignment: Leave ReferenceAlignment: Pointer ReflowComments: true RemoveBracesLLVM: false -RemoveSemicolon: true RequiresClausePosition: OwnLine -RequiresExpressionIndentation: OuterScope -SeparateDefinitionBlocks: Always -ShortNamespaceLines: 1000 +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 SortIncludes: CaseSensitive SortJavaStaticImport: Before -SortUsingDeclarations: LexicographicNumeric +SortUsingDeclarations: true SpaceAfterCStyleCast: true SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: true SpaceAroundPointerQualifiers: Default SpaceBeforeAssignmentOperators: true SpaceBeforeCaseColon: false -SpaceBeforeCpp11BracedList: true +SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements @@ -214,15 +201,11 @@ StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION TabWidth: 2 -UseTab: Never +UseCRLF: false +UseTab: ForContinuationAndIndentation WhitespaceSensitiveMacros: - - BOOST_PP_STRINGIZE - - CF_SWIFT_NAME - - NS_SWIFT_NAME - - PP_STRINGIZE - STRINGIZE -QualifierOrder: - - inline - - static - - const - - type + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME \ No newline at end of file diff --git a/.outdated/graphics/ext/easytab.h b/.outdated/graphics/ext/easytab.h deleted file mode 100644 index 2d39dd4..0000000 --- a/.outdated/graphics/ext/easytab.h +++ /dev/null @@ -1,943 +0,0 @@ -/* - EasyTab.h - Single-header multi-platform tablet library - https://github.com/ApoorvaJ/EasyTab - - ---------------------------------------------------------------------------- - USAGE - ---------------------------------------------------------------------------- - 1) Add the following lines in exactly one of your cpp files to compile the - implementation. - - #define EASYTAB_IMPLEMENTATION - #include "easytab.h" - - 2) Call EasyTab_Load() with correct parameters to initialize EasyTab. These - parameters vary per OS, so look at the function declarations or examples - below. Function returns EASYTAB_OK if initialization was successful. - - 3) Call EasyTab_HandleEvent() in your message-handling code. The function - returns EASYTAB_OK if the message was a tablet message, and - EASYTAB_EVENT_NOT_HANDLED otherwise. - - 4) Call EasyTab_Unload() in your shutdown code. - - 5) Once initialized, you can query tablet state using the EasyTab pointer. - e.g.: - - EasyTab->PosX // X position of the pen - EasyTab->PosY // Y position of the pen - EasyTab->Pressure // Pressure of the pen ranging from 0.0f to 1.0f - - For more info, have a look at the EasyTabInfo struct below. - - - * Add -lXi to compiler options to link XInput on Linux. - - ---------------------------------------------------------------------------- - EXAMPLES - ---------------------------------------------------------------------------- - 1) Windows: - - int CALLBACK WinMain(...) - { - HWND Window; - - ... - - if (EasyTab_Load(Window) != EASYTAB_OK) // Load - { - OutputDebugStringA("Tablet init failed\n"); - } - - ... - - // Once you've set up EasyTab loading, unloading and event handling, - // use the EasyTab variable at any point in your program to access - // the tablet state: - // EasyTab->PosX - // EasyTab->PosY - // EasyTab->Pressure - // For more tablet information, look at the EasyTabInfo struct. - - ... - - EasyTab_Unload(); // Unload - } - - LRESULT CALLBACK WindowProc( - HWND Window, - UINT Message, - WPARAM WParam, - LPARAM LParam) - { - if (EasyTab_HandleEvent(Window, Message, LParam, WParam) == EASYTAB_OK) // Event - { - return true; // Tablet event handled - } - - switch (Message) - { - ... - } - } - - - 2) Linux: - - int main(...) - { - Display* Disp; - Window Win; - - ... - - if (EasyTab_Load(Disp, Win) != EASYTAB_OK) // Load - { - printf("Tablet init failed\n"); - } - - ... - - while (XPending(Disp)) // Event loop - { - XEvent Event; - XNextEvent(XlibDisplay, &Event); - - if (EasyTab_HandleEvent(&Event) == EASYTAB_OK) // Event - { - continue; // Tablet event handled - } - - switch (Event.type) - { - ... - } - } - - ... - - // Once you've set up EasyTab loading, unloading and event handling, - // use the EasyTab variable at any point in your program to access - // the tablet state: - // EasyTab->PosX - // EasyTab->PosY - // EasyTab->Pressure - // For more tablet information, look at the EasyTabInfo struct. - - ... - - EasyTab_Unload(); // Unload - } - - ---------------------------------------------------------------------------- - CREDITS - ---------------------------------------------------------------------------- - Apoorva Joshi apoorvaj.io - Sergio Gonzalez s3rg.io - - This library is coded in the spirit of the stb libraries and follows the stb - guidelines. - -*/ - -// TODO: Null checks and warnings for EasyTab -// TODO: Differentiate between stylus and eraser in the API -// TODO: Linux support for relative mode -// TODO: Documentation for relative mode - -// ============================================================================= -// EasyTab header section -// ============================================================================= - -#ifndef EASYTAB_H -#define EASYTAB_H - -#include -#include -#include - -#ifdef __linux__ -#include -#endif // __linux__ - -#ifdef _WIN32 -#include -#endif // _WIN32 - -typedef enum -{ - EASYTAB_OK = 0, - - // Errors - EASYTAB_MEMORY_ERROR = -1, - EASYTAB_X11_ERROR = -2, - EASYTAB_DLL_LOAD_ERROR = -3, - EASYTAB_WACOM_WIN32_ERROR = -4, - EASYTAB_INVALID_FUNCTION_ERROR = -5, - - EASYTAB_EVENT_NOT_HANDLED = -16, -} EasyTabResult; - -typedef enum -{ - EASYTAB_TRACKING_MODE_SYSTEM = 0, - EASYTAB_TRACKING_MODE_RELATIVE = 1, -} EasyTabTrackingMode; - -#ifdef WIN32 -// ----------------------------------------------------------------------------- -// wintab.h -// ----------------------------------------------------------------------------- -#if 1 - - DECLARE_HANDLE(HMGR); - DECLARE_HANDLE(HCTX); - - typedef DWORD WTPKT; - typedef DWORD FIX32; - - // Messages - #if 1 - - #define WT_DEFBASE 0x7FF0 - #define WT_MAXOFFSET 0xF - - #define _WT_PACKET(b) ((b)+0) - #define _WT_CTXOPEN(b) ((b)+1) - #define _WT_CTXCLOSE(b) ((b)+2) - #define _WT_CTXUPDATE(b) ((b)+3) - #define _WT_CTXOVERLAP(b) ((b)+4) - #define _WT_PROXIMITY(b) ((b)+5) - #define _WT_INFOCHANGE(b) ((b)+6) - #define _WT_CSRCHANGE(b) ((b)+7) /* 1.1 */ - #define _WT_PACKETEXT(b) ((b)+8) /* 1.4 */ - #define _WT_MAX(b) ((b)+WT_MAXOFFSET) - - #define WT_PACKET _WT_PACKET(WT_DEFBASE) - #define WT_CTXOPEN _WT_CTXOPEN(WT_DEFBASE) - #define WT_CTXCLOSE _WT_CTXCLOSE(WT_DEFBASE) - #define WT_CTXUPDATE _WT_CTXUPDATE(WT_DEFBASE) - #define WT_CTXOVERLAP _WT_CTXOVERLAP(WT_DEFBASE) - #define WT_PROXIMITY _WT_PROXIMITY(WT_DEFBASE) - #define WT_INFOCHANGE _WT_INFOCHANGE(WT_DEFBASE) - #define WT_CSRCHANGE _WT_CSRCHANGE(WT_DEFBASE) /* 1.1 */ - #define WT_PACKETEXT _WT_PACKETEXT(WT_DEFBASE) /* 1.4 */ - #define WT_MAX _WT_MAX(WT_DEFBASE) - - #endif // Messages - - // Flags - #if 1 - - #define CTX_NAME 1 - #define CTX_OPTIONS 2 - #define CTX_STATUS 3 - #define CTX_LOCKS 4 - #define CTX_MSGBASE 5 - #define CTX_DEVICE 6 - #define CTX_PKTRATE 7 - #define CTX_PKTDATA 8 - #define CTX_PKTMODE 9 - #define CTX_MOVEMASK 10 - #define CTX_BTNDNMASK 11 - #define CTX_BTNUPMASK 12 - #define CTX_INORGX 13 - #define CTX_INORGY 14 - #define CTX_INORGZ 15 - #define CTX_INEXTX 16 - #define CTX_INEXTY 17 - #define CTX_INEXTZ 18 - #define CTX_OUTORGX 19 - #define CTX_OUTORGY 20 - #define CTX_OUTORGZ 21 - #define CTX_OUTEXTX 22 - #define CTX_OUTEXTY 23 - #define CTX_OUTEXTZ 24 - #define CTX_SENSX 25 - #define CTX_SENSY 26 - #define CTX_SENSZ 27 - #define CTX_SYSMODE 28 - #define CTX_SYSORGX 29 - #define CTX_SYSORGY 30 - #define CTX_SYSEXTX 31 - #define CTX_SYSEXTY 32 - #define CTX_SYSSENSX 33 - #define CTX_SYSSENSY 34 - #define CTX_MAX 34 - - // Context option values - #define CXO_SYSTEM 0x0001 - #define CXO_PEN 0x0002 - #define CXO_MESSAGES 0x0004 - #define CXO_MARGIN 0x8000 - #define CXO_MGNINSIDE 0x4000 - #define CXO_CSRMESSAGES 0x0008 /* 1.1 */ - - #define DVC_NAME 1 - #define DVC_HARDWARE 2 - #define DVC_NCSRTYPES 3 - #define DVC_FIRSTCSR 4 - #define DVC_PKTRATE 5 - #define DVC_PKTDATA 6 - #define DVC_PKTMODE 7 - #define DVC_CSRDATA 8 - #define DVC_XMARGIN 9 - #define DVC_YMARGIN 10 - #define DVC_ZMARGIN 11 - #define DVC_X 12 - #define DVC_Y 13 - #define DVC_Z 14 - #define DVC_NPRESSURE 15 - #define DVC_TPRESSURE 16 - #define DVC_ORIENTATION 17 - #define DVC_ROTATION 18 /* 1.1 */ - #define DVC_PNPID 19 /* 1.1 */ - #define DVC_MAX 19 - - #define PK_CONTEXT 0x0001 // reporting context - #define PK_STATUS 0x0002 // status bits - #define PK_TIME 0x0004 // time stamp - #define PK_CHANGED 0x0008 // change bit vector - #define PK_SERIAL_NUMBER 0x0010 // packet serial number - #define PK_CURSOR 0x0020 // reporting cursor - #define PK_BUTTONS 0x0040 // button information - #define PK_X 0x0080 // x axis - #define PK_Y 0x0100 // y axis - #define PK_Z 0x0200 // z axis - #define PK_NORMAL_PRESSURE 0x0400 // normal or tip pressure - #define PK_TANGENT_PRESSURE 0x0800 // tangential or barrel pressure - #define PK_ORIENTATION 0x1000 // orientation info: tilts - #define PK_ROTATION 0x2000 // rotation info; 1.1 - - // constants for use with pktdef.h - #define PKEXT_ABSOLUTE 1 - #define PKEXT_RELATIVE 2 - - #define WTI_DEFCONTEXT 3 - #define WTI_DEFSYSCTX 4 - #define WTI_DEVICES 100 - #define WTI_DDCTXS 400 /* 1.1 */ - #define WTI_DSCTXS 500 /* 1.1 */ - - #endif // Flags - - typedef struct tagAXIS { - LONG axMin; - LONG axMax; - UINT axUnits; - FIX32 axResolution; - } AXIS, *PAXIS, NEAR *NPAXIS, FAR *LPAXIS; - - #define LCNAMELEN 40 - typedef struct tagLOGCONTEXTA { - char lcName[LCNAMELEN]; - UINT lcOptions; - UINT lcStatus; - UINT lcLocks; - UINT lcMsgBase; - UINT lcDevice; - UINT lcPktRate; - WTPKT lcPktData; - WTPKT lcPktMode; - WTPKT lcMoveMask; - DWORD lcBtnDnMask; - DWORD lcBtnUpMask; - LONG lcInOrgX; - LONG lcInOrgY; - LONG lcInOrgZ; - LONG lcInExtX; - LONG lcInExtY; - LONG lcInExtZ; - LONG lcOutOrgX; - LONG lcOutOrgY; - LONG lcOutOrgZ; - LONG lcOutExtX; - LONG lcOutExtY; - LONG lcOutExtZ; - FIX32 lcSensX; - FIX32 lcSensY; - FIX32 lcSensZ; - BOOL lcSysMode; - int lcSysOrgX; - int lcSysOrgY; - int lcSysExtX; - int lcSysExtY; - FIX32 lcSysSensX; - FIX32 lcSysSensY; - } LOGCONTEXTA, *PLOGCONTEXTA, NEAR *NPLOGCONTEXTA, FAR *LPLOGCONTEXTA; - - typedef struct tagEXTENSIONBASE { /* 1.4 */ - HCTX nContext; - UINT nStatus; - DWORD nTime; - UINT nSerialNumber; - } EXTENSIONBASE; - -#endif // wintab.h -// ----------------------------------------------------------------------------- - -#define PACKETDATA PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE -#define PACKETMODE 0 - -// ----------------------------------------------------------------------------- -// pktdef.h -// ----------------------------------------------------------------------------- -#if 1 - - // TODO: Simplify this file if we have a fixed packet format. - // The macros here are too ugly. - - #ifndef PACKETNAME - /* if no packet name prefix */ - #define __PFX(x) x - #define __IFX(x,y) x ## y - #else - /* add prefixes and infixes to packet format names */ - #define __PFX(x) __PFX2(PACKETNAME,x) - #define __PFX2(p,x) __PFX3(p,x) - #define __PFX3(p,x) p ## x - #define __IFX(x,y) __IFX2(x,PACKETNAME,y) - #define __IFX2(x,i,y) __IFX3(x,i,y) - #define __IFX3(x,i,y) x ## i ## y - #endif - - #define __SFX2(x,s) __SFX3(x,s) - #define __SFX3(x,s) x ## s - - #define __TAG __IFX(tag,PACKET) - #define __TYPES __PFX(PACKET), * __IFX(P,PACKET), NEAR * __IFX(NP,PACKET), FAR * __IFX(LP,PACKET) - - #define __TAGE __IFX(tag,PACKETEXT) - #define __TYPESE __PFX(PACKETEXT), * __IFX(P,PACKETEXT), NEAR * __IFX(NP,PACKETEXT), FAR * __IFX(LP,PACKETEXT) - - #define __DATA (__PFX(PACKETDATA)) - #define __MODE (__PFX(PACKETMODE)) - #define __EXT(x) __SFX2(__PFX(PACKET),x) - - - typedef struct __TAG { - #if (__DATA & PK_CONTEXT) - HCTX pkContext; - #endif - #if (__DATA & PK_STATUS) - UINT pkStatus; - #endif - #if (__DATA & PK_TIME) - DWORD pkTime; - #endif - #if (__DATA & PK_CHANGED) - WTPKT pkChanged; - #endif - #if (__DATA & PK_SERIAL_NUMBER) - UINT pkSerialNumber; - #endif - #if (__DATA & PK_CURSOR) - UINT pkCursor; - #endif - #if (__DATA & PK_BUTTONS) - DWORD pkButtons; - #endif - #if (__DATA & PK_X) - LONG pkX; - #endif - #if (__DATA & PK_Y) - LONG pkY; - #endif - #if (__DATA & PK_Z) - LONG pkZ; - #endif - #if (__DATA & PK_NORMAL_PRESSURE) - #if (__MODE & PK_NORMAL_PRESSURE) - /* relative */ - int pkNormalPressure; - #else - /* absolute */ - UINT pkNormalPressure; - #endif - #endif - #if (__DATA & PK_TANGENT_PRESSURE) - #if (__MODE & PK_TANGENT_PRESSURE) - /* relative */ - int pkTangentPressure; - #else - /* absolute */ - UINT pkTangentPressure; - #endif - #endif - #if (__DATA & PK_ORIENTATION) - ORIENTATION pkOrientation; - #endif - #if (__DATA & PK_ROTATION) - ROTATION pkRotation; /* 1.1 */ - #endif - - #ifndef NOWTEXTENSIONS - /* extensions begin here. */ - #if (__EXT(FKEYS) == PKEXT_RELATIVE) || (__EXT(FKEYS) == PKEXT_ABSOLUTE) - UINT pkFKeys; - #endif - #if (__EXT(TILT) == PKEXT_RELATIVE) || (__EXT(TILT) == PKEXT_ABSOLUTE) - TILT pkTilt; - #endif - #endif - - } __TYPES; - - #ifndef NOWTEXTENSIONS - typedef struct __TAGE { - EXTENSIONBASE pkBase; - - #if (__EXT(EXPKEYS) == PKEXT_RELATIVE) || (__EXT(EXPKEYS) == PKEXT_ABSOLUTE) - EXPKEYSDATA pkExpKeys; /* 1.4 */ - #endif - #if (__EXT(TOUCHSTRIP) == PKEXT_RELATIVE) || (__EXT(TOUCHSTRIP) == PKEXT_ABSOLUTE) - SLIDERDATA pkTouchStrip; /* 1.4 */ - #endif - #if (__EXT(TOUCHRING) == PKEXT_RELATIVE) || (__EXT(TOUCHRING) == PKEXT_ABSOLUTE) - SLIDERDATA pkTouchRing; /* 1.4 */ - #endif - - } __TYPESE; - #endif - - #undef PACKETNAME - #undef __TAG - #undef __TAGE - #undef __TAG2 - #undef __TYPES - #undef __TYPESE - #undef __TYPES2 - #undef __DATA - #undef __MODE - #undef __PFX - #undef __PFX2 - #undef __PFX3 - #undef __IFX - #undef __IFX2 - #undef __IFX3 - #undef __SFX2 - #undef __SFX3 - -#endif // pktdef.h -// ----------------------------------------------------------------------------- - -typedef UINT (WINAPI * WTINFOA) (UINT, UINT, LPVOID); -typedef HCTX (WINAPI * WTOPENA) (HWND, LPLOGCONTEXTA, BOOL); -typedef BOOL (WINAPI * WTGETA) (HCTX, LPLOGCONTEXTA); -typedef BOOL (WINAPI * WTSETA) (HCTX, LPLOGCONTEXTA); -typedef BOOL (WINAPI * WTCLOSE) (HCTX); -typedef BOOL (WINAPI * WTENABLE) (HCTX, BOOL); -typedef BOOL (WINAPI * WTPACKET) (HCTX, UINT, LPVOID); -typedef BOOL (WINAPI * WTOVERLAP) (HCTX, BOOL); -typedef BOOL (WINAPI * WTSAVE) (HCTX, LPVOID); -typedef BOOL (WINAPI * WTCONFIG) (HCTX, HWND); -typedef HCTX (WINAPI * WTRESTORE) (HWND, LPVOID, BOOL); -typedef BOOL (WINAPI * WTEXTSET) (HCTX, UINT, LPVOID); -typedef BOOL (WINAPI * WTEXTGET) (HCTX, UINT, LPVOID); -typedef BOOL (WINAPI * WTQUEUESIZESET) (HCTX, int); -typedef int (WINAPI * WTDATAPEEK) (HCTX, UINT, UINT, int, LPVOID, LPINT); -typedef int (WINAPI * WTPACKETSGET) (HCTX, int, LPVOID); -typedef HMGR (WINAPI * WTMGROPEN) (HWND, UINT); -typedef BOOL (WINAPI * WTMGRCLOSE) (HMGR); -typedef HCTX (WINAPI * WTMGRDEFCONTEXT) (HMGR, BOOL); -typedef HCTX (WINAPI * WTMGRDEFCONTEXTEX) (HMGR, UINT, BOOL); - -#endif // WIN32 - -// ----------------------------------------------------------------------------- -// Enums -// ----------------------------------------------------------------------------- - -/* - Use this enum in conjunction with EasyTab->Buttons to check for tablet button - presses. - e.g. To check for lower pen button press, use: - - if (EasyTab->Buttons & EasyTab_Buttons_Pen_Lower) - { - // Lower button is pressed - } -*/ -enum EasyTab_Buttons_ -{ - EasyTab_Buttons_Pen_Touch = 1 << 0, // Pen is touching tablet - EasyTab_Buttons_Pen_Lower = 1 << 1, // Lower pen button is pressed - EasyTab_Buttons_Pen_Upper = 1 << 2, // Upper pen button is pressed -}; - -// ----------------------------------------------------------------------------- -// Structs -// ----------------------------------------------------------------------------- -typedef struct -{ - int32_t PosX, PosY; - float Pressure; // Range: 0.0f to 1.0f - int32_t Buttons; // Bit field. Use with the EasyTab_Buttons_ enum. - - int32_t RangeX, RangeY; - int32_t MaxPressure; - -#ifdef __linux__ - XDevice* Device; - uint32_t MotionType; - XEventClass EventClasses[1024]; - uint32_t NumEventClasses; -#endif // __linux__ - -#ifdef WIN32 - HINSTANCE Dll; - HCTX Context; - - WTINFOA WTInfoA; - WTOPENA WTOpenA; - WTGETA WTGetA; - WTSETA WTSetA; - WTCLOSE WTClose; - WTPACKET WTPacket; - WTENABLE WTEnable; - WTOVERLAP WTOverlap; - WTSAVE WTSave; - WTCONFIG WTConfig; - WTRESTORE WTRestore; - WTEXTSET WTExtSet; - WTEXTGET WTExtGet; - WTQUEUESIZESET WTQueueSizeSet; - WTDATAPEEK WTDataPeek; - WTPACKETSGET WTPacketsGet; - WTMGROPEN WTMgrOpen; - WTMGRCLOSE WTMgrClose; - WTMGRDEFCONTEXT WTMgrDefContext; - WTMGRDEFCONTEXTEX WTMgrDefContextEx; -#endif // WIN32 -} EasyTabInfo; - -extern EasyTabInfo* EasyTab; - -// ----------------------------------------------------------------------------- -// Function declarations -// ----------------------------------------------------------------------------- -#if defined(__linux__) - - EasyTabResult EasyTab_Load(Display* Disp, Window Win); - EasyTabResult EasyTab_HandleEvent(XEvent* Event); - void EasyTab_Unload(Display* Disp); - -#elif defined(_WIN32) - - EasyTabResult EasyTab_Load(HWND Window); - EasyTabResult EasyTab_Load_Ex(HWND Window, - EasyTabTrackingMode Mode, - float RelativeModeSensitivity, - int32_t MoveCursor); - EasyTabResult EasyTab_HandleEvent(HWND Window, - UINT Message, - LPARAM LParam, - WPARAM WParam); - void EasyTab_Unload(); - -#else - - // Save some trouble when porting. - #error "Unsupported platform." - -#endif // __linux__ _WIN32 -// ----------------------------------------------------------------------------- - -#endif // EASYTAB_H - - - -// ============================================================================= -// EasyTab implementation section -// ============================================================================= - -#ifdef EASYTAB_IMPLEMENTATION - -EasyTabInfo* EasyTab; - -// ----------------------------------------------------------------------------- -// Linux implementation -// ----------------------------------------------------------------------------- -#ifdef __linux__ - -EasyTabResult EasyTab_Load(Display* Disp, Window Win) -{ - EasyTab = (EasyTabInfo*)calloc(1, sizeof(EasyTabInfo)); // We want init to zero, hence calloc. - if (!EasyTab) { return EASYTAB_MEMORY_ERROR; } - - int32_t Count; - XDeviceInfoPtr Devices = (XDeviceInfoPtr)XListInputDevices(Disp, &Count); - if (!Devices) { return EASYTAB_X11_ERROR; } - - for (int32_t i = 0; i < Count; i++) - { - if (!strstr(Devices[i].name, "stylus") && - !strstr(Devices[i].name, "eraser")) { continue; } - - EasyTab->Device = XOpenDevice(Disp, Devices[i].id); - XAnyClassPtr ClassPtr = Devices[i].inputclassinfo; - - for (int32_t j = 0; j < Devices[i].num_classes; j++) - { -#if defined(__cplusplus) - switch (ClassPtr->c_class) -#else - switch (ClassPtr->class) -#endif - { - case ValuatorClass: - { - XValuatorInfo *Info = (XValuatorInfo *)ClassPtr; - // X - if (Info->num_axes > 0) - { - int32_t min = Info->axes[0].min_value; - EasyTab->RangeX = Info->axes[0].max_value; - //printf("Max/min x values: %d, %d\n", min, EasyTab->RangeX); // TODO: Platform-print macro - } - - // Y - if (Info->num_axes > 1) - { - int32_t min = Info->axes[1].min_value; - EasyTab->RangeY = Info->axes[1].max_value; - //printf("Max/min y values: %d, %d\n", min, EasyTab->RangeY); - } - - // Pressure - if (Info->num_axes > 2) - { - int32_t min = Info->axes[2].min_value; - EasyTab->MaxPressure = Info->axes[2].max_value; - //printf("Max/min pressure values: %d, %d\n", min, EasyTab->MaxPressure); - } - - XEventClass EventClass; - DeviceMotionNotify(EasyTab->Device, EasyTab->MotionType, EventClass); - if (EventClass) - { - EasyTab->EventClasses[EasyTab->NumEventClasses] = EventClass; - EasyTab->NumEventClasses++; - } - } break; - } - - ClassPtr = (XAnyClassPtr) ((uint8_t*)ClassPtr + ClassPtr->length); // TODO: Access this as an array to avoid pointer arithmetic? - } - - XSelectExtensionEvent(Disp, Win, EasyTab->EventClasses, EasyTab->NumEventClasses); - } - - XFreeDeviceList(Devices); - - if (EasyTab->Device != 0) { return EASYTAB_OK; } - else { return EASYTAB_X11_ERROR; } -} - -EasyTabResult EasyTab_HandleEvent(XEvent* Event) -{ - if (Event->type != EasyTab->MotionType) { return EASYTAB_EVENT_NOT_HANDLED; } - - XDeviceMotionEvent* MotionEvent = (XDeviceMotionEvent*)(Event); - EasyTab->PosX = MotionEvent->x; - EasyTab->PosY = MotionEvent->y; - EasyTab->Pressure = (float)MotionEvent->axis_data[2] / (float)EasyTab->MaxPressure; - return EASYTAB_OK; -} - -void EasyTab_Unload(Display* Disp) -{ - XCloseDevice(Disp, EasyTab->Device); - free(EasyTab); - EasyTab = NULL; -} - -#endif // __linux__ - - -// ----------------------------------------------------------------------------- -// Windows implementation -// ----------------------------------------------------------------------------- -#ifdef WIN32 - -#define GETPROCADDRESS(type, func) \ - EasyTab->func = (type)GetProcAddress(EasyTab->Dll, #func); \ - if (!EasyTab->func) \ - { \ - OutputDebugStringA("Function " #func " not found in Wintab32.dll.\n"); \ - return EASYTAB_INVALID_FUNCTION_ERROR; \ - } - - -EasyTabResult EasyTab_Load(HWND Window) -{ - return EasyTab_Load_Ex(Window, EASYTAB_TRACKING_MODE_SYSTEM, 0, 1); -} - -EasyTabResult EasyTab_Load_Ex(HWND Window, - EasyTabTrackingMode TrackingMode, - float RelativeModeSensitivity, - int32_t MoveCursor) -{ - EasyTab = (EasyTabInfo*)calloc(1, sizeof(EasyTabInfo)); // We want init to zero, hence calloc. - if (!EasyTab) { return EASYTAB_MEMORY_ERROR; } - - // Load Wintab DLL and get function addresses - { - EasyTab->Dll = LoadLibraryA("Wintab32.dll"); - if (!EasyTab->Dll) - { - OutputDebugStringA("Wintab32.dll not found.\n"); - return EASYTAB_DLL_LOAD_ERROR; - } - - GETPROCADDRESS(WTINFOA , WTInfoA); - GETPROCADDRESS(WTOPENA , WTOpenA); - GETPROCADDRESS(WTGETA , WTGetA); - GETPROCADDRESS(WTSETA , WTSetA); - GETPROCADDRESS(WTCLOSE , WTClose); - GETPROCADDRESS(WTPACKET , WTPacket); - GETPROCADDRESS(WTENABLE , WTEnable); - GETPROCADDRESS(WTOVERLAP , WTOverlap); - GETPROCADDRESS(WTSAVE , WTSave); - GETPROCADDRESS(WTCONFIG , WTConfig); - GETPROCADDRESS(WTRESTORE , WTRestore); - GETPROCADDRESS(WTEXTSET , WTExtSet); - GETPROCADDRESS(WTEXTGET , WTExtGet); - GETPROCADDRESS(WTQUEUESIZESET , WTQueueSizeSet); - GETPROCADDRESS(WTDATAPEEK , WTDataPeek); - GETPROCADDRESS(WTPACKETSGET , WTPacketsGet); - GETPROCADDRESS(WTMGROPEN , WTMgrOpen); - GETPROCADDRESS(WTMGRCLOSE , WTMgrClose); - GETPROCADDRESS(WTMGRDEFCONTEXT , WTMgrDefContext); - GETPROCADDRESS(WTMGRDEFCONTEXTEX , WTMgrDefContextEx); - } - - if (!EasyTab->WTInfoA(0, 0, NULL)) - { - OutputDebugStringA("Wintab services not available.\n"); - return EASYTAB_WACOM_WIN32_ERROR; - } - - // Open context - { - LOGCONTEXTA LogContext = {0}; - AXIS RangeX = {0}; - AXIS RangeY = {0}; - AXIS Pressure = {0}; - - EasyTab->WTInfoA(WTI_DDCTXS, 0, &LogContext); - EasyTab->WTInfoA(WTI_DEVICES, DVC_X, &RangeX); - EasyTab->WTInfoA(WTI_DEVICES, DVC_Y, &RangeY); - EasyTab->WTInfoA(WTI_DEVICES, DVC_NPRESSURE, &Pressure); - - LogContext.lcPktData = PACKETDATA; // ?? - LogContext.lcOptions |= CXO_MESSAGES; - if (MoveCursor) { LogContext.lcOptions |= CXO_SYSTEM; } - LogContext.lcPktMode = PACKETMODE; - LogContext.lcMoveMask = PACKETDATA; - LogContext.lcBtnUpMask = LogContext.lcBtnDnMask; - - LogContext.lcOutOrgX = 0; - LogContext.lcOutOrgY = 0; - LogContext.lcOutExtX = GetSystemMetrics(SM_CXSCREEN); - LogContext.lcOutExtY = -GetSystemMetrics(SM_CYSCREEN); - - LogContext.lcSysOrgX = 0; - LogContext.lcSysOrgY = 0; - LogContext.lcSysExtX = GetSystemMetrics(SM_CXSCREEN); - LogContext.lcSysExtY = GetSystemMetrics(SM_CYSCREEN); - - if (TrackingMode == EASYTAB_TRACKING_MODE_RELATIVE) - { - LogContext.lcPktMode |= PK_X | PK_Y; // TODO: Should this be included in the - // PACKETMODE macro define up top? - LogContext.lcSysMode = 1; - - if (RelativeModeSensitivity > 1.0f) - { - RelativeModeSensitivity = 1.0f; - } - else if (RelativeModeSensitivity < 0.0f) - { - RelativeModeSensitivity = 0.0f; - } - - // Wintab expects sensitivity to be a 32-bit fixed point number - // with the radix point between the two words. Thus, the type - // contains 16 bits to the left of the radix point and 16 bits to - // the right of it. - // - // 0x10000 Hex - // = 65,536 Decimal - // = 0000 0000 0000 0001 . 0000 0000 0000 0000 Binary - // = 1.0 Fixed Point - uint32_t Sensitivity = (uint32_t)(0x10000 * RelativeModeSensitivity); - - if (MoveCursor) - { - LogContext.lcSysSensX = LogContext.lcSysSensY = Sensitivity; - } - else - { - LogContext.lcSensX = LogContext.lcSensY = Sensitivity; - } - } - - EasyTab->Context = EasyTab->WTOpenA(Window, &LogContext, TRUE); - - if (!EasyTab->Context) - { - OutputDebugStringA("Wintab context couldn't be opened.\n"); - return EASYTAB_WACOM_WIN32_ERROR; - } - - // Get tablet capabilites - { - EasyTab->MaxPressure = Pressure.axMax; - EasyTab->RangeX = RangeX.axMax; - EasyTab->RangeY = RangeY.axMax; - } - } - - return EASYTAB_OK; -} - -#undef GETPROCADDRESS - -EasyTabResult EasyTab_HandleEvent(HWND Window, UINT Message, LPARAM LParam, WPARAM WParam) -{ - PACKET Packet = { 0 }; - - if (Message == WT_PACKET && - (HCTX)LParam == EasyTab->Context && - EasyTab->WTPacket(EasyTab->Context, (UINT)WParam, &Packet)) - { - POINT Point = { 0 }; - Point.x = Packet.pkX; - Point.y = Packet.pkY; - ScreenToClient(Window, &Point); - EasyTab->PosX = Point.x; - EasyTab->PosY = Point.y; - - EasyTab->Pressure = (float)Packet.pkNormalPressure / (float)EasyTab->MaxPressure; - EasyTab->Buttons = Packet.pkButtons; - return EASYTAB_OK; - } - - return EASYTAB_EVENT_NOT_HANDLED; -} - -void EasyTab_Unload() -{ - if (EasyTab->Context) { EasyTab->WTClose(EasyTab->Context); } - if (EasyTab->Dll) { FreeLibrary(EasyTab->Dll); } - free(EasyTab); - EasyTab = NULL; -} - -#endif // WIN32 -// ----------------------------------------------------------------------------- - - -#endif // EASYTAB_IMPLEMENTATION diff --git a/.outdated/graphics/ext/objloader.h b/.outdated/graphics/ext/objloader.h deleted file mode 100644 index 5e1bad6..0000000 --- a/.outdated/graphics/ext/objloader.h +++ /dev/null @@ -1,1191 +0,0 @@ -// OBJ_Loader.h - A Single Header OBJ Model Loader - -/* -MIT License - -Copyright(c) 2016 Robert Smith - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this softwareand associated documentation files(the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and /or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions : - -The above copyright noticeand this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -#pragma once - -// Iostream - STD I/O Library -#include - -// Vector - STD Vector/Array Library -#include - -// String - STD String Library -#include - -// fStream - STD File I/O Library -#include - -// Math.h - STD math Library -#include - -// Print progress to console while loading (large models) -#define OBJL_CONSOLE_OUTPUT - -// Namespace: OBJL -// -// Description: The namespace that holds eveyrthing that -// is needed and used for the OBJ Model Loader -namespace objl -{ - // Structure: Vector2 - // - // Description: A 2D Vector that Holds Positional Data - struct Vector2 - { - // Default Constructor - Vector2() - { - X = 0.0f; - Y = 0.0f; - } - // Variable Set Constructor - Vector2(float X_, float Y_) - { - X = X_; - Y = Y_; - } - // Bool Equals Operator Overload - bool operator==(const Vector2& other) const - { - return (this->X == other.X && this->Y == other.Y); - } - // Bool Not Equals Operator Overload - bool operator!=(const Vector2& other) const - { - return !(this->X == other.X && this->Y == other.Y); - } - // Addition Operator Overload - Vector2 operator+(const Vector2& right) const - { - return Vector2(this->X + right.X, this->Y + right.Y); - } - // Subtraction Operator Overload - Vector2 operator-(const Vector2& right) const - { - return Vector2(this->X - right.X, this->Y - right.Y); - } - // Float Multiplication Operator Overload - Vector2 operator*(const float& other) const - { - return Vector2(this->X *other, this->Y * other); - } - - // Positional Variables - float X; - float Y; - }; - - // Structure: Vector3 - // - // Description: A 3D Vector that Holds Positional Data - struct Vector3 - { - // Default Constructor - Vector3() - { - X = 0.0f; - Y = 0.0f; - Z = 0.0f; - } - // Variable Set Constructor - Vector3(float X_, float Y_, float Z_) - { - X = X_; - Y = Y_; - Z = Z_; - } - // Bool Equals Operator Overload - bool operator==(const Vector3& other) const - { - return (this->X == other.X && this->Y == other.Y && this->Z == other.Z); - } - // Bool Not Equals Operator Overload - bool operator!=(const Vector3& other) const - { - return !(this->X == other.X && this->Y == other.Y && this->Z == other.Z); - } - // Addition Operator Overload - Vector3 operator+(const Vector3& right) const - { - return Vector3(this->X + right.X, this->Y + right.Y, this->Z + right.Z); - } - // Subtraction Operator Overload - Vector3 operator-(const Vector3& right) const - { - return Vector3(this->X - right.X, this->Y - right.Y, this->Z - right.Z); - } - // Float Multiplication Operator Overload - Vector3 operator*(const float& other) const - { - return Vector3(this->X * other, this->Y * other, this->Z * other); - } - // Float Division Operator Overload - Vector3 operator/(const float& other) const - { - return Vector3(this->X / other, this->Y / other, this->Z / other); - } - - // Positional Variables - float X; - float Y; - float Z; - }; - - // Structure: Vertex - // - // Description: Model Vertex object that holds - // a Position, Normal, and Texture Coordinate - struct Vertex - { - // Position Vector - Vector3 Position; - - // Normal Vector - Vector3 normal; - - // Texture Coordinate Vector - Vector2 TextureCoordinate; - }; - - struct Material - { - Material() - { - name; - Ns = 0.0f; - Ni = 0.0f; - d = 0.0f; - illum = 0; - } - - // Material Name - std::string name; - // Ambient Color - Vector3 Ka; - // Diffuse Color - Vector3 Kd; - // Specular Color - Vector3 Ks; - // Specular Exponent - float Ns; - // Optical Density - float Ni; - // Dissolve - float d; - // Illumination - int illum; - // Ambient Texture Map - std::string map_Ka; - // Diffuse Texture Map - std::string map_Kd; - // Specular Texture Map - std::string map_Ks; - // Specular Hightlight Map - std::string map_Ns; - // Alpha Texture Map - std::string map_d; - // Bump Map - std::string map_bump; - }; - - // Structure: Mesh - // - // Description: A Simple Mesh Object that holds - // a name, a vertex list, and an index list - struct Mesh - { - // Default Constructor - Mesh() - { - - } - // Variable Set Constructor - Mesh(std::vector& _Vertices, std::vector& _Indices) - { - Vertices = _Vertices; - Indices = _Indices; - } - // Mesh Name - std::string MeshName; - // Vertex List - std::vector Vertices; - // Index List - std::vector Indices; - - // Material - Material MeshMaterial; - }; - - // Namespace: Math - // - // Description: The namespace that holds all of the math - // functions need for OBJL - namespace math - { - // Vector3 Cross Product - Vector3 CrossV3(const Vector3 a, const Vector3 b) - { - return Vector3(a.Y * b.Z - a.Z * b.Y, - a.Z * b.X - a.X * b.Z, - a.X * b.Y - a.Y * b.X); - } - - // Vector3 Magnitude Calculation - float MagnitudeV3(const Vector3 in) - { - return (sqrtf(powf(in.X, 2) + powf(in.Y, 2) + powf(in.Z, 2))); - } - - // Vector3 DotProduct - float DotV3(const Vector3 a, const Vector3 b) - { - return (a.X * b.X) + (a.Y * b.Y) + (a.Z * b.Z); - } - - // Angle between 2 Vector3 Objects - float AngleBetweenV3(const Vector3 a, const Vector3 b) - { - float angle = DotV3(a, b); - angle /= (MagnitudeV3(a) * MagnitudeV3(b)); - return angle = acosf(angle); - } - - // Projection Calculation of a onto b - Vector3 ProjV3(const Vector3 a, const Vector3 b) - { - Vector3 bn = b / MagnitudeV3(b); - return bn * DotV3(a, bn); - } - } - - // Namespace: Algorithm - // - // Description: The namespace that holds all of the - // Algorithms needed for OBJL - namespace algorithm - { - // Vector3 Multiplication Opertor Overload - Vector3 operator*(const float& left, const Vector3& right) - { - return Vector3(right.X * left, right.Y * left, right.Z * left); - } - - // A test to see if P1 is on the same side as P2 of a line segment ab - bool SameSide(Vector3 p1, Vector3 p2, Vector3 a, Vector3 b) - { - Vector3 cp1 = math::CrossV3(b - a, p1 - a); - Vector3 cp2 = math::CrossV3(b - a, p2 - a); - - if (math::DotV3(cp1, cp2) >= 0) - return true; - else - return false; - } - - // Generate a cross produect normal for a triangle - Vector3 GenTriNormal(Vector3 t1, Vector3 t2, Vector3 t3) - { - Vector3 u = t2 - t1; - Vector3 v = t3 - t1; - - Vector3 normal = math::CrossV3(u,v); - - return normal; - } - - // Check to see if a Vector3 Point is within a 3 Vector3 Triangle - bool inTriangle(Vector3 point, Vector3 tri1, Vector3 tri2, Vector3 tri3) - { - // Test to see if it is within an infinite prism that the triangle outlines. - bool within_tri_prisim = SameSide(point, tri1, tri2, tri3) && SameSide(point, tri2, tri1, tri3) - && SameSide(point, tri3, tri1, tri2); - - // If it isn't it will never be on the triangle - if (!within_tri_prisim) - return false; - - // Calulate Triangle's Normal - Vector3 n = GenTriNormal(tri1, tri2, tri3); - - // Project the point onto this normal - Vector3 proj = math::ProjV3(point, n); - - // If the distance from the triangle to the point is 0 - // it lies on the triangle - if (math::MagnitudeV3(proj) == 0) - return true; - else - return false; - } - - // Split a String into a string array at a given token - inline void split(const std::string &in, - std::vector &out, - std::string token) - { - out.clear(); - - std::string temp; - - for (int i = 0; i < int(in.size()); i++) - { - std::string test = in.substr(i, token.size()); - - if (test == token) - { - if (!temp.empty()) - { - out.push_back(temp); - temp.clear(); - i += (int)token.size() - 1; - } - else - { - out.push_back(""); - } - } - else if (i + token.size() >= in.size()) - { - temp += in.substr(i, token.size()); - out.push_back(temp); - break; - } - else - { - temp += in[i]; - } - } - } - - // Get tail of string after first token and possibly following spaces - inline std::string tail(const std::string &in) - { - size_t token_start = in.find_first_not_of(" \t"); - size_t space_start = in.find_first_of(" \t", token_start); - size_t tail_start = in.find_first_not_of(" \t", space_start); - size_t tail_end = in.find_last_not_of(" \t"); - if (tail_start != std::string::npos && tail_end != std::string::npos) - { - return in.substr(tail_start, tail_end - tail_start + 1); - } - else if (tail_start != std::string::npos) - { - return in.substr(tail_start); - } - return ""; - } - - // Get first token of string - inline std::string firstToken(const std::string &in) - { - if (!in.empty()) - { - size_t token_start = in.find_first_not_of(" \t"); - size_t token_end = in.find_first_of(" \t", token_start); - if (token_start != std::string::npos && token_end != std::string::npos) - { - return in.substr(token_start, token_end - token_start); - } - else if (token_start != std::string::npos) - { - return in.substr(token_start); - } - } - return ""; - } - - // Get element at given index position - template - inline const T & getElement(const std::vector &elements, std::string &index) - { - int idx = std::stoi(index); - if (idx < 0) - idx = int(elements.size()) + idx; - else - idx--; - return elements[idx]; - } - } - - // Class: Loader - // - // Description: The OBJ Model Loader - class Loader - { - public: - // Default Constructor - Loader() - { - - } - ~Loader() - { - LoadedMeshes.clear(); - } - - // Load a file into the loader - // - // If file is loaded return true - // - // If the file is unable to be found - // or unable to be loaded return false - bool LoadFile(std::string Path) - { - // If the file is not an .obj file return false - if (Path.substr(Path.size() - 4, 4) != ".obj") - return false; - - - std::ifstream file(Path); - - if (!file.is_open()) - return false; - - LoadedMeshes.clear(); - LoadedVertices.clear(); - LoadedIndices.clear(); - - std::vector Positions; - std::vector TCoords; - std::vector Normals; - - std::vector Vertices; - std::vector Indices; - - std::vector MeshMatNames; - - bool listening = false; - std::string meshname; - - Mesh tempMesh; - - #ifdef OBJL_CONSOLE_OUTPUT - const unsigned int outputEveryNth = 1000; - unsigned int outputIndicator = outputEveryNth; - #endif - - std::string curline; - while (std::getline(file, curline)) - { - #ifdef OBJL_CONSOLE_OUTPUT - if ((outputIndicator = ((outputIndicator + 1) % outputEveryNth)) == 1) - { - if (!meshname.empty()) - { - std::cout - << "\r- " << meshname - << "\t| vertices > " << Positions.size() - << "\t| texcoords > " << TCoords.size() - << "\t| normals > " << Normals.size() - << "\t| triangles > " << (Vertices.size() / 3) - << (!MeshMatNames.empty() ? "\t| material: " + MeshMatNames.back() : ""); - } - } - #endif - - // Generate a Mesh Object or Prepare for an object to be created - if (algorithm::firstToken(curline) == "o" || algorithm::firstToken(curline) == "g" || curline[0] == 'g') - { - if (!listening) - { - listening = true; - - if (algorithm::firstToken(curline) == "o" || algorithm::firstToken(curline) == "g") - { - meshname = algorithm::tail(curline); - } - else - { - meshname = "unnamed"; - } - } - else - { - // Generate the mesh to put into the array - - if (!Indices.empty() && !Vertices.empty()) - { - // Create Mesh - tempMesh = Mesh(Vertices, Indices); - tempMesh.MeshName = meshname; - - // Insert Mesh - LoadedMeshes.push_back(tempMesh); - - // Cleanup - Vertices.clear(); - Indices.clear(); - meshname.clear(); - - meshname = algorithm::tail(curline); - } - else - { - if (algorithm::firstToken(curline) == "o" || algorithm::firstToken(curline) == "g") - { - meshname = algorithm::tail(curline); - } - else - { - meshname = "unnamed"; - } - } - } - #ifdef OBJL_CONSOLE_OUTPUT - std::cout << std::endl; - outputIndicator = 0; - #endif - } - // Generate a Vertex Position - if (algorithm::firstToken(curline) == "v") - { - std::vector spos; - Vector3 vpos; - algorithm::split(algorithm::tail(curline), spos, " "); - - vpos.X = std::stof(spos[0]); - vpos.Y = std::stof(spos[1]); - vpos.Z = std::stof(spos[2]); - - Positions.push_back(vpos); - } - // Generate a Vertex Texture Coordinate - if (algorithm::firstToken(curline) == "vt") - { - std::vector stex; - Vector2 vtex; - algorithm::split(algorithm::tail(curline), stex, " "); - - vtex.X = std::stof(stex[0]); - vtex.Y = std::stof(stex[1]); - - TCoords.push_back(vtex); - } - // Generate a Vertex Normal; - if (algorithm::firstToken(curline) == "vn") - { - std::vector snor; - Vector3 vnor; - algorithm::split(algorithm::tail(curline), snor, " "); - - vnor.X = std::stof(snor[0]); - vnor.Y = std::stof(snor[1]); - vnor.Z = std::stof(snor[2]); - - Normals.push_back(vnor); - } - // Generate a Face (vertices & indices) - if (algorithm::firstToken(curline) == "f") - { - // Generate the vertices - std::vector vVerts; - GenVerticesFromRawOBJ(vVerts, Positions, TCoords, Normals, curline); - - // Add Vertices - for (int i = 0; i < int(vVerts.size()); i++) - { - Vertices.push_back(vVerts[i]); - - LoadedVertices.push_back(vVerts[i]); - } - - std::vector iIndices; - - VertexTriangluation(iIndices, vVerts); - - // Add Indices - for (int i = 0; i < int(iIndices.size()); i++) - { - unsigned int indnum = (unsigned int)((Vertices.size()) - vVerts.size()) + iIndices[i]; - Indices.push_back(indnum); - - indnum = (unsigned int)((LoadedVertices.size()) - vVerts.size()) + iIndices[i]; - LoadedIndices.push_back(indnum); - - } - } - // Get Mesh Material Name - if (algorithm::firstToken(curline) == "usemtl") - { - MeshMatNames.push_back(algorithm::tail(curline)); - - // Create new Mesh, if Material changes within a group - if (!Indices.empty() && !Vertices.empty()) - { - // Create Mesh - tempMesh = Mesh(Vertices, Indices); - tempMesh.MeshName = meshname; - int i = 2; - while(1) { - tempMesh.MeshName = meshname + "_" + std::to_string(i); - - for (auto &m : LoadedMeshes) - if (m.MeshName == tempMesh.MeshName) - continue; - break; - } - - // Insert Mesh - LoadedMeshes.push_back(tempMesh); - - // Cleanup - Vertices.clear(); - Indices.clear(); - } - - #ifdef OBJL_CONSOLE_OUTPUT - outputIndicator = 0; - #endif - } - // Load Materials - if (algorithm::firstToken(curline) == "mtllib") - { - // Generate LoadedMaterial - - // Generate a path to the material file - std::vector temp; - algorithm::split(Path, temp, "/"); - - std::string pathtomat = ""; - - if (temp.size() != 1) - { - for (int i = 0; i < temp.size() - 1; i++) - { - pathtomat += temp[i] + "/"; - } - } - - - pathtomat += algorithm::tail(curline); - - #ifdef OBJL_CONSOLE_OUTPUT - std::cout << std::endl << "- find materials in: " << pathtomat << std::endl; - #endif - - // Load Materials - LoadMaterials(pathtomat); - } - } - - #ifdef OBJL_CONSOLE_OUTPUT - std::cout << std::endl; - #endif - - // Deal with last mesh - - if (!Indices.empty() && !Vertices.empty()) - { - // Create Mesh - tempMesh = Mesh(Vertices, Indices); - tempMesh.MeshName = meshname; - - // Insert Mesh - LoadedMeshes.push_back(tempMesh); - } - - file.close(); - - // Set Materials for each Mesh - for (int i = 0; i < MeshMatNames.size(); i++) - { - std::string matname = MeshMatNames[i]; - - // Find corresponding material name in loaded materials - // when found copy material variables into mesh material - for (int j = 0; j < LoadedMaterials.size(); j++) - { - if (LoadedMaterials[j].name == matname) - { - LoadedMeshes[i].MeshMaterial = LoadedMaterials[j]; - break; - } - } - } - - if (LoadedMeshes.empty() && LoadedVertices.empty() && LoadedIndices.empty()) - { - return false; - } - else - { - return true; - } - } - - // Loaded Mesh Objects - std::vector LoadedMeshes; - // Loaded Vertex Objects - std::vector LoadedVertices; - // Loaded Index Positions - std::vector LoadedIndices; - // Loaded Material Objects - std::vector LoadedMaterials; - - private: - // Generate vertices from a list of positions, - // tcoords, normals and a face line - void GenVerticesFromRawOBJ(std::vector& oVerts, - const std::vector& iPositions, - const std::vector& iTCoords, - const std::vector& iNormals, - std::string icurline) - { - std::vector sface, svert; - Vertex vVert; - algorithm::split(algorithm::tail(icurline), sface, " "); - - bool noNormal = false; - - // For every given vertex do this - for (int i = 0; i < int(sface.size()); i++) - { - // See What type the vertex is. - int vtype; - - algorithm::split(sface[i], svert, "/"); - - // Check for just position - v1 - if (svert.size() == 1) - { - // Only position - vtype = 1; - } - - // Check for position & texture - v1/vt1 - if (svert.size() == 2) - { - // Position & Texture - vtype = 2; - } - - // Check for Position, Texture and Normal - v1/vt1/vn1 - // or if Position and Normal - v1//vn1 - if (svert.size() == 3) - { - if (svert[1] != "") - { - // Position, Texture, and Normal - vtype = 4; - } - else - { - // Position & Normal - vtype = 3; - } - } - - // Calculate and store the vertex - switch (vtype) - { - case 1: // P - { - vVert.Position = algorithm::getElement(iPositions, svert[0]); - vVert.TextureCoordinate = Vector2(0, 0); - noNormal = true; - oVerts.push_back(vVert); - break; - } - case 2: // P/T - { - vVert.Position = algorithm::getElement(iPositions, svert[0]); - vVert.TextureCoordinate = algorithm::getElement(iTCoords, svert[1]); - noNormal = true; - oVerts.push_back(vVert); - break; - } - case 3: // P//N - { - vVert.Position = algorithm::getElement(iPositions, svert[0]); - vVert.TextureCoordinate = Vector2(0, 0); - vVert.normal = algorithm::getElement(iNormals, svert[2]); - oVerts.push_back(vVert); - break; - } - case 4: // P/T/N - { - vVert.Position = algorithm::getElement(iPositions, svert[0]); - vVert.TextureCoordinate = algorithm::getElement(iTCoords, svert[1]); - vVert.normal = algorithm::getElement(iNormals, svert[2]); - oVerts.push_back(vVert); - break; - } - default: - { - break; - } - } - } - - // take care of missing normals - // these may not be truly acurate but it is the - // best they get for not compiling a mesh with normals - if (noNormal) - { - Vector3 A = oVerts[0].Position - oVerts[1].Position; - Vector3 B = oVerts[2].Position - oVerts[1].Position; - - Vector3 normal = math::CrossV3(A, B); - - for (int i = 0; i < int(oVerts.size()); i++) - { - oVerts[i].normal = normal; - } - } - } - - // Triangulate a list of vertices into a face by printing - // inducies corresponding with triangles within it - void VertexTriangluation(std::vector& oIndices, - const std::vector& iVerts) - { - // If there are 2 or less verts, - // no triangle can be created, - // so exit - if (iVerts.size() < 3) - { - return; - } - // If it is a triangle no need to calculate it - if (iVerts.size() == 3) - { - oIndices.push_back(0); - oIndices.push_back(1); - oIndices.push_back(2); - return; - } - - // Create a list of vertices - std::vector tVerts = iVerts; - - while (true) - { - // For every vertex - for (int i = 0; i < int(tVerts.size()); i++) - { - // pPrev = the previous vertex in the list - Vertex pPrev; - if (i == 0) - { - pPrev = tVerts[tVerts.size() - 1]; - } - else - { - pPrev = tVerts[i - 1]; - } - - // pCur = the current vertex; - Vertex pCur = tVerts[i]; - - // pNext = the next vertex in the list - Vertex pNext; - if (i == tVerts.size() - 1) - { - pNext = tVerts[0]; - } - else - { - pNext = tVerts[i + 1]; - } - - // Check to see if there are only 3 verts left - // if so this is the last triangle - if (tVerts.size() == 3) - { - // Create a triangle from pCur, pPrev, pNext - for (int j = 0; j < int(tVerts.size()); j++) - { - if (iVerts[j].Position == pCur.Position) - oIndices.push_back(j); - if (iVerts[j].Position == pPrev.Position) - oIndices.push_back(j); - if (iVerts[j].Position == pNext.Position) - oIndices.push_back(j); - } - - tVerts.clear(); - break; - } - if (tVerts.size() == 4) - { - // Create a triangle from pCur, pPrev, pNext - for (int j = 0; j < int(iVerts.size()); j++) - { - if (iVerts[j].Position == pCur.Position) - oIndices.push_back(j); - if (iVerts[j].Position == pPrev.Position) - oIndices.push_back(j); - if (iVerts[j].Position == pNext.Position) - oIndices.push_back(j); - } - - Vector3 tempVec; - for (int j = 0; j < int(tVerts.size()); j++) - { - if (tVerts[j].Position != pCur.Position - && tVerts[j].Position != pPrev.Position - && tVerts[j].Position != pNext.Position) - { - tempVec = tVerts[j].Position; - break; - } - } - - // Create a triangle from pCur, pPrev, pNext - for (int j = 0; j < int(iVerts.size()); j++) - { - if (iVerts[j].Position == pPrev.Position) - oIndices.push_back(j); - if (iVerts[j].Position == pNext.Position) - oIndices.push_back(j); - if (iVerts[j].Position == tempVec) - oIndices.push_back(j); - } - - tVerts.clear(); - break; - } - - // If Vertex is not an interior vertex - float angle = (float)math::AngleBetweenV3(pPrev.Position - pCur.Position, pNext.Position - pCur.Position) * (float) (180 / 3.14159265359); - if (angle <= 0 && angle >= 180) - continue; - - // If any vertices are within this triangle - bool inTri = false; - for (int j = 0; j < int(iVerts.size()); j++) - { - if (algorithm::inTriangle(iVerts[j].Position, pPrev.Position, pCur.Position, pNext.Position) - && iVerts[j].Position != pPrev.Position - && iVerts[j].Position != pCur.Position - && iVerts[j].Position != pNext.Position) - { - inTri = true; - break; - } - } - if (inTri) - continue; - - // Create a triangle from pCur, pPrev, pNext - for (int j = 0; j < int(iVerts.size()); j++) - { - if (iVerts[j].Position == pCur.Position) - oIndices.push_back(j); - if (iVerts[j].Position == pPrev.Position) - oIndices.push_back(j); - if (iVerts[j].Position == pNext.Position) - oIndices.push_back(j); - } - - // Delete pCur from the list - for (int j = 0; j < int(tVerts.size()); j++) - { - if (tVerts[j].Position == pCur.Position) - { - tVerts.erase(tVerts.begin() + j); - break; - } - } - - // reset i to the start - // -1 since loop will add 1 to it - i = -1; - } - - // if no triangles were created - if (oIndices.size() == 0) - break; - - // if no more vertices - if (tVerts.size() == 0) - break; - } - } - - // Load Materials from .mtl file - bool LoadMaterials(std::string path) - { - // If the file is not a material file return false - if (path.substr(path.size() - 4, path.size()) != ".mtl") - return false; - - std::ifstream file(path); - - // If the file is not found return false - if (!file.is_open()) - return false; - - Material tempMaterial; - - bool listening = false; - - // Go through each line looking for material variables - std::string curline; - while (std::getline(file, curline)) - { - // new material and material name - if (algorithm::firstToken(curline) == "newmtl") - { - if (!listening) - { - listening = true; - - if (curline.size() > 7) - { - tempMaterial.name = algorithm::tail(curline); - } - else - { - tempMaterial.name = "none"; - } - } - else - { - // Generate the material - - // Push Back loaded Material - LoadedMaterials.push_back(tempMaterial); - - // Clear Loaded Material - tempMaterial = Material(); - - if (curline.size() > 7) - { - tempMaterial.name = algorithm::tail(curline); - } - else - { - tempMaterial.name = "none"; - } - } - } - // Ambient Color - if (algorithm::firstToken(curline) == "Ka") - { - std::vector temp; - algorithm::split(algorithm::tail(curline), temp, " "); - - if (temp.size() != 3) - continue; - - tempMaterial.Ka.X = std::stof(temp[0]); - tempMaterial.Ka.Y = std::stof(temp[1]); - tempMaterial.Ka.Z = std::stof(temp[2]); - } - // Diffuse Color - if (algorithm::firstToken(curline) == "Kd") - { - std::vector temp; - algorithm::split(algorithm::tail(curline), temp, " "); - - if (temp.size() != 3) - continue; - - tempMaterial.Kd.X = std::stof(temp[0]); - tempMaterial.Kd.Y = std::stof(temp[1]); - tempMaterial.Kd.Z = std::stof(temp[2]); - } - // Specular Color - if (algorithm::firstToken(curline) == "Ks") - { - std::vector temp; - algorithm::split(algorithm::tail(curline), temp, " "); - - if (temp.size() != 3) - continue; - - tempMaterial.Ks.X = std::stof(temp[0]); - tempMaterial.Ks.Y = std::stof(temp[1]); - tempMaterial.Ks.Z = std::stof(temp[2]); - } - // Specular Exponent - if (algorithm::firstToken(curline) == "Ns") - { - tempMaterial.Ns = std::stof(algorithm::tail(curline)); - } - // Optical Density - if (algorithm::firstToken(curline) == "Ni") - { - tempMaterial.Ni = std::stof(algorithm::tail(curline)); - } - // Dissolve - if (algorithm::firstToken(curline) == "d") - { - tempMaterial.d = std::stof(algorithm::tail(curline)); - } - // Illumination - if (algorithm::firstToken(curline) == "illum") - { - tempMaterial.illum = std::stoi(algorithm::tail(curline)); - } - // Ambient Texture Map - if (algorithm::firstToken(curline) == "map_Ka") - { - tempMaterial.map_Ka = algorithm::tail(curline); - } - // Diffuse Texture Map - if (algorithm::firstToken(curline) == "map_Kd") - { - tempMaterial.map_Kd = algorithm::tail(curline); - } - // Specular Texture Map - if (algorithm::firstToken(curline) == "map_Ks") - { - tempMaterial.map_Ks = algorithm::tail(curline); - } - // Specular Hightlight Map - if (algorithm::firstToken(curline) == "map_Ns") - { - tempMaterial.map_Ns = algorithm::tail(curline); - } - // Alpha Texture Map - if (algorithm::firstToken(curline) == "map_d") - { - tempMaterial.map_d = algorithm::tail(curline); - } - // Bump Map - if (algorithm::firstToken(curline) == "map_Bump" || algorithm::firstToken(curline) == "map_bump" || algorithm::firstToken(curline) == "bump") - { - tempMaterial.map_bump = algorithm::tail(curline); - } - } - - // Deal with last material - - // Push Back loaded Material - LoadedMaterials.push_back(tempMaterial); - - // Test to see if anything was loaded - // If not return false - if (LoadedMaterials.empty()) - return false; - // If so return true - else - return true; - } - }; -} \ No newline at end of file diff --git a/.outdated/graphics/inc/GraphicsLibApi.h b/.outdated/graphics/inc/GraphicsLibApi.h deleted file mode 100644 index 8926a14..0000000 --- a/.outdated/graphics/inc/GraphicsLibApi.h +++ /dev/null @@ -1,19 +0,0 @@ - -#pragma once - -#include "env.h" - -#ifdef ENV_OS_ANDROID -#include -#include -#else -#include "GL/glew.h" -#endif - -#ifdef ENV_OS_ANDROID -#define GLW_CONTEXT_DEPTH_BITS 16 -#define GLW_CONTEXT_DEPTH_COMPONENT GL_DEPTH_COMPONENT16 -#else -#define GLW_CONTEXT_DEPTH_BITS 32 -#define GLW_CONTEXT_DEPTH_COMPONENT GL_DEPTH_COMPONENT32 -#endif \ No newline at end of file diff --git a/.outdated/graphics/inc/animations.h b/.outdated/graphics/inc/animations.h deleted file mode 100644 index 8f41f3d..0000000 --- a/.outdated/graphics/inc/animations.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include "rect.h" -#include "color.h" - -namespace tp { - namespace glw { - - extern bool gInTransition; - - struct AnimValue { - halnf mValPrev = 0; - halnf mVal = 0; - time_ms mTimeStart = 0; - halni mTimeAnim = 250; - - halnf interpolate() const; - - AnimValue(); - AnimValue(halnf val); - - halnf prev() { return mValPrev; } - void set(halnf val); - void setNoTransition(halnf); - void setAnimTime(halni time); - halnf get() const; - halnf getTarget() const; - bool inTransition() const; - explicit operator halnf() const; - void operator=(halnf val); - }; - - struct AnimRect : rect { - - AnimRect() { - set({ 0, 0, 0, 0 }); - setAnimTime(450); - } - - rectf get() const; - rectf getTarget() const; - void setNoTransition(rectf); - void set(const rectf&); - void setAnimTime(halni time_ms); - }; - - struct AnimColor { - AnimRect mColor; - rgba get() const; - void set(const rgba&); - }; - }; -}; \ No newline at end of file diff --git a/.outdated/graphics/inc/canvas.h b/.outdated/graphics/inc/canvas.h deleted file mode 100644 index e40d9e7..0000000 --- a/.outdated/graphics/inc/canvas.h +++ /dev/null @@ -1,84 +0,0 @@ - -#pragma once - -#include "stringt.h" -#include "fbuffer.h" - -namespace tp { - namespace glw { - class Canvas { - - typedef rectf Rect; - typedef vec2f Vec2; - typedef rgba Col; - typedef tp::halnf Val; - - Col mColorPrimary; - Col mColorSecondary; - - void* mCtx = NULL; - tp::halnf mDpmm = 1; - tp::halnf mUIScale = 1; - - public: - - Rect mClamping; - Rect mVieport; - - enum Align : uint4 { - LEFT = 1 << 0, // Default, horizontally to left. - CENTER = 1 << 1, // horizontally to center. - RIGHT = 1 << 2, // horizontally to right. - TOP = 1 << 3, // vertically to top. - MIDDLE = 1 << 4, // vertically to middle. - BOTTOM = 1 << 5, // vertically to bottom. - BASELINE = 1 << 6, // Default, vertically to baseline. - CENTER_MIDDLE = CENTER | MIDDLE, - LEFT_MIDDLE = LEFT | MIDDLE, - }; - - Canvas(); - - Val& convert2pxls(Val&); - Rect& convert2pxls(Rect&); - Vec2& convert2pxls(Vec2&); - Val as2pxls(Val); - - // Canvas Manipulation - void beginDraw(Rect viewport, tp::halnf dpmm, tp::halnf uiscale); - void clear(Col color = 0); - void endDraw(); - - void setClamping(Rect rec); - void resetViewport(); - - // Params control - void setCol1(const Col& col); - void setCol2(const Col& col); - - // Shapes - void rect(Rect rec, halnf rounding = 0, halnf borders = 0); - void circle(Vec2 rec, halnf radius, halnf borders = 0); - void trig(Vec2 p1, Vec2 p2, Vec2 p3); - void line(Vec2 p1, Vec2 p2, halnf thikness = 2); - - // Text - void text(const string text, Rect rec, halnf size, Align align = Align::CENTER_MIDDLE); - void text(const char* start, const char* end, Rect rec, halnf size, Align align = Align::CENTER_MIDDLE); - - void drawColorwheel(Rect rec, const rgb& col); - - // image - struct ImageHandle { - halni mId = NULL; - void createFromBuff(glw::fbuffer* buff, Canvas* drawer); - void free(Canvas* drawer); - ~ImageHandle(); - }; - - void drawImage(Rect rec, ImageHandle* image, halnf angle = 0.f, halnf alpha = 1.f, halnf rounding = 0.f); - - ~Canvas(); - }; - }; -}; \ No newline at end of file diff --git a/.outdated/graphics/inc/debugui.h b/.outdated/graphics/inc/debugui.h deleted file mode 100644 index f3cee0a..0000000 --- a/.outdated/graphics/inc/debugui.h +++ /dev/null @@ -1,48 +0,0 @@ - -#include "window.h" - -namespace ImGui { - - bool SubMenuBegin(const char* desc, int level); - void SubMenuEnd(int level); - - void ToolTip(const char* desc); - - struct PopupData { - bool opened = false; - bool ishovered = false; - tp::vec2f p1 = 0; - tp::vec2f p2 = 0; - operator bool() { - return opened; - } - }; - - PopupData HoverPopupBeginButton(const char* id, tp::vec2f butsize = 200, tp::vec2f popupsize = 200); - PopupData HoverPopupBegin(const char* id, tp::vec2f size = 200, tp::vec2f pos = -1, int flags = 0); - void HoverPopupEnd(PopupData& in); - - void ApplyStyle(tp::halnf dpmm, float font_size_mm = 5, float ui_scale = 1); -}; - -namespace tp { - namespace glw { - - typedef void (DebugUiDrawCallBack)(void* cd); - - struct DebugUI { - tp::halnf mDPMM = 1; - tp::halnf mFontSizeMM = 3; - tp::halnf mUIScale = 1; - - DebugUiDrawCallBack* cb = NULL; - void* cd = NULL; - - struct DebugUiInternalContext* mCtx = NULL; - - DebugUI(Window& window, DebugUiDrawCallBack* acb, void* acd); - void drawDebugUI(tp::halnf dpmm); - ~DebugUI(); - }; - }; -}; \ No newline at end of file diff --git a/.outdated/graphics/inc/fbuffer.h b/.outdated/graphics/inc/fbuffer.h deleted file mode 100644 index f353313..0000000 --- a/.outdated/graphics/inc/fbuffer.h +++ /dev/null @@ -1,40 +0,0 @@ - -#pragma once - -#include "rect.h" -#include "color.h" - -namespace tp { - namespace glw { - class fbuffer { - - uint4 mFrameBufferID = 0; // regroups 0, 1, or more textures, and 0 or 1 depth buffer. - uint4 mTextureId = 0; // texture we're going to render to ( colour attachement #0 ) - uint4 mDepthBufferID = 0; - uint4 mDrawBuffers[1]; - - vec2f mSize; - - public: - - rgba mClearCol = 0.f; - - fbuffer(const vec2f& size); - fbuffer(const vec2f& size, tp::uint1 samples); - - void beginDraw(); - void setViewport(const rectf& viewport); - void clear(); - void endDraw(); - - uint4 texId() const; - uint4 buffId() const; - - const vec2f& getSize() const; - uhalni sizeAllocatedMem() const; - uhalni sizeUsedMem() const; - - ~fbuffer(); - }; - }; -}; \ No newline at end of file diff --git a/.outdated/graphics/inc/keycodes.h b/.outdated/graphics/inc/keycodes.h deleted file mode 100644 index e947363..0000000 --- a/.outdated/graphics/inc/keycodes.h +++ /dev/null @@ -1,167 +0,0 @@ - -#pragma once - -namespace tp { - - // basically copy of glfw keys - enum class Keycode { - - /* Printable keys */ - SPACE = 32, - APOSTROPHE = 39, /* ' */ - COMMA = 44, /* , */ - MINUS = 45, /* - */ - PERIOD = 46, /* . */ - SLASH = 0xBF, /* \ */ - N0 = 48, - N1 = 49, - N2 = 50, - N3 = 51, - N4 = 52, - N5 = 53, - N6 = 54, - N7 = 55, - N8 = 56, - N9 = 57, - SEMICOLON = 59, /* ; */ - EQUAL = 61, /* = */ - A = 65, - B = 66, - C = 67, - D = 68, - E = 69, - F = 70, - G = 71, - H = 72, - I = 73, - J = 74, - K = 75, - L = 76, - M = 77, - N = 78, - O = 79, - P = 80, - Q = 81, - R = 82, - S = 83, - T = 84, - U = 85, - V = 86, - W = 87, - X = 88, - Y = 89, - Z = 90, - LEFT_BRACKET = 91, /* [ */ - BACKSLASH = 92, /* \ */ - RIGHT_BRACKET = 93, /* ] */ - GRAVE_ACCENT = 96, /* ` */ - WORLD_1 = 161, /* non-US #1 */ - WORLD_2 = 162, /* non-US #2 */ - - /* function keys */ - - ESCAPE = 256, - ENTER = 257, - TAB = 258, - BACKSPACE = 259, - INSERT = 260, - DELETE = 261, - RIGHT = 262, - LEFT = 263, - DOWN = 264, - UP = 265, - PAGE_UP = 266, - PAGE_DOWN = 267, - HOME = 268, - END = 269, - CAPS_LOCK = 280, - SCROLL_LOCK = 281, - NUM_LOCK = 282, - PRINT_SCREEN = 283, - PAUSE = 284, - F1 = 290, - F2 = 291, - F3 = 292, - F4 = 293, - F5 = 294, - F6 = 295, - F7 = 296, - F8 = 297, - F9 = 298, - F10 = 299, - F11 = 300, - F12 = 301, - F13 = 302, - F14 = 303, - F15 = 304, - F16 = 305, - F17 = 306, - F18 = 307, - F19 = 308, - F20 = 309, - F21 = 310, - F22 = 311, - F23 = 312, - F24 = 313, - F25 = 314, - KP_0 = 320, - KP_1 = 321, - KP_2 = 322, - KP_3 = 323, - KP_4 = 324, - KP_5 = 325, - KP_6 = 326, - KP_7 = 327, - KP_8 = 328, - KP_9 = 329, - KP_DECIMAL = 330, - KP_DIVIDE = 331, - KP_MULTIPLY = 332, - KP_SUBTRACT = 333, - KP_ADD = 334, - KP_ENTER = 335, - KP_EQUAL = 336, - LEFT_SHIFT = 340, - LEFT_CONTROL = 341, - LEFT_ALT = 342, - LEFT_SUPER = 343, - RIGHT_SHIFT = 344, - RIGHT_CONTROL = 345, - RIGHT_ALT = 346, - RIGHT_SUPER = 347, - MENU = 348, - - INV_SLASH = 0xDC, - BRA = 0xDB, - KET = 0xDD, - TILDA = 0xC0, - DOUBLE_DOT = 0xBA, - QUOTES = 0xDE, - - MOUSE1 = 501, - MOUSE2 = 502, - MOUSE3 = 503, - MOUSE4 = 504, - MOUSE5 = 505, - MOUSE_UP = 506, - MOUSE_DOWN = 507, - }; - - - enum class Keystate { - PRESSED, - RELEASED, - HOLD, - REPEAT, - NONE, - }; - - struct KeyEvent { - Keycode code; - enum class EventState { - RELEASED = 0, - PRESSED = 1, - REPEAT = 2, - } event_state; - }; -}; \ No newline at end of file diff --git a/.outdated/graphics/inc/shader.h b/.outdated/graphics/inc/shader.h deleted file mode 100644 index 8335a8b..0000000 --- a/.outdated/graphics/inc/shader.h +++ /dev/null @@ -1,36 +0,0 @@ - -#pragma once - -namespace tp { - namespace glw { - class shader { - - uint4 programm; - uint4 VertexShaderID; - uint4 FragmentShaderID; - uint4 GeometryShaderID; - - public: - - bool compile_shader(const char* ShaderCode, uint4 ShaderID); - void load(const char* vert, const char* geom, const char* frag, bool paths); - - shader(); - - void vert_bind_source(const char* vert_src); - void frag_bind_source(const char* frag_src); - void geom_bind_source(const char* geom_src); - - void compile(); - - shader(const char* vertid, const char* geomid, const char* fragid, bool paths = true); - void bind(); - uint4 getu(const char* uid); - void unbind(); - ~shader(); - - alni sizeAllocatedMem(); - alni sizeUsedMem(); - }; - }; -}; \ No newline at end of file diff --git a/.outdated/graphics/inc/simplegui.h b/.outdated/graphics/inc/simplegui.h deleted file mode 100644 index 2d6eaf5..0000000 --- a/.outdated/graphics/inc/simplegui.h +++ /dev/null @@ -1,71 +0,0 @@ -#pragma once - -#include "window.h" -#include "canvas.h" -#include "animations.h" - -namespace tp { - namespace glw { - - class WindowSimpleInputs { - enum class Mouse : uint1 { NONE, PRESSED, HOLD, RELEASED } mMouse; - enum class Move : uint1 { NONE, LEFT, RIGHT, UP, DOWN } mMove; - public: - - halnf mScaleVal = 0; - vec2f mWindowSizeMM; - vec2f mCrs; - vec2f mCrsPrev; - vec2f mCrsmDelta; - halnf mPressure = 0.f; - - void update(const glw::Window& window, halnf uiscale); - bool Activated(); - bool Anticipating(); - bool Selected(); - bool MoveLeft(); - bool MoveRight(); - bool MoveUp(); - bool MoveDown(); - bool Drag(); - }; - - struct ButtonWidget { - rectf mRect = { 0.f, 10.f }; - rgba mCol = { 0.3f, 0.3f, 0.3f, 1.f }; - bool mPressed = false; - AnimRect mAnimRec; - void draw(glw::Canvas& canvas); - void proc(glw::WindowSimpleInputs& inputs); - }; - - struct CheckBoxWidget { - rectf mRect = { 0.f, 10.f }; - rgba mCol = { 0.3f, 0.3f, 0.3f, 1.f }; - rgba mColActive = { 0.5f, 0.5f, 0.5f, 1.f }; - - bool mValue = false; - AnimRect mAnimRec; - AnimColor mAnimCol; - - void draw(glw::Canvas& canvas); - void proc(glw::WindowSimpleInputs& inputs); - }; - - struct WindowsHeaderWidget { - rectf header_rec = { 10, 10, 50, 10 }; - rgba col = { 0.13f, 0.13f, 0.13f, 0.9f }; - rectf grab_rec = 0.f; - - ButtonWidget mExitButton; - ButtonWidget mMaxButton; - ButtonWidget mMinButton; - CheckBoxWidget mPinButton; - - void updRecs(); - void draw(glw::Canvas& canvas); - void proc(glw::Window& window, glw::WindowSimpleInputs& inputs); - }; - - }; -}; \ No newline at end of file diff --git a/.outdated/graphics/inc/texture.h b/.outdated/graphics/inc/texture.h deleted file mode 100644 index 6a7c3d5..0000000 --- a/.outdated/graphics/inc/texture.h +++ /dev/null @@ -1,31 +0,0 @@ - -#pragma once - -#include "array2d.h" -#include "color.h" -#include "vec.h" - -namespace tp { - namespace glw { - class texture { - uint4 id; - public: - - texture(); - ~texture(); - - uint4 getid(); - void update(const Array2D& buff); - void draw(const uint4& out = 0); - - alni sizeAllocatedMem(); - alni sizeUsedMem(); - - static void init(); - static void deinit(); - static void draw_texture(uint4 out, uint4 in); - static uint4 get_tex(const char* TexId); - static void drawCurcle(vec2f pos, double radius, rgba col); - }; - }; -}; \ No newline at end of file diff --git a/.outdated/graphics/inc/window.h b/.outdated/graphics/inc/window.h deleted file mode 100644 index 23c1b32..0000000 --- a/.outdated/graphics/inc/window.h +++ /dev/null @@ -1,114 +0,0 @@ - -#pragma once - -#include "common.h" -#include "vec.h" -#include "rect.h" -#include "color.h" -#include "stringt.h" -#include "array.h" -#include "map.h" - -#include "keycodes.h" -#include "queue.h" - -namespace tp { - - extern tp::ModuleManifest gModuleGlw; - - namespace glw { - - struct PlatformContext; - - class Window { - - public: - - struct Device { - time_ms FrameRate = NULL; // monitor fps - vec2f Size; // size of the monitor - tp::halnf mDPMM = 1; - }; - - struct Events { - tp::Queue mKeysQueue; - tp::uhalni mRedraw = 2; - bool mClose = false; - - vec2f mCursor = 0; - halnf mPressure = 1.f; - - vec2f mCursorPrev = 0.f; - halnf mPressurePrev = 1.f; - }; - - struct Appearence { - vec2f mPos = { 100.f, 100.f }; // global position - vec2f mSize = { 300.f, 300.f }; // width and height of window - vec2f mSizeMin = { 100.f, 100.f }; // min size possiable - vec2f mSizeMax = { 700.f, 700.f }; // max size possiable - - bool mHiden = true; - bool mMaximized = false; - bool mMinimized = false; - bool mTopZ = false; - bool mAllDesktops = false; - - rgba mResizeColor = rgba(0.13f, 0.13f, 0.13f, 0.9f); - - rectf mMinMaxBox; - - tp::Array mCaptionsAddArea; - tp::Array mCaptionsRemoveArea; - }; - - public: - - PlatformContext* mPlatformCtx = NULL; - void platformCallback(); - void* platform_window() const; - - struct NativeEventListenerCallback { - typedef void (call_back_func)(PlatformContext* ctx, void* cd); - call_back_func* exec_begin = NULL; - call_back_func* exec = NULL; - call_back_func* exec_end = NULL; - void* cd = NULL; - }; - - tp::HashMap mNativeEventListeners; - - private: - - struct Cache { - Appearence mAppearencePrev; - vec2f mWindowSize = 0; - rectf mRectBeforResizing = 0; - bool mUserResizing = false; - bool mMinMaxHover = false; - bool mMouseTracked = false; - } mCache; - - void applyAppearance(); - void initialize(); - - public: - - static Device mDevice; - Appearence mAppearence; - Events mEvents; - - Window(); - Window(const Appearence& aAppearence); - - void pollEvents(); - void beginDraw(); - void endDraw(); - - alni sizeAllocatedMem(); - alni sizeUsedMem(); - - ~Window(); - }; - }; -}; \ No newline at end of file diff --git a/.outdated/graphics/rsc/fonts/CONSOLAB.TTF b/.outdated/graphics/rsc/fonts/CONSOLAB.TTF deleted file mode 100644 index ef6d555..0000000 Binary files a/.outdated/graphics/rsc/fonts/CONSOLAB.TTF and /dev/null differ diff --git a/.outdated/graphics/src/android_api.h b/.outdated/graphics/src/android_api.h deleted file mode 100644 index d590d32..0000000 --- a/.outdated/graphics/src/android_api.h +++ /dev/null @@ -1,25 +0,0 @@ - -#pragma once - -#include "queue.h" - -struct AndroidApi { - - union Event { - - enum Type : tp::uint1 { - EV_NONE = 0, - } type = EV_NONE; - - struct None { - - } none; - - - }; - - tp::Queue events; - -}; - -extern AndroidApi* gAndroidApi; \ No newline at end of file diff --git a/.outdated/graphics/src/android_main.cpp b/.outdated/graphics/src/android_main.cpp deleted file mode 100644 index bcc64af..0000000 --- a/.outdated/graphics/src/android_main.cpp +++ /dev/null @@ -1,804 +0,0 @@ - - // Copyright (C) 2010 The Android Open Source Project - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - -// own headers -#include "window.h" - -#include "GraphicsLibApi.h" - -// STL -#include -#include -#include -#include -#include -#include - -// jni -//#include -//#include -//#include -//#include -#include -//#include -//#include - -// opengl -#include -#include -//#include "GL/glew.h" - -// glue -#include -#include -#include -#include <../../../android/native_app_glue/android_native_app_glue.h> - -// AcquireASensorManagerInstance -#include - -#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "native-activity", __VA_ARGS__)) -#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "native-activity", __VA_ARGS__)) - -// application side entry point -int main(); - -// first function to be called in "main thread" -void* main_wrap(void* p); - - // AcquireASensorManagerInstance(void) - // Workaround ASensorManager_getInstance() deprecation false alarm - // for Android-N and before, when compiling with NDK-r15 -ASensorManager* AcquireASensorManagerInstance(android_app* app) { - - if (!app) - return nullptr; - - typedef ASensorManager* (*PF_GETINSTANCEFORPACKAGE)(const char* name); - void* androidHandle = dlopen("libandroid.so", RTLD_NOW); - auto getInstanceForPackageFunc = (PF_GETINSTANCEFORPACKAGE) - dlsym(androidHandle, "ASensorManager_getInstanceForPackage"); - if (getInstanceForPackageFunc) { - JNIEnv* env = nullptr; - app->activity->vm->AttachCurrentThread(&env, nullptr); - - jclass android_content_Context = env->GetObjectClass(app->activity->clazz); - jmethodID midGetPackageName = env->GetMethodID(android_content_Context, - "getPackageName", - "()Ljava/lang/String;"); - auto packageName = (jstring)env->CallObjectMethod(app->activity->clazz, - midGetPackageName); - - const char* nativePackageName = env->GetStringUTFChars(packageName, nullptr); - ASensorManager* mgr = getInstanceForPackageFunc(nativePackageName); - env->ReleaseStringUTFChars(packageName, nativePackageName); - app->activity->vm->DetachCurrentThread(); - if (mgr) { - dlclose(androidHandle); - return mgr; - } - } - - typedef ASensorManager* (*PF_GETINSTANCE)(); - auto getInstanceFunc = (PF_GETINSTANCE) - dlsym(androidHandle, "ASensorManager_getInstance"); - // by all means at this point, ASensorManager_getInstance should be available - assert(getInstanceFunc); - dlclose(androidHandle); - - return getInstanceFunc(); -} - -void GL_APIENTRY MessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { - DBG_BREAK(true); - LOGW("GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n", (type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : ""), type, severity, message); -} - -char const* gl_error_string(GLenum const err) { - switch (err) { - case GL_NO_ERROR: return "GL_NO_ERROR"; - case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; - case GL_INVALID_VALUE: return "GL_INVALID_VALUE"; - case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION"; - case GL_STACK_OVERFLOW: return "GL_STACK_OVERFLOW"; - case GL_STACK_UNDERFLOW: return "GL_STACK_UNDERFLOW"; - case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY"; - case GL_INVALID_FRAMEBUFFER_OPERATION: return "GL_INVALID_FRAMEBUFFER_OPERATION"; - default: return "unknown error"; - } -} - -void glerr(GLenum type) { - DBG_BREAK(true); - const GLchar* message = gl_error_string(type); - LOGW("GL CALLBACK: %s type = 0x%x, message = %s\n", (type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : ""), type, message); -} - -void glerr(GLenum type); -#define AssertGL(x) { x; GLenum __gle = glGetError(); if (__gle != GL_NO_ERROR) glerr(__gle); } - -// --------------------------------- Data --------------------------------------- // - -struct MutexEvent { - pthread_mutex_t mutex; - tp::glw::Window* active_windw; - bool parent_thread_has_events = false; - bool child_whaiting = false; -} mutex_event; - -struct ANativeActivityCtx* android_ctx = NULL; - -tp::glw::Window::Device tp::glw::Window::mDevice; -extern const char* g_android_internal_data_path; - -static pthread_t worker_thread; -static pthread_mutex_t worker_finished_mutex; -static pthread_cond_t worker_finished_cond; -static bool worker_finished = false; - -namespace tp { - namespace glw { - struct PlatformContext { - - int col = 255; - - EGLint w, h, format; - EGLint numConfigs; - EGLConfig config = nullptr; - EGLSurface surface; - EGLContext context; - EGLDisplay display = nullptr; - - AInputEvent* chache_event = NULL; - - EGLint majorVersion, minorVersion; - - // Initialize an EGL context for the current display. - PlatformContext(ANativeWindow* window) { - - display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - if (EGL_NO_DISPLAY == display) { - return; - } - - - if (eglInitialize(display, &majorVersion, &minorVersion) != EGL_TRUE) { - return; - } - - - // Here specify the attributes of the desired configuration. - // Below, we select an EGLConfig with at least 8 bits per color component compatible with on-screen windows - const EGLint attribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, // request OpenGL ES 3.0 - EGL_BLUE_SIZE, 8, - EGL_GREEN_SIZE, 8, - EGL_RED_SIZE, 8, - EGL_DEPTH_SIZE, GLW_CONTEXT_DEPTH_BITS, - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_NONE - }; - - // Here, the application chooses the configuration it desires. - // find the best match if possible, otherwise use the very first one - { - if (eglChooseConfig(display, attribs, nullptr, 0, &numConfigs) != EGL_TRUE) { - return; - } - - std::unique_ptr supportedConfigs(new EGLConfig[numConfigs]); - assert(supportedConfigs); - - if (eglChooseConfig(display, attribs, supportedConfigs.get(), numConfigs, &numConfigs) != EGL_TRUE) { - return; - } - - assert(numConfigs); - auto i = 0; - for (; i < numConfigs; i++) { - auto& cfg = supportedConfigs[i]; - EGLint r, g, b, d; - if (eglGetConfigAttrib(display, cfg, EGL_RED_SIZE, &r) && - eglGetConfigAttrib(display, cfg, EGL_GREEN_SIZE, &g) && - eglGetConfigAttrib(display, cfg, EGL_BLUE_SIZE, &b) && - eglGetConfigAttrib(display, cfg, EGL_DEPTH_SIZE, &d) && - r == 8 && g == 8 && b == 8 && d == GLW_CONTEXT_DEPTH_BITS) { - - config = supportedConfigs[i]; - break; - } - } - - if (i == numConfigs) { - config = supportedConfigs[0]; - } - - if (config == nullptr) { - LOGW("Unable to initialize EGLConfig"); - return; - } - } - - const EGLint egl_context_attributes[] = { - EGL_CONTEXT_CLIENT_VERSION, 3, - //EGL_CONTEXT_MAJOR_VERSION, 3, - //EGL_CONTEXT_MINOR_VERSION, 0, - EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, -#ifdef ENV_BUILD_DEBUG - //EGL_CONTEXT_OPENGL_DEBUG, EGL_TRUE, -#endif - EGL_NONE - }; - - // EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is - // guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). - // As soon as we picked a EGLConfig, we can safely reconfigure the - // ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID - eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); - surface = eglCreateWindowSurface(display, config, window, nullptr); - context = eglCreateContext(display, config, EGL_NO_CONTEXT, egl_context_attributes); - - if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { - LOGW("Unable to eglMakeCurrent"); - return; - } - - eglQuerySurface(display, surface, EGL_WIDTH, &w); - eglQuerySurface(display, surface, EGL_HEIGHT, &h); - - // Check openGL on the system - auto opengl_info = { GL_VENDOR, GL_RENDERER, GL_VERSION, GL_EXTENSIONS }; - for (auto name : opengl_info) { - auto info = glGetString(name); - LOGI("OpenGL Info: %s", info); - } - - // Initialize GL state. - //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); - AssertGL(glEnable(GL_CULL_FACE)); - //AssertGL(glShadeModel(GL_SMOOTH)); - AssertGL(glEnable(GL_DEPTH_TEST)); - AssertGL(glDepthFunc(GL_LESS)); - - GLint major = 0; - GLint minor = 0; - glGetIntegerv(GL_MAJOR_VERSION, &major); - glGetIntegerv(GL_MINOR_VERSION, &minor); - - glGetIntegerv(GL_DEPTH, &minor); - - AssertGL(glEnable(GL_DEBUG_OUTPUT)); - AssertGL(glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS)); - AssertGL(glDebugMessageCallback(MessageCallback, 0)); - - tp::glw::Window::mDevice.Size = { w, h }; - tp::glw::Window::mDevice.FrameRate = 60; - - return; - } - - void beginDraw() { - if (this->display == nullptr) { return; } - - glViewport(0, 0, tp::glw::Window::mDevice.Size.x, tp::glw::Window::mDevice.Size.y); - - //glClearColor(col / 255.f, col / 255.f, col / 255.f, 1); - //glClear(GL_COLOR_BUFFER_BIT); - - //if (col++ > 255) { - //col = 0; - //} - } - - void endDraw() { - eglSwapBuffers(display, surface); - } - - // Tear down the EGL context currently associated with the display. - ~PlatformContext() { - if (this->display != EGL_NO_DISPLAY) { - eglMakeCurrent(this->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - if (this->context != EGL_NO_CONTEXT) { - eglDestroyContext(this->display, this->context); - } - if (this->surface != EGL_NO_SURFACE) { - eglDestroySurface(this->display, this->surface); - } - eglTerminate(this->display); - } - - display = EGL_NO_DISPLAY; - context = EGL_NO_CONTEXT; - surface = EGL_NO_SURFACE; - } - }; - }; -}; - -// ---------------------------------- Parent Thread ------------------------------------ // -#ifndef PARENT_THREAD - -// Shared state for our app. -struct ANativeActivityCtx { - - // Our saved state data. - struct saved_state { - float angle; - int32_t x; - int32_t y; - }; - - android_app* app; - - ASensorManager* sensorManager; - const ASensor* accelerometerSensor; - ASensorEventQueue* sensorEventQueue; - - int animating; - EGLDisplay display; - EGLSurface surface; - EGLContext context; - int32_t width; - int32_t height; - saved_state state; - - ANativeActivityCtx(android_app* state) { - memset(this, 0, sizeof(*this)); - - state->userData = this; - state->onAppCmd = engine_handle_cmd; - state->onInputEvent = engine_handle_input; - - app = state; - - // Prepare to monitor accelerometer - sensorManager = AcquireASensorManagerInstance(state); - accelerometerSensor = ASensorManager_getDefaultSensor(sensorManager, ASENSOR_TYPE_ACCELEROMETER); - sensorEventQueue = ASensorManager_createEventQueue(sensorManager, state->looper, LOOPER_ID_USER, 0, 0); - - // We are starting with a previous saved state; restore from it. - if (state->savedState != nullptr) { - this->state = *(saved_state*)state->savedState; - } - } - - void proc_events_util() { - int ident; - int events; - struct android_poll_source* source; - - auto window = mutex_event.active_windw; - - if (window) { - for (auto proc : window->mNativeEventListeners) { - proc->val.exec_begin(window->mPlatformCtx, proc->val.cd); - } - } - - // we loop until all events are read - while ((ident = ALooper_pollAll(0, nullptr, &events, (void**)&source)) >= 0) { - - // Process this event. - if (source != nullptr) { - source->process(this->app, source); - } - - // If a sensor has data, process it now. - if (ident == LOOPER_ID_USER) { - if (this->accelerometerSensor != nullptr) { - ASensorEvent event; - while (ASensorEventQueue_getEvents(this->sensorEventQueue, &event, 1) > 0) { - LOGI("accelerometer: x=%f y=%f z=%f", event.acceleration.x, event.acceleration.y, event.acceleration.z); - } - } - } - - // Check if we are exiting. - if (this->app->destroyRequested != 0) { - DBG_BREAK(1); - } - } - - if (window) { - for (auto proc : window->mNativeEventListeners) { - proc->val.exec_end(window->mPlatformCtx, proc->val.cd); - } - } - } - - void proc_events() { - - pthread_mutex_lock(&mutex_event.mutex); - auto threaded = mutex_event.active_windw; - pthread_mutex_unlock(&mutex_event.mutex); - - if (!threaded) { - proc_events_util(); - return; - } - - // Read all pending events. - int ident; - int events; - struct android_poll_source* source; - - // check if events exist and if so prepare to proccess them - if ((ident = ALooper_pollAll(0, nullptr, &events, (void**)&source)) >= 0) { - - // signal child thread that we need to process those events - pthread_mutex_lock(&mutex_event.mutex); - mutex_event.parent_thread_has_events = true; - pthread_mutex_unlock(&mutex_event.mutex); - - // whait until child thread pauses - bool whait = true; - - while (whait) { - pthread_mutex_lock(&mutex_event.mutex); - whait = !mutex_event.child_whaiting; - pthread_mutex_unlock(&mutex_event.mutex); - } - } - else { - return; - } - - - pthread_mutex_lock(&mutex_event.mutex); - auto window = mutex_event.active_windw; - pthread_mutex_unlock(&mutex_event.mutex); - - proc_events_util(); - - // signal to child continue to do its work - pthread_mutex_lock(&mutex_event.mutex); - mutex_event.parent_thread_has_events = false; - pthread_mutex_unlock(&mutex_event.mutex); - } - - // Process the next input event. - static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) { - auto* engine = (struct ANativeActivityCtx*)app->userData; - auto window = mutex_event.active_windw; - - if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { - window->mEvents.mCursorPrev = window->mEvents.mCursor; - - window->mEvents.mCursor.x = AMotionEvent_getX(event, 0); - window->mEvents.mCursor.y = AMotionEvent_getY(event, 0); - - window->mEvents.mRedraw = 2; - - int32_t event_action = AMotionEvent_getAction(event); - int32_t event_pointer_index = (event_action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - event_action &= AMOTION_EVENT_ACTION_MASK; - - if ((AMotionEvent_getToolType(event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_FINGER) - || (AMotionEvent_getToolType(event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_UNKNOWN)) { - - if (event_action == AMOTION_EVENT_ACTION_DOWN) { - window->mEvents.mKeysQueue.push(tp::KeyEvent{ tp::Keycode::MOUSE1, tp::KeyEvent::EventState::PRESSED }); - } - else if (event_action == AMOTION_EVENT_ACTION_UP) { - window->mEvents.mKeysQueue.push(tp::KeyEvent{ tp::Keycode::MOUSE1, tp::KeyEvent::EventState::RELEASED }); - } - } - } - - if (window) { - window->mPlatformCtx->chache_event = event; - for (auto proc : window->mNativeEventListeners) { - proc->val.exec(window->mPlatformCtx, proc->val.cd); - } - } - - return 0; - } - - // Process the next main command. - static void engine_handle_cmd(struct android_app* app, int32_t cmd) { - auto* engine = (struct ANativeActivityCtx*)app->userData; - auto window = mutex_event.active_windw; - - switch (cmd) { - - // The system has asked us to save our current state. Do so. - case APP_CMD_SAVE_STATE: { - engine->app->savedState = malloc(sizeof(ANativeActivityCtx::saved_state)); - *((ANativeActivityCtx::saved_state*)engine->app->savedState) = engine->state; - engine->app->savedStateSize = sizeof(ANativeActivityCtx::saved_state); - } break; - - // The window is being shown, get it ready. - case APP_CMD_INIT_WINDOW: { - if (engine->app->window != nullptr) { - //engine->init_display(); - //engine->draw_frame(); - } - } break; - - // The window is being hidden or closed, clean it up. - case APP_CMD_TERM_WINDOW: { - //engine->term_display(); - } break; - - // When our app gains focus, we start monitoring the accelerometer. - case APP_CMD_GAINED_FOCUS: { - if (engine->accelerometerSensor != nullptr) { - ASensorEventQueue_enableSensor(engine->sensorEventQueue, - engine->accelerometerSensor); - // We'd like to get 60 events per second (in us). - ASensorEventQueue_setEventRate(engine->sensorEventQueue, - engine->accelerometerSensor, - (1000L / 60) * 1000); - } - } break; - - // When our app loses focus, we stop monitoring the accelerometer. - // This is to avoid consuming battery while not being used. - case APP_CMD_LOST_FOCUS: { - if (engine->accelerometerSensor != nullptr) { - ASensorEventQueue_disableSensor(engine->sensorEventQueue, - engine->accelerometerSensor); - } - // Also stop animating. - engine->animating = 0; - //engine->draw_frame(); - } break; - - default: break; - } - } - -}; - -#include - -void unsure_dir_exist(const char* path_to_file) { - char* temp_path = strdup(path_to_file); - - for (char* p = temp_path + 1; *p; p++) { - if (*p == '/') { - *p = '\0'; - int status = mkdir(temp_path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); - if (status != 0 && errno != EEXIST) { - // handle error - break; - } - *p = '/'; - } - } - - free(temp_path); -} - -// FIXME -void unpackAsset(AAssetManager* mgr, const char* filename, const std::string& path) { - AAsset* asset = AAssetManager_open(mgr, filename, AASSET_MODE_STREAMING); - if (asset == NULL) { - return; - } - off_t length = AAsset_getLength(asset); - char* buffer = new char[length]; - AAsset_read(asset, buffer, length); - - unsure_dir_exist(path.c_str()); - FILE* out = fopen(path.c_str(), "w"); - if (out != NULL) { - fwrite(buffer, length, 1, out); - fclose(out); - } - delete[] buffer; - AAsset_close(asset); -} - -// FIXME -void unpackDirectory(AAssetManager* mgr, const char* dirname, const std::string& path) { - - AAssetDir* assetDir = AAssetManager_openDir(mgr, dirname); - const char* filename = NULL; - - while ((filename = AAssetDir_getNextFileName(assetDir)) != NULL) { - std::string assetPath = std::string(dirname) + "/" + filename; - std::string internalPath = path + "/" + std::string(dirname) + "/" + filename; - - struct stat sb; - stat(assetPath.c_str(), &sb); - if (S_ISDIR(sb.st_mode)) { - unpackDirectory(mgr, assetPath.c_str(), internalPath); - } - else { - unpackAsset(mgr, assetPath.c_str(), internalPath); - } - } - AAssetDir_close(assetDir); -} - -extern "C" { - - // This is the main entry point of a native application that is using - // android_native_app_glue. It runs in its own thread, with its own - // event loop for receiving input events and doing other things. - void android_main(android_app* state) { - - tp::print_env_info(); - tp::alloc_init(); - - ANativeActivityCtx engine(state); - - unpackDirectory(state->activity->assetManager, "", state->activity->internalDataPath); - unpackDirectory(state->activity->assetManager, "rsc", state->activity->internalDataPath); - unpackDirectory(state->activity->assetManager, "rsc/fonts", state->activity->internalDataPath); - - android_ctx = &engine; - - bool running = true; - while (running) { - - engine.proc_events(); - - // whait until our app fully initialized - if (!engine.app->window) { - continue; - } - - // run once - static bool main_thread_started = false; - if (!main_thread_started) { - - // init types - g_android_internal_data_path = state->activity->internalDataPath; - - // create main thread - pthread_create(&worker_thread, NULL, main_wrap, NULL); - pthread_mutex_init(&worker_finished_mutex, NULL); - pthread_cond_init(&worker_finished_cond, NULL); - - main_thread_started = true; - continue; - } - - // check for exit - pthread_mutex_lock(&worker_finished_mutex); - running = !worker_finished; - pthread_mutex_unlock(&worker_finished_mutex); - } - - pthread_join(worker_thread, NULL); - - tp::alloc_uninit(); - } -}; -#endif - - -// ------------------------------- Child thread --------------------------------------- // -#ifndef CHILD_THREAD - -//#include -//#include - -AInputEvent* androidPlatformContextGetEvent(tp::glw::PlatformContext* ctx) { - return ctx->chache_event; -} - -int32_t getDensityDpi(android_app* app) { - AConfiguration* config = AConfiguration_new(); - AConfiguration_fromAssetManager(config, app->activity->assetManager); - int32_t density = AConfiguration_getDensity(config); - AConfiguration_delete(config); - return density; -} - -// statics -void tp::glw::Window::init() {} -void tp::glw::Window::deinit() {} - -void tp::glw::Window::initialize() { - mPlatformCtx = new PlatformContext(android_ctx->app->window); - applyAppearance(); - - - AConfiguration* config = AConfiguration_new(); - AConfiguration_fromAssetManager(config, android_ctx->app->activity->assetManager); - int32_t density = AConfiguration_getDensity(config); - AConfiguration_delete(config); - - mDevice.mDPMM = density / 25.4f; -} - -tp::glw::Window::Window() { - initialize(); - - pthread_mutex_lock(&mutex_event.mutex); - mutex_event.active_windw = this; - pthread_mutex_unlock(&mutex_event.mutex); -} - -tp::glw::Window::Window(const Appearence& aAppearence) { - mAppearence = aAppearence; - initialize(); -} - -tp::glw::Window::~Window() { - delete mPlatformCtx; -} - -void tp::glw::Window::applyAppearance() { - int width = ANativeWindow_getWidth(android_ctx->app->window); - int height = ANativeWindow_getHeight(android_ctx->app->window); - - if (width != mAppearence.mSize.x || height != mAppearence.mSize.y) { - mEvents.mRedraw = 2; - } - - mAppearence.mPos = mCache.mAppearencePrev.mPos = 0; - mAppearence.mSize.x = mCache.mAppearencePrev.mSize.x = tp::glw::Window::mDevice.Size.x = width; - mAppearence.mSize.y = mCache.mAppearencePrev.mSize.y = tp::glw::Window::mDevice.Size.y = height; -} - -void tp::glw::Window::pollEvents() { - applyAppearance(); - - // check if parent thread has some events to pass - - pthread_mutex_lock(&mutex_event.mutex); - bool has_event = mutex_event.parent_thread_has_events; - mutex_event.child_whaiting = has_event; - pthread_mutex_unlock(&mutex_event.mutex); - - while (has_event) { - pthread_mutex_lock(&mutex_event.mutex); - has_event = mutex_event.parent_thread_has_events; - pthread_mutex_unlock(&mutex_event.mutex); - } - - pthread_mutex_lock(&mutex_event.mutex); - mutex_event.child_whaiting = false; - pthread_mutex_unlock(&mutex_event.mutex); -} - -void tp::glw::Window::platformCallback() {} - -void tp::glw::Window::beginDraw() { - mPlatformCtx->beginDraw(); -} - -void tp::glw::Window::endDraw() { - mPlatformCtx->endDraw(); - if (mEvents.mRedraw-- < 0) mEvents.mRedraw = 0; -} - -void* tp::glw::Window::platform_window() const { return android_ctx->app->window; } - -tp::alni tp::glw::Window::sizeAllocatedMem() { return 0; } - -tp::alni tp::glw::Window::sizeUsedMem() { return 0; } - - -void* main_wrap(void* p) { - - // exec main - main(); - - // mark as doen after completion - pthread_mutex_lock(&worker_finished_mutex); - worker_finished = true; - pthread_cond_signal(&worker_finished_cond); - pthread_mutex_unlock(&worker_finished_mutex); - - // exit "main thread" - pthread_exit(NULL); - - return NULL; -} - -#endif \ No newline at end of file diff --git a/.outdated/graphics/src/android_native_app_glue.c b/.outdated/graphics/src/android_native_app_glue.c deleted file mode 100644 index db624a1..0000000 --- a/.outdated/graphics/src/android_native_app_glue.c +++ /dev/null @@ -1,453 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "android_native_app_glue.h" - -#include - -#include -#include -#include -#include - -#include - -#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "threaded_app", __VA_ARGS__)) -#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "threaded_app", __VA_ARGS__)) - -/* For debug builds, always enable the debug traces in this library */ -#ifndef NDEBUG -# define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "threaded_app", __VA_ARGS__)) -#else -# define LOGV(...) ((void)0) -#endif - - void free_saved_state(struct android_app* android_app) { - pthread_mutex_lock(&android_app->mutex); - if (android_app->savedState != NULL) { - free(android_app->savedState); - android_app->savedState = NULL; - android_app->savedStateSize = 0; - } - pthread_mutex_unlock(&android_app->mutex); -} - -int8_t android_app_read_cmd(struct android_app* android_app) { - int8_t cmd; - if (read(android_app->msgread, &cmd, sizeof(cmd)) != sizeof(cmd)) { - LOGE("No data on command pipe!"); - return -1; - } - if (cmd == APP_CMD_SAVE_STATE) free_saved_state(android_app); - return cmd; -} - - void print_cur_config(struct android_app* android_app) { - char lang[2], country[2]; - AConfiguration_getLanguage(android_app->config, lang); - AConfiguration_getCountry(android_app->config, country); - - LOGV("Config: mcc=%d mnc=%d lang=%c%c cnt=%c%c orien=%d touch=%d dens=%d " - "keys=%d nav=%d keysHid=%d navHid=%d sdk=%d size=%d long=%d " - "modetype=%d modenight=%d", - AConfiguration_getMcc(android_app->config), - AConfiguration_getMnc(android_app->config), - lang[0], lang[1], country[0], country[1], - AConfiguration_getOrientation(android_app->config), - AConfiguration_getTouchscreen(android_app->config), - AConfiguration_getDensity(android_app->config), - AConfiguration_getKeyboard(android_app->config), - AConfiguration_getNavigation(android_app->config), - AConfiguration_getKeysHidden(android_app->config), - AConfiguration_getNavHidden(android_app->config), - AConfiguration_getSdkVersion(android_app->config), - AConfiguration_getScreenSize(android_app->config), - AConfiguration_getScreenLong(android_app->config), - AConfiguration_getUiModeType(android_app->config), - AConfiguration_getUiModeNight(android_app->config)); -} - -void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd) { - switch (cmd) { - case APP_CMD_INPUT_CHANGED: - LOGV("APP_CMD_INPUT_CHANGED"); - pthread_mutex_lock(&android_app->mutex); - if (android_app->inputQueue != NULL) { - AInputQueue_detachLooper(android_app->inputQueue); - } - android_app->inputQueue = android_app->pendingInputQueue; - if (android_app->inputQueue != NULL) { - LOGV("Attaching input queue to looper"); - AInputQueue_attachLooper(android_app->inputQueue, - android_app->looper, LOOPER_ID_INPUT, NULL, - &android_app->inputPollSource); - } - pthread_cond_broadcast(&android_app->cond); - pthread_mutex_unlock(&android_app->mutex); - break; - - case APP_CMD_INIT_WINDOW: - LOGV("APP_CMD_INIT_WINDOW"); - pthread_mutex_lock(&android_app->mutex); - android_app->window = android_app->pendingWindow; - pthread_cond_broadcast(&android_app->cond); - pthread_mutex_unlock(&android_app->mutex); - break; - - case APP_CMD_TERM_WINDOW: - LOGV("APP_CMD_TERM_WINDOW"); - pthread_cond_broadcast(&android_app->cond); - break; - - case APP_CMD_RESUME: - case APP_CMD_START: - case APP_CMD_PAUSE: - case APP_CMD_STOP: - LOGV("activityState=%d", cmd); - pthread_mutex_lock(&android_app->mutex); - android_app->activityState = cmd; - pthread_cond_broadcast(&android_app->cond); - pthread_mutex_unlock(&android_app->mutex); - break; - - case APP_CMD_CONFIG_CHANGED: - LOGV("APP_CMD_CONFIG_CHANGED"); - AConfiguration_fromAssetManager(android_app->config, - android_app->activity->assetManager); - print_cur_config(android_app); - break; - - case APP_CMD_DESTROY: - LOGV("APP_CMD_DESTROY"); - android_app->destroyRequested = 1; - break; - } -} - -void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd) { - switch (cmd) { - case APP_CMD_TERM_WINDOW: - LOGV("APP_CMD_TERM_WINDOW"); - pthread_mutex_lock(&android_app->mutex); - android_app->window = NULL; - pthread_cond_broadcast(&android_app->cond); - pthread_mutex_unlock(&android_app->mutex); - break; - - case APP_CMD_SAVE_STATE: - LOGV("APP_CMD_SAVE_STATE"); - pthread_mutex_lock(&android_app->mutex); - android_app->stateSaved = 1; - pthread_cond_broadcast(&android_app->cond); - pthread_mutex_unlock(&android_app->mutex); - break; - - case APP_CMD_RESUME: - free_saved_state(android_app); - break; - } -} - - void android_app_destroy(struct android_app* android_app) { - LOGV("android_app_destroy!"); - free_saved_state(android_app); - pthread_mutex_lock(&android_app->mutex); - if (android_app->inputQueue != NULL) { - AInputQueue_detachLooper(android_app->inputQueue); - } - AConfiguration_delete(android_app->config); - android_app->destroyed = 1; - pthread_cond_broadcast(&android_app->cond); - pthread_mutex_unlock(&android_app->mutex); - // Can't touch android_app object after this. -} - - void process_input(struct android_app* app, struct android_poll_source* source) { - AInputEvent* event = NULL; - while (AInputQueue_getEvent(app->inputQueue, &event) >= 0) { - LOGV("New input event: type=%d", AInputEvent_getType(event)); - if (AInputQueue_preDispatchEvent(app->inputQueue, event)) { - continue; - } - int32_t handled = 0; - if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event); - AInputQueue_finishEvent(app->inputQueue, event, handled); - } -} - - void process_cmd(struct android_app* app, struct android_poll_source* source) { - int8_t cmd = android_app_read_cmd(app); - android_app_pre_exec_cmd(app, cmd); - if (app->onAppCmd != NULL) app->onAppCmd(app, cmd); - android_app_post_exec_cmd(app, cmd); -} - - void* android_app_entry(void* param) { - struct android_app* android_app = (struct android_app*)param; - - android_app->config = AConfiguration_new(); - AConfiguration_fromAssetManager(android_app->config, android_app->activity->assetManager); - - print_cur_config(android_app); - - android_app->cmdPollSource.id = LOOPER_ID_MAIN; - android_app->cmdPollSource.app = android_app; - android_app->cmdPollSource.process = process_cmd; - android_app->inputPollSource.id = LOOPER_ID_INPUT; - android_app->inputPollSource.app = android_app; - android_app->inputPollSource.process = process_input; - - ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS); - ALooper_addFd(looper, android_app->msgread, LOOPER_ID_MAIN, ALOOPER_EVENT_INPUT, NULL, - &android_app->cmdPollSource); - android_app->looper = looper; - - pthread_mutex_lock(&android_app->mutex); - android_app->running = 1; - pthread_cond_broadcast(&android_app->cond); - pthread_mutex_unlock(&android_app->mutex); - - android_main(android_app); - - android_app_destroy(android_app); - return NULL; -} - -// -------------------------------------------------------------------- -// Native activity interaction (called from main thread) -// -------------------------------------------------------------------- - - struct android_app* android_app_create(ANativeActivity* activity, - void* savedState, size_t savedStateSize) { - struct android_app* android_app = calloc(1, sizeof(struct android_app)); - android_app->activity = activity; - - pthread_mutex_init(&android_app->mutex, NULL); - pthread_cond_init(&android_app->cond, NULL); - - if (savedState != NULL) { - android_app->savedState = malloc(savedStateSize); - android_app->savedStateSize = savedStateSize; - memcpy(android_app->savedState, savedState, savedStateSize); - } - - int msgpipe[2]; - if (pipe(msgpipe)) { - LOGE("could not create pipe: %s", strerror(errno)); - return NULL; - } - android_app->msgread = msgpipe[0]; - android_app->msgwrite = msgpipe[1]; - - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - pthread_create(&android_app->thread, &attr, android_app_entry, android_app); - - // Wait for thread to start. - pthread_mutex_lock(&android_app->mutex); - while (!android_app->running) { - pthread_cond_wait(&android_app->cond, &android_app->mutex); - } - pthread_mutex_unlock(&android_app->mutex); - - return android_app; -} - - void android_app_write_cmd(struct android_app* android_app, int8_t cmd) { - if (write(android_app->msgwrite, &cmd, sizeof(cmd)) != sizeof(cmd)) { - LOGE("Failure writing android_app cmd: %s", strerror(errno)); - } -} - - void android_app_set_input(struct android_app* android_app, AInputQueue* inputQueue) { - pthread_mutex_lock(&android_app->mutex); - android_app->pendingInputQueue = inputQueue; - android_app_write_cmd(android_app, APP_CMD_INPUT_CHANGED); - while (android_app->inputQueue != android_app->pendingInputQueue) { - pthread_cond_wait(&android_app->cond, &android_app->mutex); - } - pthread_mutex_unlock(&android_app->mutex); -} - - void android_app_set_window(struct android_app* android_app, ANativeWindow* window) { - pthread_mutex_lock(&android_app->mutex); - if (android_app->pendingWindow != NULL) { - android_app_write_cmd(android_app, APP_CMD_TERM_WINDOW); - } - android_app->pendingWindow = window; - if (window != NULL) { - android_app_write_cmd(android_app, APP_CMD_INIT_WINDOW); - } - while (android_app->window != android_app->pendingWindow) { - pthread_cond_wait(&android_app->cond, &android_app->mutex); - } - pthread_mutex_unlock(&android_app->mutex); -} - - void android_app_set_activity_state(struct android_app* android_app, int8_t cmd) { - pthread_mutex_lock(&android_app->mutex); - android_app_write_cmd(android_app, cmd); - while (android_app->activityState != cmd) { - pthread_cond_wait(&android_app->cond, &android_app->mutex); - } - pthread_mutex_unlock(&android_app->mutex); -} - - void android_app_free(struct android_app* android_app) { - pthread_mutex_lock(&android_app->mutex); - android_app_write_cmd(android_app, APP_CMD_DESTROY); - while (!android_app->destroyed) { - pthread_cond_wait(&android_app->cond, &android_app->mutex); - } - pthread_mutex_unlock(&android_app->mutex); - - close(android_app->msgread); - close(android_app->msgwrite); - pthread_cond_destroy(&android_app->cond); - pthread_mutex_destroy(&android_app->mutex); - free(android_app); -} - - struct android_app* ToApp(ANativeActivity* activity) { - return (struct android_app*) activity->instance; -} - - void onDestroy(ANativeActivity* activity) { - LOGV("Destroy: %p", activity); - android_app_free(ToApp(activity)); -} - - void onStart(ANativeActivity* activity) { - LOGV("Start: %p", activity); - android_app_set_activity_state(ToApp(activity), APP_CMD_START); -} - - void onResume(ANativeActivity* activity) { - LOGV("Resume: %p", activity); - android_app_set_activity_state(ToApp(activity), APP_CMD_RESUME); -} - - void* onSaveInstanceState(ANativeActivity* activity, size_t* outLen) { - LOGV("SaveInstanceState: %p", activity); - - struct android_app* android_app = ToApp(activity); - void* savedState = NULL; - pthread_mutex_lock(&android_app->mutex); - android_app->stateSaved = 0; - android_app_write_cmd(android_app, APP_CMD_SAVE_STATE); - while (!android_app->stateSaved) { - pthread_cond_wait(&android_app->cond, &android_app->mutex); - } - - if (android_app->savedState != NULL) { - savedState = android_app->savedState; - *outLen = android_app->savedStateSize; - android_app->savedState = NULL; - android_app->savedStateSize = 0; - } - - pthread_mutex_unlock(&android_app->mutex); - - return savedState; -} - - void onPause(ANativeActivity* activity) { - LOGV("Pause: %p", activity); - android_app_set_activity_state(ToApp(activity), APP_CMD_PAUSE); -} - - void onStop(ANativeActivity* activity) { - LOGV("Stop: %p", activity); - android_app_set_activity_state(ToApp(activity), APP_CMD_STOP); -} - - void onConfigurationChanged(ANativeActivity* activity) { - LOGV("ConfigurationChanged: %p", activity); - android_app_write_cmd(ToApp(activity), APP_CMD_CONFIG_CHANGED); -} - - void onContentRectChanged(ANativeActivity* activity, const ARect* r) { - LOGV("ContentRectChanged: l=%d,t=%d,r=%d,b=%d", r->left, r->top, r->right, r->bottom); - struct android_app* android_app = ToApp(activity); - pthread_mutex_lock(&android_app->mutex); - android_app->contentRect = *r; - pthread_mutex_unlock(&android_app->mutex); - android_app_write_cmd(ToApp(activity), APP_CMD_CONTENT_RECT_CHANGED); -} - - void onLowMemory(ANativeActivity* activity) { - LOGV("LowMemory: %p", activity); - android_app_write_cmd(ToApp(activity), APP_CMD_LOW_MEMORY); -} - - void onWindowFocusChanged(ANativeActivity* activity, int focused) { - LOGV("WindowFocusChanged: %p -- %d", activity, focused); - android_app_write_cmd(ToApp(activity), focused ? APP_CMD_GAINED_FOCUS : APP_CMD_LOST_FOCUS); -} - - void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* window) { - LOGV("NativeWindowCreated: %p -- %p", activity, window); - android_app_set_window(ToApp(activity), window); -} - - void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* window) { - LOGV("NativeWindowDestroyed: %p -- %p", activity, window); - android_app_set_window(ToApp(activity), NULL); -} - - void onNativeWindowRedrawNeeded(ANativeActivity* activity, ANativeWindow* window) { - LOGV("NativeWindowRedrawNeeded: %p -- %p", activity, window); - android_app_write_cmd(ToApp(activity), APP_CMD_WINDOW_REDRAW_NEEDED); -} - - void onNativeWindowResized(ANativeActivity* activity, ANativeWindow* window) { - LOGV("NativeWindowResized: %p -- %p", activity, window); - android_app_write_cmd(ToApp(activity), APP_CMD_WINDOW_RESIZED); -} - - void onInputQueueCreated(ANativeActivity* activity, AInputQueue* queue) { - LOGV("InputQueueCreated: %p -- %p", activity, queue); - android_app_set_input(ToApp(activity), queue); -} - - void onInputQueueDestroyed(ANativeActivity* activity, AInputQueue* queue) { - LOGV("InputQueueDestroyed: %p -- %p", activity, queue); - android_app_set_input(ToApp(activity), NULL); -} - -void ILOVEU_ANativeActivity_onCreate(ANativeActivity* activity, void* savedState, size_t savedStateSize) { - LOGV("Creating: %p", activity); - - activity->callbacks->onConfigurationChanged = onConfigurationChanged; - activity->callbacks->onContentRectChanged = onContentRectChanged; - activity->callbacks->onDestroy = onDestroy; - activity->callbacks->onInputQueueCreated = onInputQueueCreated; - activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed; - activity->callbacks->onLowMemory = onLowMemory; - activity->callbacks->onNativeWindowCreated = onNativeWindowCreated; - activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed; - activity->callbacks->onNativeWindowRedrawNeeded = onNativeWindowRedrawNeeded; - activity->callbacks->onNativeWindowResized = onNativeWindowResized; - activity->callbacks->onPause = onPause; - activity->callbacks->onResume = onResume; - activity->callbacks->onSaveInstanceState = onSaveInstanceState; - activity->callbacks->onStart = onStart; - activity->callbacks->onStop = onStop; - activity->callbacks->onWindowFocusChanged = onWindowFocusChanged; - - activity->instance = android_app_create(activity, savedState, savedStateSize); -} diff --git a/.outdated/graphics/src/android_native_app_glue.h b/.outdated/graphics/src/android_native_app_glue.h deleted file mode 100644 index 89eafe3..0000000 --- a/.outdated/graphics/src/android_native_app_glue.h +++ /dev/null @@ -1,350 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * The native activity interface provided by - * is based on a set of application-provided callbacks that will be called - * by the Activity's main thread when certain events occur. - * - * This means that each one of this callbacks _should_ _not_ block, or they - * risk having the system force-close the application. This programming - * model is direct, lightweight, but constraining. - * - * The 'android_native_app_glue' static library is used to provide a different - * execution model where the application can implement its own main event - * loop in a different thread instead. Here's how it works: - * - * 1/ The application must provide a function named "android_main()" that - * will be called when the activity is created, in a new thread that is - * distinct from the activity's main thread. - * - * 2/ android_main() receives a pointer to a valid "android_app" structure - * that contains references to other important objects, e.g. the - * ANativeActivity obejct instance the application is running in. - * - * 3/ the "android_app" object holds an ALooper instance that already - * listens to two important things: - * - * - activity lifecycle events (e.g. "pause", "resume"). See APP_CMD_XXX - * declarations below. - * - * - input events coming from the AInputQueue attached to the activity. - * - * Each of these correspond to an ALooper identifier returned by - * ALooper_pollOnce with values of LOOPER_ID_MAIN and LOOPER_ID_INPUT, - * respectively. - * - * Your application can use the same ALooper to listen to additional - * file-descriptors. They can either be callback based, or with return - * identifiers starting with LOOPER_ID_USER. - * - * 4/ Whenever you receive a LOOPER_ID_MAIN or LOOPER_ID_INPUT event, - * the returned data will point to an android_poll_source structure. You - * can call the process() function on it, and fill in android_app->onAppCmd - * and android_app->onInputEvent to be called for your own processing - * of the event. - * - * Alternatively, you can call the low-level functions to read and process - * the data directly... look at the process_cmd() and process_input() - * implementations in the glue to see how to do this. - * - * See the sample named "native-activity" that comes with the NDK with a - * full usage example. Also look at the JavaDoc of NativeActivity. - */ - -struct android_app; - -/** - * Data associated with an ALooper fd that will be returned as the "outData" - * when that source has data ready. - */ -struct android_poll_source { - // The identifier of this source. May be LOOPER_ID_MAIN or - // LOOPER_ID_INPUT. - int32_t id; - - // The android_app this ident is associated with. - struct android_app* app; - - // Function to call to perform the standard processing of data from - // this source. - void (*process)(struct android_app* app, struct android_poll_source* source); -}; - -/** - * This is the interface for the standard glue code of a threaded - * application. In this model, the application's code is running - * in its own thread separate from the main thread of the process. - * It is not required that this thread be associated with the Java - * VM, although it will need to be in order to make JNI calls any - * Java objects. - */ -struct android_app { - // The application can place a pointer to its own state object - // here if it likes. - void* userData; - - // Fill this in with the function to process main app commands (APP_CMD_*) - void (*onAppCmd)(struct android_app* app, int32_t cmd); - - // Fill this in with the function to process input events. At this point - // the event has already been pre-dispatched, and it will be finished upon - // return. Return 1 if you have handled the event, 0 for any default - // dispatching. - int32_t (*onInputEvent)(struct android_app* app, AInputEvent* event); - - // The ANativeActivity object instance that this app is running in. - ANativeActivity* activity; - - // The current configuration the app is running in. - AConfiguration* config; - - // This is the last instance's saved state, as provided at creation time. - // It is NULL if there was no state. You can use this as you need; the - // memory will remain around until you call android_app_exec_cmd() for - // APP_CMD_RESUME, at which point it will be freed and savedState set to NULL. - // These variables should only be changed when processing a APP_CMD_SAVE_STATE, - // at which point they will be initialized to NULL and you can malloc your - // state and place the information here. In that case the memory will be - // freed for you later. - void* savedState; - size_t savedStateSize; - - // The ALooper associated with the app's thread. - ALooper* looper; - - // When non-NULL, this is the input queue from which the app will - // receive user input events. - AInputQueue* inputQueue; - - // When non-NULL, this is the window surface that the app can draw in. - ANativeWindow* window; - - // Current content rectangle of the window; this is the area where the - // window's content should be placed to be seen by the user. - ARect contentRect; - - // Current state of the app's activity. May be either APP_CMD_START, - // APP_CMD_RESUME, APP_CMD_PAUSE, or APP_CMD_STOP; see below. - int activityState; - - // This is non-zero when the application's NativeActivity is being - // destroyed and waiting for the app thread to complete. - int destroyRequested; - - // ------------------------------------------------- - // Below are "private" implementation of the glue code. - - pthread_mutex_t mutex; - pthread_cond_t cond; - - int msgread; - int msgwrite; - - pthread_t thread; - - struct android_poll_source cmdPollSource; - struct android_poll_source inputPollSource; - - int running; - int stateSaved; - int destroyed; - int redrawNeeded; - AInputQueue* pendingInputQueue; - ANativeWindow* pendingWindow; - ARect pendingContentRect; -}; - -enum { - /** - * Looper data ID of commands coming from the app's main thread, which - * is returned as an identifier from ALooper_pollOnce(). The data for this - * identifier is a pointer to an android_poll_source structure. - * These can be retrieved and processed with android_app_read_cmd() - * and android_app_exec_cmd(). - */ - LOOPER_ID_MAIN = 1, - - /** - * Looper data ID of events coming from the AInputQueue of the - * application's window, which is returned as an identifier from - * ALooper_pollOnce(). The data for this identifier is a pointer to an - * android_poll_source structure. These can be read via the inputQueue - * object of android_app. - */ - LOOPER_ID_INPUT = 2, - - /** - * Start of user-defined ALooper identifiers. - */ - LOOPER_ID_USER = 3, -}; - -enum { - /** - * Command from main thread: the AInputQueue has changed. Upon processing - * this command, android_app->inputQueue will be updated to the new queue - * (or NULL). - */ - APP_CMD_INPUT_CHANGED, - - /** - * Command from main thread: a new ANativeWindow is ready for use. Upon - * receiving this command, android_app->window will contain the new window - * surface. - */ - APP_CMD_INIT_WINDOW, - - /** - * Command from main thread: the existing ANativeWindow needs to be - * terminated. Upon receiving this command, android_app->window still - * contains the existing window; after calling android_app_exec_cmd - * it will be set to NULL. - */ - APP_CMD_TERM_WINDOW, - - /** - * Command from main thread: the current ANativeWindow has been resized. - * Please redraw with its new size. - */ - APP_CMD_WINDOW_RESIZED, - - /** - * Command from main thread: the system needs that the current ANativeWindow - * be redrawn. You should redraw the window before handing this to - * android_app_exec_cmd() in order to avoid transient drawing glitches. - */ - APP_CMD_WINDOW_REDRAW_NEEDED, - - /** - * Command from main thread: the content area of the window has changed, - * such as from the soft input window being shown or hidden. You can - * find the new content rect in android_app::contentRect. - */ - APP_CMD_CONTENT_RECT_CHANGED, - - /** - * Command from main thread: the app's activity window has gained - * input focus. - */ - APP_CMD_GAINED_FOCUS, - - /** - * Command from main thread: the app's activity window has lost - * input focus. - */ - APP_CMD_LOST_FOCUS, - - /** - * Command from main thread: the current device configuration has changed. - */ - APP_CMD_CONFIG_CHANGED, - - /** - * Command from main thread: the system is running low on memory. - * Try to reduce your memory use. - */ - APP_CMD_LOW_MEMORY, - - /** - * Command from main thread: the app's activity has been started. - */ - APP_CMD_START, - - /** - * Command from main thread: the app's activity has been resumed. - */ - APP_CMD_RESUME, - - /** - * Command from main thread: the app should generate a new saved state - * for itself, to restore from later if needed. If you have saved state, - * allocate it with malloc and place it in android_app.savedState with - * the size in android_app.savedStateSize. The will be freed for you - * later. - */ - APP_CMD_SAVE_STATE, - - /** - * Command from main thread: the app's activity has been paused. - */ - APP_CMD_PAUSE, - - /** - * Command from main thread: the app's activity has been stopped. - */ - APP_CMD_STOP, - - /** - * Command from main thread: the app's activity is being destroyed, - * and waiting for the app thread to clean up and exit before proceeding. - */ - APP_CMD_DESTROY, -}; - -/** - * Call when ALooper_pollAll() returns LOOPER_ID_MAIN, reading the next - * app command message. - */ -int8_t android_app_read_cmd(struct android_app* android_app); - -/** - * Call with the command returned by android_app_read_cmd() to do the - * initial pre-processing of the given command. You can perform your own - * actions for the command after calling this function. - */ -void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd); - -/** - * Call with the command returned by android_app_read_cmd() to do the - * final post-processing of the given command. You must have done your own - * actions for the command before calling this function. - */ -void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd); - -/** - * No-op function that used to be used to prevent the linker from stripping app - * glue code. No longer necessary, since __attribute__((visibility("default"))) - * does this for us. - */ -__attribute__(( - deprecated("Calls to app_dummy are no longer necessary. See " - "https://github.com/android-ndk/ndk/issues/381."))) void -app_dummy(); - -/** - * This is the function that application code must implement, representing - * the main entry to the app. - */ -extern void android_main(struct android_app* app); - -#ifdef __cplusplus -} -#endif diff --git a/.outdated/graphics/src/animations.cpp b/.outdated/graphics/src/animations.cpp deleted file mode 100644 index 84df77a..0000000 --- a/.outdated/graphics/src/animations.cpp +++ /dev/null @@ -1,115 +0,0 @@ - -#include "animations.h" -#include "timer.h" - -using namespace tp; -using namespace glw; - -bool tp::glw::gInTransition = false; - -halnf AnimValue::interpolate() const { - if (!mTimeAnim) { - return mVal; - } - - auto dt = gCurrentTime - mTimeStart; - if (dt > mTimeAnim) dt = mTimeAnim; - auto t = (halnf)dt / mTimeAnim; - t = (halnf)(0.511 + atan((t - 0.36) * 28) / 2.9); - t = clamp(t, 0.f, 1.f); - auto out = mValPrev + (mVal - mValPrev) * t; - return out; -} - -AnimValue::AnimValue() {} - -void AnimValue::setAnimTime(halni time) { - mTimeAnim = time; -} - -AnimValue::AnimValue(halnf val) { - mVal = val; - mValPrev = mVal; - mTimeStart = gCurrentTime; -} - -bool AnimValue::inTransition() const { - auto time_pased = gCurrentTime - mTimeStart >= mTimeAnim; - return !time_pased; -} - -void AnimValue::set(halnf val) { - if (!inTransition()) { - mValPrev = mVal; - } - - if (val == mVal) { - return; - } - - mValPrev = get(); - mVal = val; - - if (!inTransition()) { - mTimeStart = (halni)gCurrentTime; - } -} - -halnf AnimValue::getTarget() const { - return mVal; -} - -void AnimValue::setNoTransition(halnf val) { - mValPrev = val; - mVal = val; - mTimeStart -= mTimeStart; -} - -halnf AnimValue::get() const { - if (inTransition()) { - gInTransition = true; - } - return interpolate(); -} - -AnimValue::operator halnf() const { - return get(); -} - -rectf AnimRect::get() const { - return { x.get(), y.get() , z.get(), w.get() }; -} - -rectf AnimRect::getTarget() const { - return { x.getTarget(), y.getTarget() , z.getTarget(), w.getTarget() }; -} - -void AnimRect::setNoTransition(rectf rec) { - x.setNoTransition(rec.x); - y.setNoTransition(rec.y); - z.setNoTransition(rec.z); - w.setNoTransition(rec.w); -} - -void AnimRect::setAnimTime(const halni time) { - x.setAnimTime(time); - y.setAnimTime(time); - z.setAnimTime(time); - w.setAnimTime(time); -} - -void AnimRect::set(const rectf& in) { - x.set(in.x); - y.set(in.y); - z.set(in.z); - w.set(in.w); -} - -rgba AnimColor::get() const { - auto col = mColor.get(); - return rgba(col.x, col.y, col.z, col.w); -} - -void AnimColor::set(const rgba& col) { - mColor.set(rectf(col.r, col.g, col.b, col.a)); -} \ No newline at end of file diff --git a/.outdated/graphics/src/canvas.cpp b/.outdated/graphics/src/canvas.cpp deleted file mode 100644 index 899784a..0000000 --- a/.outdated/graphics/src/canvas.cpp +++ /dev/null @@ -1,378 +0,0 @@ - -#include "canvas.h" - -#include "GraphicsLibApi.h" - -#ifdef ENV_OS_ANDROID -const char* get_android_abs_path(const char* path, bool second = false); -#define NANOVG_GLES3_IMPLEMENTATION // Use GLES3 implementation. -#else -#define NANOVG_GL3_IMPLEMENTATION // Use GL3 implementation. -#endif - -#include "nanovg.h" -#include "nanovg_gl.h" -#include "nanovg_gl_utils.h" - -using namespace tp; -using namespace glw; - -#define NVG ((NVGcontext*) mCtx) - -static const char* getFontPath() { -#ifdef ENV_OS_ANDROID - return get_android_abs_path("rsc/fonts/CONSOLAB.TTF"); -#else - return "./rsc/fonts/CONSOLAB.TTF"; -#endif - -} - -Canvas::Canvas() { - - // create context - mCtx = -#ifdef ENV_OS_ANDROID - nvgCreateGLES3 -#else - nvgCreateGL3 -#endif - (NVG_ANTIALIAS | NVG_STENCIL_STROKES -#ifdef ENV_BUILD_DEBUG - | NVG_DEBUG -#endif - ); - - mColorPrimary = rgba(0.5f, 0.5f, 0.5f, 0.9f); - mColorSecondary = rgba(0.2f, 0.2f, 0.2f, 0.9f); - - nvgCreateFont(NVG, "basic", getFontPath()); -} - -Canvas::Val& Canvas::convert2pxls(Val& val) { - val = val * mDpmm * mUIScale; - return val; -} - -Canvas::Val Canvas::as2pxls(Val val) { - return val * mDpmm * mUIScale; -} - -Canvas::Rect& Canvas::convert2pxls(Rect& rec) { - convert2pxls(rec.x); - convert2pxls(rec.y); - convert2pxls(rec.z); - convert2pxls(rec.w); - return rec; -} - -Canvas::Vec2& Canvas::convert2pxls(Vec2& vec) { - convert2pxls(vec.x); - convert2pxls(vec.y); - return vec; -} - -void Canvas::beginDraw(Rect viewport, tp::halnf dpmm, tp::halnf uiscale) { - convert2pxls(viewport); - nvgBeginFrame(NVG, viewport.size.x, viewport.size.y, 1); - - mVieport = { 0.f, 0.f, viewport.size.x, viewport.size.y }; - glViewport((GLsizei)mVieport.x, (GLsizei)mVieport.y, (GLsizei)mVieport.size.x, (GLsizei)mVieport.size.y); - - mDpmm = dpmm; - mUIScale = tp::clamp(uiscale, 0.03f, 100.f); - - mClamping = mVieport; -} - -void Canvas::resetViewport() { - glViewport((GLsizei)mVieport.x, (GLsizei)mVieport.y, (GLsizei)mVieport.size.x, (GLsizei)mVieport.size.y); -} - -void Canvas::clear(Col color) { - glClearColor(color.r, color.g, color.b, color.a); - //glClearDepth(0.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); -} - -void Canvas::endDraw() { - nvgEndFrame(NVG); -} - -void Canvas::setClamping(Rect rec) { - mClamping = rec; - convert2pxls(rec); - nvgScissor(NVG, rec.x, rec.y, rec.z, rec.w); -} - -void Canvas::setCol1(const Col& col) { - mColorPrimary = col; -} - -void Canvas::setCol2(const Col& col) { - mColorSecondary = col; -} - -void Canvas::rect(Rect rec, halnf rounding, halnf borders) { - convert2pxls(rec); - convert2pxls(rounding); - convert2pxls(borders); - - if (borders) { - nvgBeginPath(NVG); - - auto borders_rec = rec; - rec.pos += borders; - rec.size -= borders * 2; - - if (rounding) { - nvgRoundedRect(NVG, borders_rec.x, borders_rec.y, borders_rec.z, borders_rec.w, rounding); - } - else { - nvgRect(NVG, borders_rec.x, borders_rec.y, borders_rec.z, borders_rec.w); - } - - nvgFillColor(NVG, nvgRGBAf(mColorSecondary.r, mColorSecondary.g, mColorSecondary.b, mColorSecondary.a)); - nvgFill(NVG); - } - - nvgBeginPath(NVG); - - if (rounding) { - nvgRoundedRect(NVG, rec.x, rec.y, rec.z, rec.w, rounding); - } - else { - nvgRect(NVG, rec.x, rec.y, rec.z, rec.w); - } - nvgFillColor(NVG, nvgRGBAf(mColorPrimary.r, mColorPrimary.g, mColorPrimary.b, mColorPrimary.a)); - nvgFill(NVG); -} - -void Canvas::line(Vec2 p1, Vec2 p2, halnf thikness) { - convert2pxls(p1); - convert2pxls(p2); - convert2pxls(thikness); - - nvgBeginPath(NVG); - - nvgMoveTo(NVG, p1.x, p1.y); - nvgLineTo(NVG, p2.x, p2.y); - - nvgStrokeColor(NVG, nvgRGBAf(mColorPrimary.r, mColorPrimary.g, mColorPrimary.b, mColorPrimary.a)); - nvgStrokeWidth(NVG, thikness); - nvgStroke(NVG); -} - -void Canvas::trig(Vec2 p1, Vec2 p2, Vec2 p3) { - convert2pxls(p1); - convert2pxls(p2); - convert2pxls(p3); - - nvgBeginPath(NVG); - - nvgMoveTo(NVG, p1.x, p1.y); - nvgLineTo(NVG, p2.x, p2.y); - nvgLineTo(NVG, p3.x, p3.y); - - nvgFillColor(NVG, nvgRGBAf(mColorPrimary.r, mColorPrimary.g, mColorPrimary.b, mColorPrimary.a)); - nvgFill(NVG); -} - -void Canvas::circle(Vec2 rec, halnf radius, halnf borders) { - convert2pxls(rec); - convert2pxls(radius); - convert2pxls(borders); - DBG_BREAK(1); -} - -void Canvas::text(const char* start, const char* end, Rect rec, halnf size, Align align) { - convert2pxls(rec); - convert2pxls(size); - - nvgFillColor(NVG, nvgRGBAf(mColorPrimary.r, mColorPrimary.g, mColorPrimary.b, mColorPrimary.a)); - nvgFontSize(NVG, size); - nvgTextAlign(NVG, NVGalign(align)); - auto y = (align & Align::MIDDLE) ? rec.y + rec.w / 2 : rec.y; - auto x = (align & Align::CENTER) ? rec.x + rec.z / 2 : rec.x; - nvgText(NVG, x, y, start, end); -} - -void Canvas::text(const string text, Rect rec, halnf size, Align align) { - convert2pxls(rec); - convert2pxls(size); - - nvgFillColor(NVG, nvgRGBAf(mColorPrimary.r, mColorPrimary.g, mColorPrimary.b, mColorPrimary.a)); - nvgFontSize(NVG, size); - nvgTextAlign(NVG, NVGalign(align)); - - //nvgTextBounds(NVG, ); - - auto t_mid = rec.y + rec.w / 2; - auto t_top = rec.y; - auto res = bool(align & Align::MIDDLE); - auto y = res ? t_mid : t_top; - - auto x_mid = rec.x + rec.z / 2; - auto x_left = rec.x; - res = bool(align & Align::CENTER); - auto x = res ? x_mid : x_left; - - nvgText(NVG, x, y, text.cstr(), text.cstr() + text.size()); -} - - -void Canvas::ImageHandle::createFromBuff(glw::fbuffer* buff, Canvas* drawer) { - this->~ImageHandle(); - auto const size = buff->getSize(); - -#ifdef ENV_OS_ANDROID - mId = nvglCreateImageFromHandleGLES3((NVGcontext*)drawer->mCtx, buff->texId(), size.x, size.y, 0); -#else - mId = nvglCreateImageFromHandleGL3((NVGcontext*)drawer->mCtx, buff->texId(), (halni) size.x, (halni) size.y, 0); -#endif -} - -void Canvas::ImageHandle::free(Canvas* drawer) { - if (mId && (NVGcontext*)drawer->mCtx) { - nvgDeleteImage((NVGcontext*)drawer->mCtx, mId); - } -} - -Canvas::ImageHandle::~ImageHandle() {} - -void Canvas::drawImage(Rect rec, ImageHandle* image, halnf angle, halnf alpha, halnf rounding) { - convert2pxls(rec); - convert2pxls(rounding); - - - auto imgPaint = nvgImagePattern(NVG, rec.x, rec.y, rec.z, rec.w, angle, image->mId, alpha); - nvgBeginPath(NVG); - nvgRoundedRect(NVG, rec.x, rec.y, rec.z, rec.w, rounding); - nvgFillPaint(NVG, imgPaint); - nvgFill(NVG); -} - -void Canvas::drawColorwheel(Rect rec, const rgb& col) { - convert2pxls(rec); - - float const x = rec.x; - float const y = rec.y; - float const w = rec.z; - float const h = rec.w; - - hsv hsv = tp::hsv(col); - float const hue = hsv.h / (NVG_PI * 2); - - int i; - float r0, r1, ax, ay, bx, by, cx, cy, aeps, r; - NVGpaint paint; - - nvgSave(NVG); - - cx = x + w * 0.5f; - cy = y + h * 0.5f; - r1 = (w < h ? w : h) * 0.5f - as2pxls(1.0f); - r0 = r1 - as2pxls(3.0f); - aeps = 0.5f / r1; // half a pixel arc length in radians (2pi cancels out). - - for (i = 0; i < 6; i++) { - float a0 = (float)i / 6.0f * NVG_PI * 2.0f - aeps; - float a1 = (float)(i + 1.0f) / 6.0f * NVG_PI * 2.0f + aeps; - nvgBeginPath(NVG); - nvgArc(NVG, cx, cy, r0, a0, a1, NVG_CW); - nvgArc(NVG, cx, cy, r1, a1, a0, NVG_CCW); - nvgClosePath(NVG); - ax = cx + cosf(a0) * (r0 + r1) * 0.5f; - ay = cy + sinf(a0) * (r0 + r1) * 0.5f; - bx = cx + cosf(a1) * (r0 + r1) * 0.5f; - by = cy + sinf(a1) * (r0 + r1) * 0.5f; - paint = nvgLinearGradient(NVG, ax, ay, bx, by, nvgHSLA(a0 / (NVG_PI * 2), 1.0f, 0.55f, 255), nvgHSLA(a1 / (NVG_PI * 2), 1.0f, 0.55f, 255)); - nvgFillPaint(NVG, paint); - nvgFill(NVG); - } - - nvgBeginPath(NVG); - nvgCircle(NVG, cx, cy, r0 - 0.5f); - nvgCircle(NVG, cx, cy, r1 + 0.5f); - nvgStrokeColor(NVG, nvgRGBA(0, 0, 0, 64)); - nvgStrokeWidth(NVG, 1.0f); - nvgStroke(NVG); - - // Selector - nvgSave(NVG); - nvgTranslate(NVG, cx, cy); - nvgRotate(NVG, hue * NVG_PI * 2); - - // Marker on - nvgStrokeWidth(NVG, 2.0f); - nvgBeginPath(NVG); - nvgRect(NVG, r0 - 1, -3, r1 - r0 + 2, 6); - nvgStrokeColor(NVG, nvgRGBA(255, 255, 255, 192)); - nvgStroke(NVG); - - paint = nvgBoxGradient(NVG, r0 - 3, -5, r1 - r0 + 6, 10, 2, 4, nvgRGBA(0, 0, 0, 128), nvgRGBA(0, 0, 0, 0)); - nvgBeginPath(NVG); - nvgRect(NVG, r0 - 2 - 10, -4 - 10, r1 - r0 + 4 + 20, 8 + 20); - nvgRect(NVG, r0 - 2, -4, r1 - r0 + 4, 8); - nvgPathWinding(NVG, NVG_HOLE); - nvgFillPaint(NVG, paint); - nvgFill(NVG); - - // Center triangle - r = r0 - 6; - ax = cosf(120.0f / 180.0f * NVG_PI) * r; - ay = sinf(120.0f / 180.0f * NVG_PI) * r; - bx = cosf(-120.0f / 180.0f * NVG_PI) * r; - by = sinf(-120.0f / 180.0f * NVG_PI) * r; - nvgBeginPath(NVG); - nvgMoveTo(NVG, r, 0); - nvgLineTo(NVG, ax, ay); - nvgLineTo(NVG, bx, by); - nvgClosePath(NVG); - paint = nvgLinearGradient(NVG, r, 0, ax, ay, nvgHSLA(hue, 1.0f, 0.5f, 255), nvgRGBA(255, 255, 255, 255)); - nvgFillPaint(NVG, paint); - nvgFill(NVG); - paint = nvgLinearGradient(NVG, (r + ax) * 0.5f, (0 + ay) * 0.5f, bx, by, nvgRGBA(0, 0, 0, 0), nvgRGBA(0, 0, 0, 255)); - nvgFillPaint(NVG, paint); - nvgFill(NVG); - nvgStrokeColor(NVG, nvgRGBA(0, 0, 0, 64)); - nvgStroke(NVG); - - // Select circle on triangle - auto inner = as2pxls(3); - //auto outter = as2pxls(5); - - float yt = hsv.v * hsv.s; - float xt = hsv.v - 0.5f * yt; - ay = sinf(120.0f / 180.0f * NVG_PI) * r * (-1.0f + xt * 2.0f); - ax = cosf(120.0f / 180.0f * NVG_PI) * r * (1.0f - yt * 3.f); - nvgStrokeWidth(NVG, as2pxls(0.6f)); - nvgBeginPath(NVG); - nvgCircle(NVG, ax, ay, inner); - nvgStrokeColor(NVG, nvgRGBA(255, 255, 255, 192)); - nvgStroke(NVG); - - //paint = nvgRadialGradient(NVG, ax, ay, 4, 9, nvgRGBA(0, 0, 0, 64), nvgRGBA(0, 0, 0, 0)); - //nvgBeginPath(NVG); - //nvgRect(NVG, ax - outter, ay - outter, outter * 2, outter * 2); - //nvgCircle(NVG, ax, ay, outter); - //nvgPathWinding(NVG, NVG_HOLE); - //nvgFillPaint(NVG, paint); - //nvgFill(NVG); - - nvgRestore(NVG); - - nvgRestore(NVG); -} - - -Canvas::~Canvas() { - if (NVG) { -#ifdef ENV_OS_ANDROID - nvgDeleteGLES3(NVG); -#else - nvgDeleteGL3(NVG); -#endif - } - mCtx = NULL; -} diff --git a/.outdated/graphics/src/debugui.cpp b/.outdated/graphics/src/debugui.cpp deleted file mode 100644 index dfcc0f3..0000000 --- a/.outdated/graphics/src/debugui.cpp +++ /dev/null @@ -1,877 +0,0 @@ - -#include "debugui.h" - -#include "typelist.h" -#include "stringt.h" -#include "stack.h" -#include "npple.h" -#include "rect.h" -#include "map.h" - -#include "imgui.h" -#include "imgui_internal.h" -#include "implot.h" - -// -------------- Platform Includes ---------------------- // - -#if defined ENV_OS_WINDOWS -#include "backends/imgui_impl_opengl3.h" -#include "backends/imgui_impl_win32.h" -#include -#elif defined ENV_OS_LINUX -#include "backends/imgui_impl_opengl3.h" -#include "backends/imgui_impl_glfw.h" -#elif defined ENV_OS_ANDROID -#include "backends/imgui_impl_opengl3.h" -#include "backends/imgui_impl_android.h" -#include -#include -#include -#include -#endif - - -#if defined ENV_OS_WINDOWS -extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); - -extern HWND windowsPlatformContextGetNativeWindow(tp::glw::PlatformContext* ctx); -extern UINT windowsPlatformContextGetMessage(tp::glw::PlatformContext* ctx); -extern WPARAM windowsPlatformContextGetWparam(tp::glw::PlatformContext* ctx); -extern LRESULT windowsPlatformContextGetLparam(tp::glw::PlatformContext* ctx); - -#elif defined ENV_OS_LINUX -#elif defined ENV_OS_ANDROID -extern AInputEvent* androidPlatformContextGetEvent(tp::glw::PlatformContext* ctx); -extern const char* get_android_abs_path(const char* path, bool second = false); - -const char* AndroidGetImGuiIniPath() { - static char imgui_path[512]; - auto tmp = get_android_abs_path("imgui.ini"); - memcpy(imgui_path, tmp, strlen(tmp)); - return imgui_path; -} -#endif - -static const char* getFontPath() { -#ifdef ENV_OS_ANDROID - return get_android_abs_path("rsc/fonts/CONSOLAB.TTF"); -#else - return "./rsc/fonts/CONSOLAB.TTF"; -#endif -} - -namespace tp { - namespace glw { - struct DebugUiInternalContext { - - DebugUiDrawCallBack* cb = NULL; - void* cd = NULL; - - ImGuiContext* ui_context = NULL; - ImGuiContext* vk_context = NULL; - - bool initialized = false; - - bool ui_first_drawn = false; - bool vk_first_drawn = false; - - bool ui_context_want_active = true; - bool ui_context_want_active_vk = false; - bool vk_context_want_active = false; - - tp::halnf dpmm; - tp::halnf font_size_mm; - tp::halnf ui_scale; - - struct VKState { - - struct InputButton { - char val = '?'; - char shift_val = '?'; - tp::halnf width = 1; - - void (*action)(InputButton* button, VKState* state) = [](InputButton* button, VKState* state) { - if (state->mShifted) { - ImGui::GetIO().AddInputCharacter(button->shift_val); - } - else { - ImGui::GetIO().AddInputCharacter(button->val); - } - }; - - const char* display_name = NULL; - }; - - struct Config { - InputButton** rows = NULL; - tp::halni nrows = NULL; - tp::halnf* rows_widths = NULL; - tp::halnf* rows_sizes = NULL; - }; - - bool mShifted = false; - - static const tp::uhalni mNConfigs = 2; - Config mConfigs[mNConfigs]; - tp::uhalni mActiveConfigIdx = 0; - - InputButton mCommonRow[7]; - //bool mActive = false; - - VKState() { - mCommonRow[0] = { '^', '^', 1 , [](InputButton* button, VKState* state) { state->mShifted = !state->mShifted; } }; - - mCommonRow[1] = { ' ', ' ', 1, - [](InputButton* button, VKState* state) { - state->mActiveConfigIdx++; - if (state->mActiveConfigIdx == state->mNConfigs) { - state->mActiveConfigIdx = 0; - } - }, - "..." - }; - - mCommonRow[2] = { ' ', ' ', 2 }; - - mCommonRow[3] = { '<', '<', 2, [](InputButton* button, VKState* state) { - ImGui::GetIO().AddKeyEvent(ImGuiKey_Backspace, true); - ImGui::GetIO().AddKeyEvent(ImGuiKey_Backspace, false); - } }; - - mCommonRow[4] = { '.', '.', 1 }; - mCommonRow[5] = { '@', '@', 1 }; - - mCommonRow[6] = { ' ', ' ', 2, [](InputButton* button, VKState* state) { - ImGui::GetIO().AddKeyEvent(ImGuiKey_Enter, true); - ImGui::GetIO().AddKeyEvent(ImGuiKey_Enter, false); - }, "Entrer" }; - - setupMainConfig(mConfigs[0]); - setupAdditionalConfig(mConfigs[1]); - } - - void setupMainConfig(Config& config) { - - static InputButton row1[] = { - {'1', '!'}, - {'2', '@'}, - {'3', '#'}, - {'4', '$'}, - {'5', '%'}, - {'6', '^'}, - {'7', '&'}, - {'8', '*'}, - {'9', '('}, - {'0', ')'}, - }; - - static InputButton row2[] = { - {'q', 'Q'}, - {'w', 'W'}, - {'e', 'E'}, - {'r', 'R'}, - {'t', 'T'}, - {'y', 'Y'}, - {'u', 'U'}, - {'i', 'I'}, - {'o', 'O'}, - {'p', 'P'}, - }; - - static InputButton row3[] = { - {'a', 'A'}, - {'s', 'S'}, - {'d', 'D'}, - {'f', 'F'}, - {'g', 'G'}, - {'h', 'H'}, - {'j', 'J'}, - {'k', 'K'}, - {'l', 'L'}, - }; - - static InputButton row4[] = { - {'z', 'Z'}, - {'x', 'X'}, - {'c', 'C'}, - {'v', 'V'}, - {'b', 'B'}, - {'n', 'N'}, - {'m', 'M'}, - }; - - static InputButton* rows[] = { - row1, - row2, - row3, - row4, - mCommonRow, - }; - - static tp::halnf rows_sizes[IM_ARRAYSIZE(rows)] = { - IM_ARRAYSIZE(row1), - IM_ARRAYSIZE(row2), - IM_ARRAYSIZE(row3), - IM_ARRAYSIZE(row4), - IM_ARRAYSIZE(mCommonRow), - }; - - static tp::halnf rows_widths[IM_ARRAYSIZE(rows)]; - for (auto row = 0; row < IM_ARRAYSIZE(rows); row++) { - for (auto butt = 0; butt < rows_sizes[row]; butt++) { - rows_widths[row] += rows[row][butt].width; - } - } - - config = { - rows, - IM_ARRAYSIZE(rows), - rows_widths, - rows_sizes, - }; - } - - void setupAdditionalConfig(Config& config) { - static InputButton row1[] = { - {'~', '~'}, - {'`', '`'}, - {'_', '_'}, - {'|', '|'}, - {'\\', '\\'}, - {'/', '/'}, - {'"', '"'}, - {'\'', '\''}, - }; - - static InputButton row2[] = { - {';', ';'}, - {':', ':'}, - {'?', '?'}, - {',', ','}, - {'[', '['}, - {']', ']'}, - {'{', '{'}, - {'}', '}'}, - {'(', '('}, - {')', ')'}, - }; - - static InputButton row3[] = { - {'-', '-'}, - {'=', '='}, - {'*', '*'}, - {'+', '+'}, - {'<', '<'}, - {'>', '>'}, - }; - - static InputButton row4[] = { - {' ', ' ', 1, [](InputButton* butt, VKState* state) { - ImGui::GetIO().AddKeyEvent(ImGuiKey_UpArrow, true); - ImGui::GetIO().AddKeyEvent(ImGuiKey_UpArrow, false); - }, "up" }, - {' ', ' ', 1, [](InputButton* butt, VKState* state) { - ImGui::GetIO().AddKeyEvent(ImGuiKey_DownArrow, true); - ImGui::GetIO().AddKeyEvent(ImGuiKey_DownArrow, false); - }, "down"}, - {' ', ' ', 1, [](InputButton* butt, VKState* state) { - ImGui::GetIO().AddKeyEvent(ImGuiKey_LeftArrow, true); - ImGui::GetIO().AddKeyEvent(ImGuiKey_LeftArrow, false); - }, "left"}, - {' ', ' ', 1, [](InputButton* butt, VKState* state) { - ImGui::GetIO().AddKeyEvent(ImGuiKey_RightArrow, true); - ImGui::GetIO().AddKeyEvent(ImGuiKey_RightArrow, false); - }, "right"}, - }; - - static InputButton* rows[] = { - row1, - row2, - row3, - row4, - mCommonRow, - }; - - static tp::halnf rows_sizes[IM_ARRAYSIZE(rows)] = { - IM_ARRAYSIZE(row1), - IM_ARRAYSIZE(row2), - IM_ARRAYSIZE(row3), - IM_ARRAYSIZE(row4), - IM_ARRAYSIZE(mCommonRow), - }; - - static tp::halnf rows_widths[IM_ARRAYSIZE(rows)]; - for (auto row = 0; row < IM_ARRAYSIZE(rows); row++) { - for (auto butt = 0; butt < rows_sizes[row]; butt++) { - rows_widths[row] += rows[row][butt].width; - } - } - - config = { - rows, - IM_ARRAYSIZE(rows), - rows_widths, - rows_sizes, - }; - } - - } mVKState; - - DebugUiInternalContext(Window& window, DebugUiDrawCallBack* acb, void* acd) { - - cb = acb; - cd = acd; - - ui_context = ImGui::CreateContext(); - ImGui::SetCurrentContext(ui_context); - ImGuiContextInit(window); - - vk_context = ImGui::CreateContext(); - ImGui::SetCurrentContext(vk_context); - ImGuiContextInit(window); - - initialized = true; - } - - void drawDebugUI(tp::halnf a_dpmm, tp::halnf a_font_size_mm, tp::halnf a_ui_scale) { - dpmm = a_dpmm; - font_size_mm = a_font_size_mm; - ui_scale = a_ui_scale; - - if (!initialized) return; - - ImGui::SetCurrentContext(ui_context); - ImGui::ApplyStyle(dpmm, font_size_mm, ui_scale); - ImGuiContextBeginFrame(); - cb(cd); - ImGuiContextEndFrame(); - ImGui::SetCurrentContext(NULL); - ui_first_drawn = true; - - if (ui_context_want_active_vk || vk_context_want_active) { - ImGui::SetCurrentContext(vk_context); - ImGui::ApplyStyle(dpmm, font_size_mm, ui_scale); - ImGuiContextBeginFrame(); - VirtualKeyboard(dpmm, font_size_mm, ui_scale); - ImGuiContextEndFrame(); - ImGui::SetCurrentContext(NULL); - - vk_first_drawn = true; - } - } - - ~DebugUiInternalContext() { - if (!initialized) return; - - ImGui::SetCurrentContext(ui_context); - ImGuiContextDeinit(); - ImGui::DestroyContext(ui_context); - - ImGui::SetCurrentContext(vk_context); - ImGuiContextDeinit(); - ImGui::DestroyContext(vk_context); - } - - private: - - void ImGuiContextInit(Window& window) { -#if defined ENV_OS_WINDOWS - ImGui_ImplOpenGL3_Init(); - ImGui_ImplWin32_Init(window.platform_window()); - window.mNativeEventListeners.put("imgui", { - nativeWindowEventListenerWrapBegin, - nativeWindowEventListenerWrap, - nativeWindowEventListenerWrapEnd, - this - }); -#elif defined ENV_OS_LINUX - ImGui_ImplOpenGL3_Init(); - ImGui_ImplGlfw_InitForOpenGL((GLFWwindow*)window.platform_window(), true); -#elif defined ENV_OS_ANDROID - ImGui_ImplOpenGL3_Init("#version 300 es"); - ImGui_ImplAndroid_Init((ANativeWindow*)window.platform_window()); - ImGui::GetIO().IniFilename = AndroidGetImGuiIniPath(); - window.mNativeEventListeners.put("imgui", { - nativeWindowEventListenerWrapBegin, - nativeWindowEventListenerWrap, - nativeWindowEventListenerWrapEnd, - this - }); -#endif - } - - void ImGuiContextBeginFrame() { -#if defined ENV_OS_WINDOWS - ImGui_ImplWin32_NewFrame(); - ImGui_ImplOpenGL3_NewFrame(); -#elif defined ENV_OS_LINUX - ImGui_ImplOpenGL3_NewFrame(); - ImGui_ImplGlfw_NewFrame(); -#elif defined ENV_OS_ANDROID - ImGui_ImplOpenGL3_NewFrame(); - ImGui_ImplAndroid_NewFrame(); -#endif - ImGui::NewFrame(); - } - - void ImGuiContextEndFrame() { - ImGui::Render(); - -#if defined ENV_OS_WINDOWS - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); -#elif defined ENV_OS_LINUX - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); -#elif defined ENV_OS_ANDROID - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); -#endif - } - - void ImGuiContextDeinit() { -#if defined ENV_OS_WINDOWS - ImGui_ImplWin32_Shutdown(); -#elif defined ENV_OS_LINUX - ImGui_ImplGlfw_Shutdown(); -#elif defined ENV_OS_ANDROID - ImGui_ImplAndroid_Shutdown(); -#endif - ImGui_ImplOpenGL3_Shutdown(); - } - - void nativeWindowEventListenerPlatform(tp::glw::PlatformContext* ctx) { -#if defined ENV_OS_WINDOWS - auto native_window = windowsPlatformContextGetNativeWindow(ctx); - auto message = windowsPlatformContextGetMessage(ctx); - auto w_param = windowsPlatformContextGetWparam(ctx); - auto l_param = windowsPlatformContextGetLparam(ctx); - // IMGUI : needs to be commented out - //if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr) - // ::SetCapture(hwnd); - ImGui_ImplWin32_WndProcHandler(native_window, message, w_param, l_param); -#elif defined ENV_OS_LINUX -#elif defined ENV_OS_ANDROID - - auto aev = androidPlatformContextGetEvent(ctx); - - int32_t event_type = AInputEvent_getType(aev); - - ImGui_ImplAndroid_HandleInputEvent(aev); - - auto& io = ImGui::GetIO(); - - if (event_type == AINPUT_EVENT_TYPE_MOTION); { - int32_t event_action = AMotionEvent_getAction(aev); - int32_t event_pointer_index = (event_action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - event_action &= AMOTION_EVENT_ACTION_MASK; - - if ((AMotionEvent_getToolType(aev, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_FINGER) - || (AMotionEvent_getToolType(aev, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_UNKNOWN)) { - - if (event_action == AMOTION_EVENT_ACTION_DOWN) { - io.AddMousePosEvent(AMotionEvent_getX(aev, event_pointer_index), AMotionEvent_getY(aev, event_pointer_index)); - } - else if (event_action == AMOTION_EVENT_ACTION_UP) { - io.AddMousePosEvent(AMotionEvent_getX(aev, event_pointer_index), AMotionEvent_getY(aev, event_pointer_index)); - if (!ui_context_want_active_vk || vk_context_want_active) { - io.AddMousePosEvent(-1, -1); - } - } - } - } -#endif - } - - void nativeWindowEventListenerBegin(tp::glw::PlatformContext* ctx) { - vk_context_want_active = vk_context->IO.WantCaptureMouse || vk_context->IO.WantSetMousePos; - - ui_context_want_active_vk = ui_context->IO.WantTextInput; - ui_context_want_active = ui_context->IO.WantCaptureKeyboard || ui_context->IO.WantCaptureMouse || ui_context->IO.WantSetMousePos; - } - - void nativeWindowEventListener(tp::glw::PlatformContext* ctx) { - - // proc vk - if ((ui_context_want_active_vk || vk_context_want_active) && vk_first_drawn) { - ImGui::SetCurrentContext(vk_context); - nativeWindowEventListenerPlatform(ctx); - - while (vk_context->InputEventsQueue.Size) { - ImGui::ApplyStyle(dpmm, font_size_mm, ui_scale); - ImGui::NewFrame(); - VirtualKeyboard(dpmm, font_size_mm, ui_scale); - ImGui::Render(); - - vk_context_want_active |= vk_context->IO.WantCaptureMouse || vk_context->IO.WantSetMousePos; - } - - vk_context_want_active |= vk_context->IO.WantCaptureMouse || vk_context->IO.WantSetMousePos; - - ImGui::SetCurrentContext(NULL); - } - - // proc ui - if (!vk_context_want_active && ui_first_drawn) { - ImGui::SetCurrentContext(ui_context); - nativeWindowEventListenerPlatform(ctx); - - while (ui_context->InputEventsQueue.Size) { - ImGui::ApplyStyle(dpmm, font_size_mm, ui_scale); - ImGui::NewFrame(); - cb(cd); - ImGui::Render(); - - ui_context_want_active_vk |= ui_context->IO.WantTextInput; - ui_context_want_active |= ui_context->IO.WantCaptureKeyboard || ui_context->IO.WantCaptureMouse || ui_context->IO.WantSetMousePos; - } - - ImGui::SetCurrentContext(NULL); - } - } - - void nativeWindowEventListenerEnd(tp::glw::PlatformContext* ctx) {} - - static void nativeWindowEventListenerWrapBegin(tp::glw::PlatformContext* ctx, void* cd) { ((DebugUiInternalContext*)cd)->nativeWindowEventListenerBegin(ctx); } - static void nativeWindowEventListenerWrap(tp::glw::PlatformContext* ctx, void* cd) { ((DebugUiInternalContext*)cd)->nativeWindowEventListener(ctx); } - static void nativeWindowEventListenerWrapEnd(tp::glw::PlatformContext* ctx, void* cd) { ((DebugUiInternalContext*)cd)->nativeWindowEventListenerEnd(ctx); } - - void VirtualKeyboard(tp::halnf dpmm, tp::halnf font_size_mm, tp::halnf ui_scale) { - auto& config = mVKState.mConfigs[mVKState.mActiveConfigIdx]; - - ImGuiID dockspace_id = ImGui::DockSpaceOverViewport(0, ImGuiDockNodeFlags_PassthruCentralNode); - - ImGuiDockNode* node = ImGui::DockContextFindNodeByID(ImGui::GetCurrentContext(), dockspace_id); - - if (!node->IsSplitNode()) { - node->MergedFlags |= ImGuiDockNodeFlags_HiddenTabBar; - ImGuiID dock_id = ImGui::DockBuilderSplitNode(dockspace_id, ImGuiDir_Down, 0.33f, nullptr, &dockspace_id); - ImGui::DockBuilderDockWindow("VK", dock_id); - } - - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 0.f, 0.f }); - ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.f); - ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, { 50 * dpmm, 30 * dpmm }); - ImGui::Begin("VK"); - ImGui::PopStyleVar(3); - - auto pos = ImGui::GetCursorPos(); - - auto width = ImGui::GetWindowWidth(); - auto height = ImGui::GetWindowHeight() - pos.y; - //auto scale = dpmm * ui_scale; - auto padding = dpmm * 2 * ui_scale; - auto button_sizey = (tp::halnf)(height - (config.nrows + 1) * padding) / config.nrows; - - tp::vec2f crs = { pos.x + padding, pos.y + padding }; - - for (auto row = 0; row < config.nrows; row++) { - tp::halnf butt_scalex = (width - (config.rows_sizes[row] + 1) * padding) / config.rows_widths[row]; - - crs.x = pos.x + padding; - - for (auto butt = 0; butt < config.rows_sizes[row]; butt++) { - auto& button = config.rows[row][butt]; - - ImGui::SetCursorPos({ crs.x, crs.y }); - - char name[2] = { mVKState.mShifted ? button.shift_val : button.val, 0 }; - - ImGui::PushID(&button); - if (!ImGui::Button(button.display_name ? button.display_name: name, { butt_scalex * button.width, button_sizey })) { - crs.x += butt_scalex * button.width + padding; - ImGui::PopID(); - continue; - } - - ImGui::SetCurrentContext(ui_context); - button.action(&button, &mVKState); - ImGui::SetCurrentContext(vk_context); - - ImGui::PopID(); - } - - crs.y += button_sizey + padding; - } - - ImGui::End(); - } - }; - } -} - -tp::glw::DebugUI::DebugUI(Window& window, DebugUiDrawCallBack* acb, void* acd) { - mDPMM = window.mDevice.mDPMM; - - // map device size to font and ui size - { - auto device_max = 600.f; - auto device_min = 50.f; - auto device = tp::clamp(window.mDevice.Size.x / mDPMM, device_min, device_max); - auto device_factor = (device - device_min) / (device_max - device_min); - - auto font_min = 2.f; - auto font_max = 3.5f; - mFontSizeMM = (font_max - font_min) * device_factor + font_min; - - auto ui_max = 1.f; - auto ui_min = 0.45f; - mUIScale = (ui_max - ui_min) * device_factor + ui_min; - } - - mCtx = new DebugUiInternalContext(window, acb, acd); -} - -void tp::glw::DebugUI::drawDebugUI(tp::halnf dpmm) { - mDPMM = dpmm; - mCtx->drawDebugUI(mDPMM, mFontSizeMM, mUIScale); -} - -tp::glw::DebugUI::~DebugUI() { - delete mCtx; -} - -// ------------------------------------------------------ // - -static const int sWindowFrameFlags = (ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoDecoration); - -bool ImGui::SubMenuBegin(const char* desc, int level) { - if (level == 1) { - ImGui::Separator(); - } - if (ImGui::TreeNode(desc)) { - GImGui->Style.IndentSpacing = 6; - return true; - } - return false; -} - -void ImGui::SubMenuEnd(int level) { - ImGui::TreePop(); -} - -void ImGui::ToolTip(const char* desc) { - ImGui::SameLine(); - ImGui::TextDisabled("*"); - if (ImGui::IsItemHovered()) { - ImGui::BeginTooltip(); - ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); - ImGui::TextUnformatted(desc); - ImGui::PopTextWrapPos(); - ImGui::EndTooltip(); - } -} - -ImGui::PopupData ImGui::HoverPopupBeginButton(const char* id, tp::vec2f butsize, tp::vec2f popupsize) { - ImVec2 curs = ImGui::GetCursorScreenPos(); - tp::vec2f popup_pos = tp::vec2f(curs.x + butsize.x / 2.f - popupsize.x / 2.f, (curs.y + butsize.y + 7)); - ImGui::Button(id, ImVec2(butsize.x, butsize.y)); ImGui::SameLine(); - return HoverPopupBegin(id, popupsize, popup_pos); -} - -ImGui::PopupData ImGui::HoverPopupBegin(const char* str_id, tp::vec2f size, tp::vec2f pos_p, ImGuiPopupFlags popup_flags) { - ImGui::PopupData out; - out.ishovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); - - if (out.ishovered) { - ImVec2 pos; - - if (pos_p == tp::vec2f(-1)) { - pos = GImGui->CurrentWindow->DC.CursorPos; - } - else { - pos.x = pos_p.x; - pos.y = pos_p.y; - } - - ImGui::SetNextWindowPos(pos); - out.p1 = { pos.x, pos.y }; - - ImGui::OpenPopup(str_id); - - out.p2 = out.p1; - out.p2.x += ImGui::GetWindowWidth(); - } - - if (BeginPopup(str_id, ImGuiWindowFlags_NoMove)) { - out.opened = true; - - auto pos = GetWindowPos(); - out.p1 = { pos.x, pos.y }; - out.p2 = out.p1; - out.p2.x += ImGui::GetWindowWidth(); - - } - return out; -} - -void ImGui::HoverPopupEnd(ImGui::PopupData& in) { - - if (!in.opened) { - return; - } - - in.ishovered |= IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_ChildWindows); - - tp::vec2f mousepos = { ImGui::GetMousePos().x, ImGui::GetMousePos().y }; - tp::halnf tollerance = 10; - tp::rectf tollerace_rect = tp::rectf(tp::vec2f(in.p1.x, in.p1.y - tollerance), tp::vec2f(in.p2.x - in.p1.x, tollerance * 2.f)); - bool is_tollerance = tollerace_rect.inside(mousepos); - - if (!(in.ishovered || is_tollerance)) { - CloseCurrentPopup(); - } - - EndPopup(); -} - -#define VAL(val) (val * dpmm / 3 * ui_scale) -#define VEC(x, y) ImVec2(x * dpmm / 3, y * dpmm / 3 * ui_scale) - -void ImGui::ApplyStyle(tp::halnf dpmm, float font_size_mm, float ui_scale) { - - ImGuiStyle* style = &ImGui::GetStyle(); - auto& io = ImGui::GetIO(); - bool first_init = io.Fonts->Fonts.Size == 0; - auto font_path = getFontPath(); - - // supports PDMM from 0.3 to 10 - const float min_dpmm = 0.3f; - const float max_dpmm = 20.f; - dpmm = tp::clamp(dpmm, min_dpmm, max_dpmm); - - // calc font - const float font_size_mm_max = 10; - const float font_size_pixels_min = 9; - float font_size_mm_min = font_size_pixels_min / dpmm; - const int font_quality_steps = 3; - font_size_mm = tp::clamp(font_size_mm, font_size_mm_min, font_size_mm_max); - - float font_sizes[font_quality_steps]; - for (auto i = 0; i < font_quality_steps; i++) { - auto mm = font_size_mm_min + (font_size_mm_max - font_size_mm_min) * tp::pow(((tp::halnf) (i + 1) / font_quality_steps), 3); - font_sizes[i] = dpmm * mm; - } - - if (first_init) { - for (auto i = 0; i < font_quality_steps; i++) { - io.Fonts->AddFontFromFileTTF(font_path, font_sizes[i] * 1); - } - } - - // select fonts - auto const pixels_required = dpmm * font_size_mm; - auto idx = -1; - for (auto i = 0; i < font_quality_steps; i++) { - idx = i; - if (pixels_required <= font_sizes[i]) { - break; - } - } - DBG_BREAK(idx == -1); - io.FontDefault = io.Fonts->Fonts[idx]; - io.FontGlobalScale = font_size_mm / (font_size_mm_min + ((font_size_mm_max - font_size_mm_min) / font_quality_steps) * (idx + 1)); - io.FontGlobalScale = pixels_required / font_sizes[idx]; - - auto rounding = VAL(5); - auto pudding = VEC(7, 7); - - style->WindowPadding = pudding; - style->WindowRounding = rounding; - //style->WindowMinSize = VEC(11, 11); - style->ChildRounding = rounding; - style->PopupRounding = rounding; - style->FramePadding = pudding; - style->FrameRounding = rounding; - style->ItemSpacing = VEC(4, 11); - style->ItemInnerSpacing = VEC(9, 4); - style->CellPadding = pudding; - style->TouchExtraPadding = pudding; - style->IndentSpacing = VAL(25); - style->ColumnsMinSpacing = VAL(5); - style->ScrollbarSize = VAL(16); - style->ScrollbarRounding = rounding; - style->GrabMinSize = VAL(2); - style->GrabRounding = rounding; - style->LogSliderDeadzone = VAL(2); - style->TabRounding = rounding; - style->TabMinWidthForCloseButton = VAL(5); - style->DisplayWindowPadding = pudding; - style->DisplaySafeAreaPadding = pudding; - style->MouseCursorScale = VAL(5); - - style->FrameBorderSize = VAL(0); - style->WindowBorderSize = VAL(1.5f); - style->ChildBorderSize = VAL(2); - - style->WindowTitleAlign = VEC(0.5f, 0.6f); - style->WindowMenuButtonPosition = ImGuiDir_Right; - - if (!first_init) - return; - - ImVec4* colors = ImGui::GetStyle().Colors; - colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); - colors[ImGuiCol_TextDisabled] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); - colors[ImGuiCol_WindowBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - colors[ImGuiCol_ChildBg] = ImVec4(0.09f, 0.09f, 0.10f, 1.00f); - colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.10f, 1.00f); - colors[ImGuiCol_Border] = ImVec4(0.06f, 0.06f, 0.06f, 1.00f); - colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_FrameBg] = ImVec4(0.14f, 0.14f, 0.17f, 1.00f); - colors[ImGuiCol_FrameBgHovered] = ImVec4(0.27f, 0.27f, 0.33f, 1.00f); - colors[ImGuiCol_FrameBgActive] = ImVec4(0.43f, 0.43f, 0.53f, 1.00f); - colors[ImGuiCol_TitleBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - colors[ImGuiCol_TitleBgActive] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - colors[ImGuiCol_MenuBarBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - colors[ImGuiCol_ScrollbarBg] = ImVec4(0.09f, 0.09f, 0.10f, 0.00f); - colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.15f, 0.15f, 0.19f, 1.00f); - colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.21f, 0.20f, 0.25f, 1.00f); - colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.30f, 0.29f, 0.35f, 1.00f); - colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.48f, 0.50f, 1.00f); - colors[ImGuiCol_SliderGrab] = ImVec4(0.53f, 0.57f, 0.64f, 1.00f); - colors[ImGuiCol_SliderGrabActive] = ImVec4(0.69f, 0.74f, 0.83f, 1.00f); - colors[ImGuiCol_Button] = ImVec4(0.14f, 0.14f, 0.17f, 1.00f); - colors[ImGuiCol_ButtonHovered] = ImVec4(0.27f, 0.27f, 0.33f, 1.00f); - colors[ImGuiCol_ButtonActive] = ImVec4(0.43f, 0.43f, 0.53f, 1.00f); - colors[ImGuiCol_Header] = ImVec4(0.14f, 0.14f, 0.17f, 1.00f); - colors[ImGuiCol_HeaderHovered] = ImVec4(0.27f, 0.27f, 0.33f, 1.00f); - colors[ImGuiCol_HeaderActive] = ImVec4(0.33f, 0.33f, 0.40f, 1.00f); - colors[ImGuiCol_Separator] = ImVec4(0.37f, 0.37f, 0.40f, 1.00f); - colors[ImGuiCol_SeparatorHovered] = ImVec4(0.33f, 0.35f, 0.38f, 1.00f); - colors[ImGuiCol_SeparatorActive] = ImVec4(0.37f, 0.39f, 0.42f, 1.00f); - colors[ImGuiCol_ResizeGrip] = ImVec4(0.16f, 0.17f, 0.19f, 1.00f); - colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.33f, 0.35f, 0.38f, 1.00f); - colors[ImGuiCol_ResizeGripActive] = ImVec4(0.28f, 0.34f, 0.42f, 1.00f); - colors[ImGuiCol_Tab] = ImVec4(0.14f, 0.14f, 0.17f, 1.00f); - colors[ImGuiCol_TabHovered] = ImVec4(0.23f, 0.23f, 0.28f, 1.00f); - colors[ImGuiCol_TabActive] = ImVec4(0.23f, 0.23f, 0.28f, 1.00f); - colors[ImGuiCol_TabUnfocused] = ImVec4(0.11f, 0.15f, 0.17f, 1.00f); - colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.43f, 0.45f, 0.48f, 1.00f); - colors[ImGuiCol_DockingPreview] = ImVec4(0.81f, 0.81f, 0.81f, 0.18f); - colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); - colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.33f, 0.35f, 0.38f, 1.00f); - colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); - colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.49f, 0.51f, 0.54f, 1.00f); - colors[ImGuiCol_TableHeaderBg] = ImVec4(0.13f, 0.13f, 0.20f, 1.00f); - colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); - colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); - colors[ImGuiCol_TableRowBg] = ImVec4(0.23f, 0.20f, 0.20f, 0.00f); - colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); - colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); - colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); - colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); - colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); - colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.38f, 0.22f, 0.22f, 0.20f); - colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); - - colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.10f, 1.00f); - colors[ImGuiCol_DockingPreview] = ImVec4(0.64f, 0.75f, 0.83f, 0.18f); - colors[ImGuiCol_TabHovered] = ImVec4(0.39f, 0.39f, 0.47f, 1.00f); - colors[ImGuiCol_TabActive] = ImVec4(0.27f, 0.27f, 0.33f, 1.00f); - colors[ImGuiCol_TabUnfocused] = ImVec4(0.14f, 0.14f, 0.17f, 1.00f); - colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.24f, 0.24f, 0.29f, 1.00f); - colors[ImGuiCol_Border] = ImVec4(0.65f, 0.65f, 0.65f, 0.70f); - - io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; -} diff --git a/.outdated/graphics/src/fbuffer.cpp b/.outdated/graphics/src/fbuffer.cpp deleted file mode 100644 index 369caa0..0000000 --- a/.outdated/graphics/src/fbuffer.cpp +++ /dev/null @@ -1,116 +0,0 @@ - -#include "fbuffer.h" - -#include "GraphicsLibApi.h" - -void glerr(GLenum type); -#define AssertGL(x) { x; GLenum __gle = glGetError(); if (__gle != GL_NO_ERROR) glerr(__gle); } - -namespace tp { - - using namespace glw; - - fbuffer::fbuffer(const vec2f& size) : mSize(size) { - mDrawBuffers[0] = {GL_COLOR_ATTACHMENT0}; - - // --------- texture --------- - AssertGL(glGenTextures(1, &mTextureId)); - AssertGL(glBindTexture(GL_TEXTURE_2D, mTextureId)); - // Give an empty image to OpenGL ( the last "0" ) - AssertGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)size.x, (GLsizei)size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); - // Poor filtering. Needed - AssertGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); - AssertGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); - - // --------- depth --------- - AssertGL(glGenRenderbuffers(1, &mDepthBufferID)); - AssertGL(glBindRenderbuffer(GL_RENDERBUFFER, mDepthBufferID)); - AssertGL(glRenderbufferStorage(GL_RENDERBUFFER, GLW_CONTEXT_DEPTH_COMPONENT, (GLsizei)size.x, (GLsizei)size.y)); - - // ------------ framebuffer ------------ - AssertGL(glGenFramebuffers(1, &mFrameBufferID)); - AssertGL(glBindFramebuffer(GL_FRAMEBUFFER, mFrameBufferID)); - AssertGL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mDepthBufferID)); - // Set "renderedTexture" as our colour attachement #0 - AssertGL(glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, mTextureId, 0)); - // Set the list of draw buffers. - AssertGL(glDrawBuffers(1, mDrawBuffers)); // "1" is the size of DrawBuffers - assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); - glBindFramebuffer(GL_FRAMEBUFFER, 0); - } - - fbuffer::fbuffer(const vec2f& size, tp::uint1 samples) : mSize(size) { - mDrawBuffers[0] = { GL_COLOR_ATTACHMENT0 }; - - // ------- texture --------- - AssertGL(glGenTextures(1, &mTextureId)); - AssertGL(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mTextureId)); -#ifdef ENV_OS_ANDROID - AssertGL(glTexStorage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGBA, (GLsizei)size.x, (GLsizei)size.y, GL_TRUE)); -#else - AssertGL(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGBA, (GLsizei)size.x, (GLsizei)size.y, GL_TRUE)); -#endif - // !? - //AssertGL(glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); - //AssertGL(glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); - - // ------- depth ------- - AssertGL(glGenRenderbuffers(1, &mDepthBufferID)); - AssertGL(glBindRenderbuffer(GL_RENDERBUFFER, mDepthBufferID)); - AssertGL(glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GLW_CONTEXT_DEPTH_COMPONENT, (GLsizei)size.x, (GLsizei)size.y)); - - // ------- fbuff ------- - AssertGL(glGenFramebuffers(1, &mFrameBufferID)); - AssertGL(glBindFramebuffer(GL_FRAMEBUFFER, mFrameBufferID)); - AssertGL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, mTextureId, 0)); - AssertGL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mDepthBufferID)); - AssertGL(glDrawBuffers(1, mDrawBuffers)); - assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); - glBindFramebuffer(GL_FRAMEBUFFER, 0); - } - - tp::uint4 fbuffer::buffId() const { - return mFrameBufferID; - } - - void fbuffer::beginDraw() { - AssertGL(glBindFramebuffer(GL_FRAMEBUFFER, mFrameBufferID)); - setViewport({ 0.f, 0.f, mSize.x, mSize.y }); - } - - void fbuffer::setViewport(const rectf& viewport) { - AssertGL(glViewport((GLsizei)viewport.x, (GLsizei)viewport.y, (GLsizei)viewport.z, (GLsizei)viewport.w)); - } - - void fbuffer::clear() { - AssertGL(glClearColor(mClearCol.r, mClearCol.g, mClearCol.b, mClearCol.a)); - AssertGL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); - } - - void fbuffer::endDraw() { - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glClearColor(0, 0, 0, 0); - glUseProgram(0); - } - - fbuffer::~fbuffer() { - glDeleteFramebuffers(1, &mFrameBufferID); - glDeleteTextures(1, &mTextureId); - glDeleteRenderbuffers(1, &mDepthBufferID); - } - - uhalni glw::fbuffer::sizeAllocatedMem() const { - return uhalni(sizeof(GLenum) * 4 + mSize.sizeAllocatedMem() + (sizeof(mClearCol) + 1) * (alni) mSize.x * (alni) mSize.y); - } - - uhalni glw::fbuffer::sizeUsedMem() const { - return sizeAllocatedMem(); - } - - uint4 glw::fbuffer::texId() const { - return mTextureId; - } - - const vec2f& fbuffer::getSize() const { return mSize; } - -}; \ No newline at end of file diff --git a/.outdated/graphics/src/linux_window.cpp b/.outdated/graphics/src/linux_window.cpp deleted file mode 100644 index 1162d2f..0000000 --- a/.outdated/graphics/src/linux_window.cpp +++ /dev/null @@ -1,282 +0,0 @@ - -#include "window.h" - -#include "GL/glew.h" -#include "GLFW/glfw3.h" - -#include -#include - -tp::glw::Window::Device tp::glw::Window::mDevice; - -static void glfw_error_callback(int error, const char* description) { - std::cout << stderr << "Glfw Error" << error << " " << description << "\n"; -} - -void tp::glw::Window::init() { - tp::glw::Window::mDevice.Size; - tp::glw::Window::mDevice.FrameRate; - - // Setup window - - setenv("DISPLAY", ":0.0", 0); // does overwrite - - glfwSetErrorCallback(glfw_error_callback); - RelAssert(glfwInit()); - - - // GL 3.0 + GLSL 130 - const char* glsl_version = "#version 130"; - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // 3.0+ only - - glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); - - GLFWmonitor* primary = glfwGetPrimaryMonitor(); - auto mode = glfwGetVideoMode(primary); - - tp::glw::Window::mDevice.Size = { mode->width, mode->height }; - tp::glw::Window::mDevice.FrameRate = mode->refreshRate; -} - -#define MAP_EV(SYSKEY, code) case SYSKEY: { self->mEvents.mKeysQueue.push(tp::KeyEvent{ code, state }); break; } - -namespace tp { - namespace glw { - struct PlatformContext { - - GLFWwindow* window; - tp::glw::Window* window_ctx = NULL; - - PlatformContext(tp::glw::Window* a_window_ctx) { - - window_ctx = a_window_ctx; - - // Create window with graphics context - window = glfwCreateWindow(300, 300, " ", NULL, NULL); - RelAssert(window); - - glfwMakeContextCurrent(window); - - GLenum err = glewInit(); - if (GLEW_OK != err) - { - std::cout << stderr << "Error:" << glewGetErrorString(err); - RelAssert(0); - } - - glfwSwapInterval(1); // Enable vsync - - glfwSetWindowUserPointer(window, window_ctx); - - glfwSetKeyCallback(window, key_callback); - glfwSetMouseButtonCallback(window, mouse_button_callback); - glfwSetScrollCallback(window, scroll_callback); - } - - void applyAppearance(tp::glw::Window::Appearence& appear, tp::glw::Window::Appearence& prev, tp::glw::Window* win_ctx) { - - if (!(appear.mSize == prev.mSize)) { - glfwSetWindowSize(window, appear.mSize.x, appear.mSize.y); - prev.mSize = appear.mSize; - } - - if (!(appear.mPos == prev.mPos)) { - //glfwSetWindowPos(window, appear.mPos.x, appear.mPos.y); - - win_ctx->mEvents.mCursor -= appear.mPos - prev.mPos; - //win_ctx->mEvents.mCursorPrev -= appear.mPos - prev.mPos; - prev.mPos = appear.mPos; - } - - if (!(appear.mSizeMax == prev.mSizeMax && appear.mSizeMin == prev.mSizeMin)) { - glfwSetWindowSizeLimits(window, appear.mSizeMin.x, appear.mSizeMin.y, appear.mSizeMax.x, appear.mSizeMax.y); - prev.mSizeMax = appear.mSizeMax; - prev.mSizeMin = appear.mSizeMin; - } - - if (!(appear.mMaximized == prev.mMaximized)) { - DBG_BREAK(1); - } - - if (!(appear.mMinimized == prev.mMinimized)) { - DBG_BREAK(1); - } - - int width, height; - glfwGetWindowSize(window, &width, &height); - appear.mSize = { width, height }; - prev.mSize = appear.mSize; - - glfwGetWindowPos(window, &width, &height); - appear.mPos = { width, height }; - prev.mPos = appear.mPos; - } - - void beginDraw() { - //int display_w, display_h; - //glfwGetFramebufferSize(window, &display_w, &display_h); - //glViewport(0, 0, display_w, display_h); - //glClearColor(0, 0, 0, 0); - //glClear(GL_COLOR_BUFFER_BIT); - } - - void endDraw() { - glfwSwapBuffers(window); - } - - void pollEvents() { - - glfwPollEvents(); - - double xpos, ypos; - glfwGetCursorPos(window, &xpos, &ypos); - - window_ctx->mEvents.mCursorPrev = window_ctx->mEvents.mCursor; - window_ctx->mEvents.mCursor = { xpos, ypos }; - } - - static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { - auto self = (tp::glw::Window*) glfwGetWindowUserPointer(window); - - if (action != GLFW_PRESS && action != GLFW_RELEASE) { - return; - } - - auto state = (action == GLFW_RELEASE) ? tp::KeyEvent::EventState::RELEASED : tp::KeyEvent::EventState::PRESSED; - - //* VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39) - if (key >= GLFW_KEY_0 && key <= GLFW_KEY_9) { - self->mEvents.mKeysQueue.push(tp::KeyEvent{ tp::Keycode(key), state }); - return; - } - - //* VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A) - else if (key >= GLFW_KEY_A && key <= GLFW_KEY_Z) { - self->mEvents.mKeysQueue.push(tp::KeyEvent{ tp::Keycode(key), state }); - return; - } - - switch (key) { - MAP_EV(GLFW_KEY_LEFT_SHIFT, tp::Keycode::LEFT_SHIFT); - MAP_EV(GLFW_KEY_LEFT, tp::Keycode::LEFT); - MAP_EV(GLFW_KEY_RIGHT, tp::Keycode::RIGHT); - MAP_EV(GLFW_KEY_UP, tp::Keycode::UP); - MAP_EV(GLFW_KEY_DOWN, tp::Keycode::DOWN); - MAP_EV(GLFW_KEY_BACKSPACE, tp::Keycode::BACKSPACE); - MAP_EV(GLFW_KEY_LEFT_CONTROL, tp::Keycode::LEFT_CONTROL); - MAP_EV(GLFW_KEY_MENU, tp::Keycode::LEFT_ALT); - MAP_EV(GLFW_KEY_ENTER, tp::Keycode::ENTER); - MAP_EV(GLFW_KEY_SPACE, tp::Keycode::SPACE); - MAP_EV(GLFW_KEY_COMMA, tp::Keycode::COMMA); - MAP_EV(GLFW_KEY_PERIOD, tp::Keycode::PERIOD); - MAP_EV(GLFW_KEY_TAB, tp::Keycode::TAB); - MAP_EV(GLFW_KEY_EQUAL, tp::Keycode::EQUAL); - MAP_EV(GLFW_KEY_MINUS, tp::Keycode::MINUS); - MAP_EV(GLFW_KEY_3, tp::Keycode::TILDA); - MAP_EV(GLFW_KEY_4, tp::Keycode::BRA); - MAP_EV(GLFW_KEY_5, tp::Keycode::SLASH); - MAP_EV(GLFW_KEY_6, tp::Keycode::KET); - MAP_EV(GLFW_KEY_1, tp::Keycode::DOUBLE_DOT); - MAP_EV(GLFW_KEY_7, tp::Keycode::QUOTES); - MAP_EV(GLFW_KEY_2, tp::Keycode::INV_SLASH); - MAP_EV(GLFW_KEY_ESCAPE, tp::Keycode::ESCAPE); - } - } - - static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { - auto self = (tp::glw::Window*)glfwGetWindowUserPointer(window); - - if (action != GLFW_PRESS && action != GLFW_RELEASE) { - return; - } - - auto state = (action == GLFW_RELEASE) ? tp::KeyEvent::EventState::RELEASED : tp::KeyEvent::EventState::PRESSED; - - - switch (button) { - case GLFW_MOUSE_BUTTON_RIGHT: { - self->mEvents.mKeysQueue.push(tp::KeyEvent{ tp::Keycode::MOUSE2, state }); - } break; - case GLFW_MOUSE_BUTTON_LEFT: { - self->mEvents.mKeysQueue.push(tp::KeyEvent{ tp::Keycode::MOUSE1, state }); - } break; - case GLFW_MOUSE_BUTTON_MIDDLE: { - self->mEvents.mKeysQueue.push(tp::KeyEvent{ tp::Keycode::MOUSE3, state }); - } break; - } - } - - static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { - } - - ~PlatformContext() { - glfwDestroyWindow(window); - } - }; - }; -}; - - -void tp::glw::Window::deinit() {} - -tp::glw::Window::Window() { - initialize(); - - mAppearence.mSize = tp::glw::Window::mDevice.Size / 1.5f; - mAppearence.mPos = (tp::glw::Window::mDevice.Size - mAppearence.mSize) / 2.f; - mAppearence.mSizeMax = tp::glw::Window::mDevice.Size; - - applyAppearance(); -} - -tp::glw::Window::Window(const Appearence& aAppearence) { - mAppearence = aAppearence; - initialize(); -} - -void tp::glw::Window::initialize() { - mPlatformCtx = new PlatformContext(this); - applyAppearance(); -} - -void tp::glw::Window::applyAppearance() { - mPlatformCtx->applyAppearance(mAppearence, this->mCache.mAppearencePrev, this); -} - -void tp::glw::Window::pollEvents() { - applyAppearance(); - mPlatformCtx->pollEvents(); - - mEvents.mRedraw |= (mEvents.mCursorPrev - mEvents.mCursor) != 0; - mEvents.mRedraw |= mEvents.mKeysQueue.length; -} - -void tp::glw::Window::platformCallback() {} - -void tp::glw::Window::beginDraw() { - mPlatformCtx->beginDraw(); -} - -void tp::glw::Window::endDraw() { - mPlatformCtx->endDraw(); - if (mEvents.mRedraw-- < 0) mEvents.mRedraw = 0; -} - -void* tp::glw::Window::platform_window() const { - return mPlatformCtx->window; -} - -tp::alni tp::glw::Window::sizeAllocatedMem() { - return 0; -} - -tp::alni tp::glw::Window::sizeUsedMem() { - return 0; -} - -tp::glw::Window::~Window() { - delete mPlatformCtx; -} diff --git a/.outdated/graphics/src/shader.cpp b/.outdated/graphics/src/shader.cpp deleted file mode 100644 index b630b5a..0000000 --- a/.outdated/graphics/src/shader.cpp +++ /dev/null @@ -1,170 +0,0 @@ - - -#include "stringt.h" - -#include "array.h" - -#include "array.h" -#include "filesystem.h" -#include "shader.h" - -#include "new.h" - -#include "GraphicsLibApi.h" - -#include - -namespace tp { - - using namespace glw; - - //string shader_path = "../rsc/shaders/"; - - shader::shader() { - programm = 0; - VertexShaderID = 0; - FragmentShaderID = 0; - GeometryShaderID = 0; - } - - void shader::vert_bind_source(const char* vert_src) { - VertexShaderID = glCreateShader(GL_VERTEX_SHADER); - compile_shader(vert_src, VertexShaderID); - } - - void shader::frag_bind_source(const char* frag_src) { - FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); - compile_shader(frag_src, FragmentShaderID); - } - - void shader::geom_bind_source(const char* geom_src) { - GeometryShaderID = glCreateShader(GL_GEOMETRY_SHADER); - compile_shader(geom_src, GeometryShaderID); - } - - void shader::compile() { - GLint Result = GL_FALSE; - int InfoLogLength; - - programm = glCreateProgram(); - glAttachShader(programm, VertexShaderID); - if (GeometryShaderID) glAttachShader(programm, GeometryShaderID); - glAttachShader(programm, FragmentShaderID); - glLinkProgram(programm); - - // Check the program - glGetProgramiv(programm, GL_LINK_STATUS, &Result); - glGetProgramiv(programm, GL_INFO_LOG_LENGTH, &InfoLogLength); - - if (InfoLogLength > 0) { - Array ProgramErrorMessage(InfoLogLength + 1); - glGetProgramInfoLog(programm, InfoLogLength, NULL, &ProgramErrorMessage[0]); - printf("%s\n", &ProgramErrorMessage[0]); - } - - glDetachShader(programm, VertexShaderID); - glDetachShader(programm, FragmentShaderID); - if (GeometryShaderID) glDetachShader(programm, GeometryShaderID); - - glDeleteShader(VertexShaderID); - glDeleteShader(FragmentShaderID); - if (GeometryShaderID) glDeleteShader(GeometryShaderID); - } - - bool shader::compile_shader(const char* ShaderCode, uint4 ShaderID) { - GLint Result = GL_FALSE; - int InfoLogLength; - - char const* SourcePointer = ShaderCode; - glShaderSource(ShaderID, 1, &SourcePointer, NULL); - glCompileShader(ShaderID); - - // Check Shader - glGetShaderiv(ShaderID, GL_COMPILE_STATUS, &Result); - glGetShaderiv(ShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); - - if (InfoLogLength > 0) { - Array VertexShaderErrorMessage(InfoLogLength + 1); - glGetShaderInfoLog(ShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); - printf("%s\n", &VertexShaderErrorMessage[0]); - } - - return Result; - } - - - void shader::load(const char* pvert, const char* pgeom, const char* pfrag, bool paths) { - - // Create the shaders - VertexShaderID = glCreateShader(GL_VERTEX_SHADER); - FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); - if (pgeom) GeometryShaderID = glCreateShader(GL_GEOMETRY_SHADER); - else GeometryShaderID = 0; - - GLint Result = GL_FALSE; - int InfoLogLength = 0; - - if (paths) { - string vert = sfmt("%c.vert", pvert); - string geom = pgeom ? sfmt("%c.geom", pgeom) : " "; - string frag = sfmt("%c.frag", pfrag); - - tp::string content; - - printf("Compiling shader : %s\n", vert.cstr()); - if (content.loadFile(vert)) { - compile_shader(content.cstr(), VertexShaderID); - } - - if (GeometryShaderID) { - printf("Compiling shader : %s\n", geom.cstr()); - if (content.loadFile(geom)) { - compile_shader(content.cstr(), GeometryShaderID); - } - } - - printf("Compiling shader : %s\n", frag.cstr()); - if (content.loadFile(frag)) { - compile_shader(content.cstr(), FragmentShaderID); - } - } - else { - compile_shader(pvert, VertexShaderID); - if (GeometryShaderID) { - compile_shader(pgeom, GeometryShaderID); - } - compile_shader(pfrag, FragmentShaderID); - } - - compile(); - } - - shader::shader(const char* vert, const char* geom, const char* frag, bool paths) { - load(vert, geom, frag, paths); - } - - void shader::bind() { - glUseProgram(programm); - } - - GLuint glw::shader::getu(const char* uid) { - return glGetUniformLocation(programm, uid); - } - - void shader::unbind() { - glUseProgram(0); - } - - shader::~shader() { - glDeleteProgram(programm); - } - - alni glw::shader::sizeAllocatedMem() { - return sizeof(GLuint) * 4; - } - - alni glw::shader::sizeUsedMem() { - return sizeof(GLuint) * 4; - } - -}; \ No newline at end of file diff --git a/.outdated/graphics/src/simplegui.cpp b/.outdated/graphics/src/simplegui.cpp deleted file mode 100644 index daed0e3..0000000 --- a/.outdated/graphics/src/simplegui.cpp +++ /dev/null @@ -1,164 +0,0 @@ -#pragma once - -#include "simplegui.h" - -using namespace tp; -using namespace glw; - -void WindowSimpleInputs::update(const glw::Window& window, halnf uiscale) { - mScaleVal = (window.mDevice.mDPMM * uiscale); - mWindowSizeMM = window.mAppearence.mSize / mScaleVal; - mCrs = window.mEvents.mCursor / mScaleVal; - mCrsPrev = window.mEvents.mCursorPrev / mScaleVal; - mCrsmDelta = mCrs - mCrsPrev; - - if (mMouse == Mouse::PRESSED) { - mMouse = Mouse::HOLD; - } - else if (mMouse == Mouse::RELEASED) { - mMouse = Mouse::NONE; - } - mMove = Move::NONE; - - for (auto event : window.mEvents.mKeysQueue) { - bool press = event.data().event_state == KeyEvent::EventState::PRESSED; - if (press) { - switch (event.data().code) { - case Keycode::UP: mMove = Move::UP; break; - case Keycode::DOWN: mMove = Move::DOWN; break; - case Keycode::LEFT: mMove = Move::LEFT; break; - case Keycode::RIGHT: mMove = Move::RIGHT; break; - } - } - if (event.data().code == Keycode::MOUSE1) { - if (press) { - mMouse = Mouse::PRESSED; - } - else { - mMouse = Mouse::RELEASED; - } - } - } -} - -bool WindowSimpleInputs::Activated() { return mMouse == Mouse::PRESSED; } -bool WindowSimpleInputs::Anticipating() { return mMouse == Mouse::HOLD; } -bool WindowSimpleInputs::Selected() { return mMouse == Mouse::RELEASED; } -bool WindowSimpleInputs::MoveLeft() { return mMove == Move::LEFT; } -bool WindowSimpleInputs::MoveRight() { return mMove == Move::RIGHT; } -bool WindowSimpleInputs::MoveUp() { return mMove == Move::UP; } -bool WindowSimpleInputs::MoveDown() { return mMove == Move::DOWN; } -bool WindowSimpleInputs::Drag() { return mCrsmDelta != 0; } - -void ButtonWidget::draw(glw::Canvas& canvas) { - canvas.setCol1(mCol); - canvas.rect(mAnimRec.get(), 1.f); -} - -void ButtonWidget::proc(glw::WindowSimpleInputs& inputs) { - auto rec = mAnimRec.get(); - mPressed = false; - - mAnimRec.setAnimTime(100); - - if (rec.inside(inputs.mCrs)) { - if (inputs.Anticipating()) { - auto new_rec = mRect; - new_rec.scale_from_center(0.3f, true); - mAnimRec.setNoTransition(new_rec); - } - else { - mAnimRec.set(mRect); - } - - if (inputs.Selected()) { - mPressed = true; - } - } - else { - auto new_rec = mRect; - new_rec.scale_from_center(0.3f, true); - mAnimRec.set(new_rec); - } -} - -void CheckBoxWidget::draw(glw::Canvas& canvas) { - canvas.setCol1(mAnimCol.get()); - canvas.rect(mAnimRec.get(), 1.f); -} - -void CheckBoxWidget::proc(glw::WindowSimpleInputs& inputs) { - auto rec = mAnimRec.get(); - - mAnimRec.setAnimTime(100); - - if (rec.inside(inputs.mCrs)) { - if (inputs.Anticipating()) { - auto new_rec = mRect; - new_rec.scale_from_center(0.3f, true); - mAnimRec.setNoTransition(new_rec); - } - else { - mAnimRec.set(mRect); - } - - if (inputs.Selected()) { - mValue = !mValue; - } - } - else { - auto new_rec = mRect; - new_rec.scale_from_center(0.3f, true); - mAnimRec.set(new_rec); - } - - if (mValue) { - mAnimCol.set(mColActive); - } - else { - mAnimCol.set(mCol); - } -} - -void WindowsHeaderWidget::updRecs() { - auto padding = 0.7f; - auto butt_size = header_rec.w - padding * 2.f; - grab_rec = { header_rec.pos, { header_rec.z - header_rec.w * 4, header_rec.w } }; - mPinButton.mRect = { { grab_rec.pos.x + grab_rec.size.x + padding, grab_rec.y + padding }, butt_size }; - mMinButton.mRect = { { mPinButton.mRect.pos.x + mPinButton.mRect.size.x + padding * 2, mPinButton.mRect.y }, butt_size }; - mMaxButton.mRect = { { mMinButton.mRect.pos.x + mMinButton.mRect.size.x + padding * 2, mPinButton.mRect.y }, butt_size }; - mExitButton.mRect = { { mMaxButton.mRect.pos.x + mMaxButton.mRect.size.x + padding * 2, mPinButton.mRect.y }, butt_size }; - - mPinButton.mCol = { 0.3f, 0.3f, 0.3f, 0.9f}; - mMinButton.mCol = { 0.3f, 0.3f, 0.8f, 0.9f }; - mMaxButton.mCol = { 0.3f, 0.8f, 0.3f, 0.9f }; - mExitButton.mCol = { 0.8f, 0.3f, 0.3f, 0.9f }; -} - -void WindowsHeaderWidget::draw(glw::Canvas& canvas) { - updRecs(); - canvas.setCol1(col); - canvas.rect(header_rec, 1.f); - canvas.setCol1(1.f); - canvas.text("MemLeaks", grab_rec, 4.f); - - mExitButton.draw(canvas); - mMaxButton.draw(canvas); - mMinButton.draw(canvas); - mPinButton.draw(canvas); -} - -void WindowsHeaderWidget::proc(glw::Window& window, glw::WindowSimpleInputs& inputs) { - get_time(); - - mExitButton.proc(inputs); - mMaxButton.proc(inputs); - mMinButton.proc(inputs); - mPinButton.proc(inputs); - - window.mAppearence.mMinMaxBox = mMaxButton.mRect * inputs.mScaleVal; - window.mAppearence.mCaptionsAddArea = { grab_rec * inputs.mScaleVal }; - window.mAppearence.mMinimized = mMinButton.mPressed; - window.mEvents.mClose = mExitButton.mPressed; - window.mAppearence.mTopZ = mPinButton.mValue; -} \ No newline at end of file diff --git a/.outdated/graphics/src/texture.cpp b/.outdated/graphics/src/texture.cpp deleted file mode 100644 index 94fa96e..0000000 --- a/.outdated/graphics/src/texture.cpp +++ /dev/null @@ -1,216 +0,0 @@ - -#include "texture.h" - -#include "map.h" - -#include "stringt.h" - -#include "shader.h" - -#include "GraphicsLibApi.h" - -const char* texture_vertex = -#ifdef ENV_OS_ANDROID -"#version 300 es\n" -"precision mediump float;\n" -#else -"#version 330 core\n" -#endif -"layout(location = 0) in vec3 vPos;\n" -"out vec2 UV;\n" -"void main() {\n" -" gl_Position = vec4(vPos, 1);\n" -" UV = (vPos.xy + vec2(1, 1)) / 2.0;\n" -"}\n"; - -const char* texture_fragment = -#ifdef ENV_OS_ANDROID -"#version 300 es\n" -"precision mediump float;\n" -#else -"#version 330 core\n" -#endif -"in vec2 UV;\n" -"out vec4 color;\n" -"uniform sampler2D renderedTexture;\n" -"uniform float time;\n" -"void main() {\n" -" vec4 texColor = texture(renderedTexture, UV);\n" -" if (texColor.a < 0.2)\n" -" discard;\n" -" color = texColor;\n" -"}\n"; - -namespace tp { - - using namespace glw; - - GLuint texture::getid() { return id; } - - texture::texture() { - glGenTextures(1, &id); - glBindTexture(GL_TEXTURE_2D, id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glBindTexture(GL_TEXTURE_2D, 0); - } - - texture::~texture() { glDeleteTextures(1, &id); } - - alni texture::sizeAllocatedMem() { - return sizeof(GLuint); - } - - alni texture::sizeUsedMem() { - return sizeof(GLuint); - } - - - void texture::update(const Array2D& buff) { - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)buff.size().x, (GLsizei)buff.size().y, 0, GL_RGBA, GL_FLOAT, buff.buff()); - } - - void texture::draw(const GLuint& out) { - draw_texture(out, id); - } - - - struct texture_drawer_data { - - HashMap textures; - - GLuint quad_VertexArrayID; - GLuint quad_vertexbuffer; - GLuint texID; - glw::shader shader; - - const GLfloat g_quad_vertex_buffer_data[18] = { - -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, - -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, - }; - - texture_drawer_data() : shader(texture_vertex, NULL, texture_fragment, false) { - // The fullscreen quad's FBO - glGenVertexArrays(1, &quad_VertexArrayID); - glBindVertexArray(quad_VertexArrayID); - - glGenBuffers(1, &quad_vertexbuffer); - glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), - g_quad_vertex_buffer_data, GL_STATIC_DRAW); - - texID = shader.getu("renderedTexture"); - } - - ~texture_drawer_data() { - glDeleteBuffers(1, &quad_vertexbuffer); - glDeleteVertexArrays(1, &quad_VertexArrayID); - - for (auto tex : textures) { - glDeleteTextures(1, &tex->val); - } - } - }; - - texture_drawer_data* texdd = NULL; - - void texture::init() { - if (!texdd) texdd = new texture_drawer_data(); - } - - void texture::deinit() { - if (texdd) delete texdd; - texdd = NULL; - } - - void texture::draw_texture(uint4 out, uint4 in) { - assert(in); - - // Render to the screen - glBindFramebuffer(GL_FRAMEBUFFER, out); - - // Use our shader - texdd->shader.bind(); - - // Bind our texture in Texture Unit 0 - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, in); - // Set our "renderedTexture" sampler to use Texture Unit 0 - glUniform1i(texdd->texID, 0); - - // glUniformMatrix4fv(texdd->rect_mat, 1, GL_FALSE, &tmat[0][0]); - - // 1rst attribute buffer : vertices - glEnableVertexAttribArray(0); - glBindBuffer(GL_ARRAY_BUFFER, texdd->quad_vertexbuffer); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); - - // Draw the triangles. 2*3 indices starting at 0 -> 2 triangles - glDrawArrays(GL_TRIANGLES, 0, 6); - - glDisableVertexAttribArray(0); - - texdd->shader.unbind(); - } - - GLuint load_texture(string name) { - GLuint tex_2d = 0; - RelAssert(0 && "incomplete compilation - no SOIL support added"); - - if (0) { - //auto document = lunasvg::Document::loadFromFile("tiger.svg"); - //auto bitmap = document->renderToBitmap(); - } - else { - /* - tex_2d = SOIL_load_OGL_texture( - name.cstr(), SOIL_LOAD_RGBA, SOIL_CREATE_NEW_ID, - SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | - SOIL_FLAG_COMPRESS_TO_DXT); - - if (0 == tex_2d) { - printf("SOIL loading error: '%s'\n", SOIL_last_result()); - } - */ - } - - return tex_2d; - } - - GLuint texture::get_tex(const char* TexId) { - GLuint out = 0; - alni idx = texdd->textures.presents(TexId); - if (idx != -1) { - out = texdd->textures.get(TexId); - } - else { - out = load_texture(TexId); - texdd->textures.put(TexId, out); - } - return out; - } - - void texture::drawCurcle(vec2f pos, double radius, rgba col) { -#ifndef ENV_OS_ANDROID - static alni precision = 40; - - glColor4f(col.r, col.g, col.b, col.a); - - double twicePi = 2.0 * 3.142; - - glBegin(GL_TRIANGLE_FAN); // BEGIN CIRCLE - glVertex2f(pos.x, pos.y); // center of circle - - for (alni i = 0; i <= precision; i++) { - glVertex2f((GLfloat)(pos.x + (radius * cos(i * twicePi / precision))), - (GLfloat)(pos.y + (radius * sin(i * twicePi / precision)))); - } - glEnd(); // END -#endif - } -}; - - diff --git a/.outdated/graphics/src/windows_window.cpp b/.outdated/graphics/src/windows_window.cpp deleted file mode 100644 index ca721cc..0000000 Binary files a/.outdated/graphics/src/windows_window.cpp and /dev/null differ diff --git a/.outdated/graphics/tests/tests.cpp b/.outdated/graphics/tests/tests.cpp deleted file mode 100644 index b1d5304..0000000 --- a/.outdated/graphics/tests/tests.cpp +++ /dev/null @@ -1,107 +0,0 @@ - -#include "SimpleGui.h" -#include "debugui.h" -#include "texture.h" -#include "timer.h" -#include "imgui.h" - -struct CollorWheelWidget { - tp::rgba col = { 0.3f, 0.3f, 0.3f, 0.9f }; - tp::rectf rec = { 10, 30, 40, 40 }; - - void draw(tp::glw::Canvas& canvas) { - canvas.setCol1(col); - canvas.rect(rec, 3.f); - canvas.drawColorwheel(rec, col.rgbs); - } -}; - -struct Test { - - tp::glw::Window window; - tp::glw::DebugUI ui; - tp::glw::Canvas canvas; - tp::glw::WindowsHeaderWidget header; - tp::glw::WindowSimpleInputs inputs; - tp::halnf mHeaderHeight = 6.5f; - - CollorWheelWidget colorwheel; - tp::halnf uiscale = 1.f; - tp::Timer time; - tp::halni frames = 0; - tp::halni fps = 0; - - Test() : window(), ui(window, debuguiCallBack, this), time(1000) { - tp::glw::texture::init(); - canvas.setCol1({ 0.5f, 0.5f, 0.5f, 0.5f }); - window.mAppearence.mHiden = false; - } - - void proc() { - window.pollEvents(); - inputs.update(window, uiscale); - - header.header_rec = { (inputs.mWindowSizeMM.x - 60.f) / 2.f, 3.f, 60.f, mHeaderHeight }; - header.proc(window, inputs); - } - - void draw() { - // window frame - window.beginDraw(); { - // canvas draw - canvas.beginDraw({ { 0, 0 }, inputs.mWindowSizeMM }, window.mDevice.mDPMM, uiscale); { - canvas.clear(); - header.draw(canvas); - colorwheel.draw(canvas); - } canvas.endDraw(); - // debug draw - ui.drawDebugUI(window.mDevice.mDPMM); - } window.endDraw(); - } - - void run() { - while (!window.mEvents.mClose) { - proc(); - if (window.mEvents.mRedraw || tp::glw::gInTransition) { - draw(); - } - if (time.isTimeout()) { - fps = frames; - frames = 0; - time.reset(); - } - frames++; - } - } - - void debugui() { - static char buff[100]; - ImGui::DragFloat("UI SCale", &uiscale, 0.02); - ImGui::Text("Fps: %i", fps); - ImGui::InputText("Fps: %i", buff, 100); - } - - static void debuguiCallBack(void* self) { - ((Test*)self)->debugui(); - } - - ~Test() { - tp::glw::texture::deinit(); - } -}; - -CROSSPLATFORM_MAIN -int main() { - tp::ModuleManifest* ModuleDependencies[] = { &tp::gModuleGlw, NULL }; - tp::ModuleManifest TestModule("Test", NULL, NULL, ModuleDependencies); - if (!TestModule.initialize()) { - return 1; - } - - { - Test test; - test.run(); - } - - TestModule.deinitialize(); -} \ No newline at end of file diff --git a/Allocators/private/Allocators.cpp b/Allocators/private/Allocators.cpp index ad1d935..eb4b494 100644 --- a/Allocators/private/Allocators.cpp +++ b/Allocators/private/Allocators.cpp @@ -3,25 +3,22 @@ #include -static void deinit(const tp::ModuleManifest* self) { - tp::HeapAllocGlobal::checkLeaks(); -} +static void deinit(const tp::ModuleManifest* self) { tp::HeapAllocGlobal::checkLeaks(); } static tp::ModuleManifest* sModuleDependencies[] = { &tp::gModuleUtils, nullptr }; tp::ModuleManifest tp::gModuleAllocators = ModuleManifest("Allocators", nullptr, deinit, sModuleDependencies); - void* operator new(size_t aSize) { return tp::HeapAllocGlobal::allocate(aSize); } void* operator new[](size_t aSize) { return tp::HeapAllocGlobal::allocate(aSize); } -void operator delete(void* aPtr) noexcept { tp::HeapAllocGlobal::deallocate(aPtr); } -void operator delete[](void* aPtr) noexcept { tp::HeapAllocGlobal::deallocate(aPtr); } +void operator delete(void* aPtr) noexcept { tp::HeapAllocGlobal::deallocate(aPtr); } +void operator delete[](void* aPtr) noexcept { tp::HeapAllocGlobal::deallocate(aPtr); } void* operator new(size_t aSize, tp::HeapAlloc& aAlloc) { return aAlloc.allocate(aSize); } void* operator new[](size_t aSize, tp::HeapAlloc& aAlloc) { return aAlloc.allocate(aSize); } -void operator delete(void* aPtr, tp::HeapAlloc& aAlloc) { aAlloc.deallocate(aPtr); } -void operator delete[](void* aPtr, tp::HeapAlloc& aAlloc) { aAlloc.deallocate(aPtr); } +void operator delete(void* aPtr, tp::HeapAlloc& aAlloc) { aAlloc.deallocate(aPtr); } +void operator delete[](void* aPtr, tp::HeapAlloc& aAlloc) { aAlloc.deallocate(aPtr); } void* operator new(size_t aSize, tp::HeapAllocGlobal& aAlloc) { return tp::HeapAllocGlobal::allocate(aSize); } void* operator new[](size_t aSize, tp::HeapAllocGlobal& aAlloc) { return tp::HeapAllocGlobal::allocate(aSize); } -void operator delete(void* aPtr, tp::HeapAllocGlobal& aAlloc) { tp::HeapAllocGlobal::deallocate(aPtr); } -void operator delete[](void* aPtr, tp::HeapAllocGlobal& aAlloc) { tp::HeapAllocGlobal::deallocate(aPtr); } \ No newline at end of file +void operator delete(void* aPtr, tp::HeapAllocGlobal& aAlloc) { tp::HeapAllocGlobal::deallocate(aPtr); } +void operator delete[](void* aPtr, tp::HeapAllocGlobal& aAlloc) { tp::HeapAllocGlobal::deallocate(aPtr); } \ No newline at end of file diff --git a/Allocators/private/HeapAllocator.cpp b/Allocators/private/HeapAllocator.cpp index a1994da..1b18b2f 100644 --- a/Allocators/private/HeapAllocator.cpp +++ b/Allocators/private/HeapAllocator.cpp @@ -1,70 +1,69 @@ - - -#include "HeapAllocator.hpp" -#include "HeapAllocatorGlobal.hpp" - -#include "PrivateConfig.hpp" - -using namespace tp; - -#if not defined(MEM_DEBUG) - -// ----------------------- Release Implementation ---------------------------- // -void* HeapAlloc::allocate(ualni aBlockSize) { return malloc(aBlockSize); } -void HeapAlloc::deallocate(void* aPtr) { free(aPtr); } -HeapAlloc::~HeapAlloc() {} - -#else - -namespace tp { - struct MemHeadLocal { - MemHeadLocal* mPrev; - MemHeadLocal* mNext; - }; -} - -void* HeapAlloc::allocate(ualni aBlockSize) { - auto head = (MemHeadLocal*) HeapAllocGlobal::allocate(aBlockSize + sizeof(MemHeadLocal)); - auto out = head + 1; - - mNumAllocations++; - if (mEntry) { - DEBUG_ASSERT(!mEntry->mNext) - head->mNext = nullptr; - head->mPrev = mEntry; - mEntry->mNext = head; - } else { - head->mNext = nullptr; - head->mPrev = nullptr; - } - mEntry = head; - - return out; -} - -void HeapAlloc::deallocate(void* aPtr) { - auto head = ((MemHeadLocal*)(aPtr)) - 1; - - mNumAllocations--; - DEBUG_ASSERT(!mEntry->mNext) - if (head->mNext) head->mNext->mPrev = head->mPrev; - if (head->mPrev) head->mPrev->mNext = head->mNext; - if (head == mEntry) { - mEntry = head->mPrev; - } - - HeapAllocGlobal::deallocate(head); -} - -HeapAlloc::~HeapAlloc() { - if (mNumAllocations) { - DEBUG_BREAK("Destruction of not freed Allocator") - - #ifdef MEM_STACK_TRACE - // TODO : log leaks and free them up - #endif - } -} - -#endif - + + +#include "HeapAllocator.hpp" +#include "HeapAllocatorGlobal.hpp" + +#include "PrivateConfig.hpp" + +using namespace tp; + +#if not defined(MEM_DEBUG) + +// ----------------------- Release Implementation ---------------------------- // +void* HeapAlloc::allocate(ualni aBlockSize) { return malloc(aBlockSize); } +void HeapAlloc::deallocate(void* aPtr) { free(aPtr); } +HeapAlloc::~HeapAlloc() {} + +#else + +namespace tp { + struct MemHeadLocal { + MemHeadLocal* mPrev; + MemHeadLocal* mNext; + }; +} + +void* HeapAlloc::allocate(ualni aBlockSize) { + auto head = (MemHeadLocal*) HeapAllocGlobal::allocate(aBlockSize + sizeof(MemHeadLocal)); + auto out = head + 1; + + mNumAllocations++; + if (mEntry) { + DEBUG_ASSERT(!mEntry->mNext) + head->mNext = nullptr; + head->mPrev = mEntry; + mEntry->mNext = head; + } else { + head->mNext = nullptr; + head->mPrev = nullptr; + } + mEntry = head; + + return out; +} + +void HeapAlloc::deallocate(void* aPtr) { + auto head = ((MemHeadLocal*) (aPtr)) - 1; + + mNumAllocations--; + DEBUG_ASSERT(!mEntry->mNext) + if (head->mNext) head->mNext->mPrev = head->mPrev; + if (head->mPrev) head->mPrev->mNext = head->mNext; + if (head == mEntry) { + mEntry = head->mPrev; + } + + HeapAllocGlobal::deallocate(head); +} + +HeapAlloc::~HeapAlloc() { + if (mNumAllocations) { + DEBUG_BREAK("Destruction of not freed Allocator") + +#ifdef MEM_STACK_TRACE +// TODO : log leaks and free them up +#endif + } +} + +#endif diff --git a/Allocators/private/HeapAllocatorGlobal.cpp b/Allocators/private/HeapAllocatorGlobal.cpp index 469070d..fc7b748 100644 --- a/Allocators/private/HeapAllocatorGlobal.cpp +++ b/Allocators/private/HeapAllocatorGlobal.cpp @@ -1,198 +1,196 @@ - - -#include "HeapAllocatorGlobal.hpp" -#include "PrivateConfig.hpp" - -#include "Utils.hpp" -#include "Debugging.hpp" - -#include -#include - -using namespace tp; - -#if not defined(MEM_DEBUG) - -// ----------------------- Release Implementation ---------------------------- // - -void* HeapAllocGlobal::allocate(ualni aBlockSize) { return malloc(aBlockSize); } -void HeapAllocGlobal::deallocate(void* aPtr) { free(aPtr); } -HeapAllocGlobal::~HeapAllocGlobal() = default; - -#else - -tp::MemHead* tp::HeapAllocGlobal::mEntry = nullptr; -tp::ualni tp::HeapAllocGlobal::mNumAllocations = 0; -tp::Mutex tp::HeapAllocGlobal::mMutex; -bool tp::HeapAllocGlobal::mIgnore; - -// ----------------------- Debug Implementation ---------------------------- // -// |----------------| -// | MemHead | -// |----------------| -// | wrap top | -// |----------------| - Allocated Block Layout -// | data | -// |----------------| -// | wrap bottom | -// |----------------| - -namespace tp { - struct MemHead { - MemHead* mPrev; - MemHead* mNext; - uhalni mBlockSize; - uhalni mIgnored; - #ifdef MEM_STACK_TRACE - const CallStackCapture::CallStack* mCallStack; - #endif - }; -} - -enum : ualni { - ALIGNED_SIZE = ENV_ALNI_SIZE_B, - WRAP_SIZE = MEM_WRAP_SIZE * ALIGNED_SIZE, - WRAP_VAL = MEM_WRAP_FILL_VAL, - HEAD_SIZE = sizeof(MemHead), - CLEAR_ALLOC_VAL = MEM_CLEAR_ON_ALLOC_VAL, - CLEAR_DEALLOC_VAL = MEM_CLEAR_ON_DEALLOC_VAL, -}; - -void* HeapAllocGlobal::allocate(ualni aBlockSize) { - - static_assert(HEAD_SIZE % ALIGNED_SIZE == 0, "Heap Allocator Configuration Error"); - - if (aBlockSize % ALIGNED_SIZE) { - aBlockSize = (aBlockSize / ALIGNED_SIZE + 1) * ALIGNED_SIZE; - } - - // 1) Allocate the block - ALLOCATE: - auto head = (MemHead*)malloc(aBlockSize + WRAP_SIZE * 2 + HEAD_SIZE); - if (!head) { - printf("WARNING : Cant allocate memory. Trying again\n"); - goto ALLOCATE; // Just freeze if no memory is available - } - - auto wrap_top = (int1*)(head + 1); - auto data = wrap_top + WRAP_SIZE; - auto wrap_bottom = data + aBlockSize; - - head->mBlockSize = aBlockSize; - head->mIgnored = mIgnore; - - // 2) Link with existing blocks - mMutex.lock(); - mNumAllocations++; - if (mEntry) { - DEBUG_ASSERT(mEntry->mNext == nullptr) - head->mNext = nullptr; - head->mPrev = mEntry; - mEntry->mNext = head; - } else { - head->mNext = nullptr; - head->mPrev = nullptr; - } - mEntry = head; - - - // 3) Trace the stack - #ifdef MEM_STACK_TRACE - head->mCallStack = gCSCapture->getSnapshot(); - #endif - - mMutex.unlock(); - - // 4) Wrap fill - memSetVal(wrap_top, WRAP_SIZE, WRAP_VAL); - memSetVal(wrap_bottom, WRAP_SIZE, WRAP_VAL); - - // 5) clear data -#ifdef MEM_CLEAR_ON_ALLOC - memSetVal(data, aBlockSize, CLEAR_ALLOC_VAL); -#endif - - return data; -} - -void HeapAllocGlobal::deallocate(void* aPtr) { - if (!aPtr) return; - - // 1) Restore the pointers - auto head = ((MemHead*)((int1*)aPtr - WRAP_SIZE)) - 1; - auto wrap_top = (int1*)(head + 1); - auto data = wrap_top + WRAP_SIZE; - auto wrap_bottom = data + head->mBlockSize; - - // 2) Unlink with blocks - mMutex.lock(); - mNumAllocations--; - DEBUG_ASSERT(!mEntry->mNext) - if (head->mNext) head->mNext->mPrev = head->mPrev; - if (head->mPrev) head->mPrev->mNext = head->mNext; - if (head == mEntry) { - mEntry = head->mPrev; - } - mMutex.unlock(); - - if (!head->mIgnored) { - // 3) Check the wrap - if (memCompareVal(wrap_top, WRAP_SIZE, WRAP_VAL)) { - CallStackCapture::printSnapshot(head->mCallStack); - ASSERT(!"Allocated Block Wrap Corrupted!") - } - - if (memCompareVal(wrap_bottom, WRAP_SIZE, WRAP_VAL)) { - CallStackCapture::printSnapshot(head->mCallStack); - ASSERT(!"Allocated Block Wrap Corrupted!") - } - - // 4) clear data - #ifdef MEM_CLEAR_ON_ALLOC - memSetVal(data, head->mBlockSize, CLEAR_DEALLOC_VAL); - #endif - } - - // 5) free the block - free(head); -} - -bool HeapAllocGlobal::checkLeaks() { - ualni ignoredCount = 0; - for (auto iter = mEntry; iter; iter = iter->mPrev) { - ignoredCount += iter->mIgnored; - } - - // 1) Check for not deallocated memory - if (mNumAllocations && ignoredCount < mNumAllocations) { - - #ifdef MEM_STACK_TRACE - for (auto iter = mEntry; iter; iter = iter->mPrev) { - if (!iter->mIgnored) CallStackCapture::printSnapshot(iter->mCallStack); - } - #endif - - printf(" Count : %llu", mNumAllocations - ignoredCount); - - ASSERT(!"Destruction of not freed Allocator") - return true; - } - return false; -} - -void HeapAllocGlobal::startIgnore() { - mMutex.lock(); - mIgnore = true; - mMutex.unlock(); -} - -void HeapAllocGlobal::stopIgnore() { - mMutex.lock(); - mIgnore = false; - mMutex.unlock(); -} - -HeapAllocGlobal::~HeapAllocGlobal() = default; - -#endif - + + +#include "HeapAllocatorGlobal.hpp" +#include "PrivateConfig.hpp" + +#include "Debugging.hpp" +#include "Utils.hpp" + +#include +#include + +using namespace tp; + +#if not defined(MEM_DEBUG) + +// ----------------------- Release Implementation ---------------------------- // + +void* HeapAllocGlobal::allocate(ualni aBlockSize) { return malloc(aBlockSize); } +void HeapAllocGlobal::deallocate(void* aPtr) { free(aPtr); } +HeapAllocGlobal::~HeapAllocGlobal() = default; + +#else + +tp::MemHead* tp::HeapAllocGlobal::mEntry = nullptr; +tp::ualni tp::HeapAllocGlobal::mNumAllocations = 0; +tp::Mutex tp::HeapAllocGlobal::mMutex; +bool tp::HeapAllocGlobal::mIgnore; + +// ----------------------- Debug Implementation ---------------------------- // +// |----------------| +// | MemHead | +// |----------------| +// | wrap top | +// |----------------| - Allocated Block Layout +// | data | +// |----------------| +// | wrap bottom | +// |----------------| + +namespace tp { + struct MemHead { + MemHead* mPrev; + MemHead* mNext; + uhalni mBlockSize; + uhalni mIgnored; +#ifdef MEM_STACK_TRACE + const CallStackCapture::CallStack* mCallStack; +#endif + }; +} + +enum : ualni { + ALIGNED_SIZE = ENV_ALNI_SIZE_B, + WRAP_SIZE = MEM_WRAP_SIZE * ALIGNED_SIZE, + WRAP_VAL = MEM_WRAP_FILL_VAL, + HEAD_SIZE = sizeof(MemHead), + CLEAR_ALLOC_VAL = MEM_CLEAR_ON_ALLOC_VAL, + CLEAR_DEALLOC_VAL = MEM_CLEAR_ON_DEALLOC_VAL, +}; + +void* HeapAllocGlobal::allocate(ualni aBlockSize) { + + static_assert(HEAD_SIZE % ALIGNED_SIZE == 0, "Heap Allocator Configuration Error"); + + if (aBlockSize % ALIGNED_SIZE) { + aBlockSize = (aBlockSize / ALIGNED_SIZE + 1) * ALIGNED_SIZE; + } + +// 1) Allocate the block +ALLOCATE: + auto head = (MemHead*) malloc(aBlockSize + WRAP_SIZE * 2 + HEAD_SIZE); + if (!head) { + printf("WARNING : Cant allocate memory. Trying again\n"); + goto ALLOCATE; // Just freeze if no memory is available + } + + auto wrap_top = (int1*) (head + 1); + auto data = wrap_top + WRAP_SIZE; + auto wrap_bottom = data + aBlockSize; + + head->mBlockSize = aBlockSize; + head->mIgnored = mIgnore; + + // 2) Link with existing blocks + mMutex.lock(); + mNumAllocations++; + if (mEntry) { + DEBUG_ASSERT(mEntry->mNext == nullptr) + head->mNext = nullptr; + head->mPrev = mEntry; + mEntry->mNext = head; + } else { + head->mNext = nullptr; + head->mPrev = nullptr; + } + mEntry = head; + +// 3) Trace the stack +#ifdef MEM_STACK_TRACE + head->mCallStack = gCSCapture->getSnapshot(); +#endif + + mMutex.unlock(); + + // 4) Wrap fill + memSetVal(wrap_top, WRAP_SIZE, WRAP_VAL); + memSetVal(wrap_bottom, WRAP_SIZE, WRAP_VAL); + + // 5) clear data +#ifdef MEM_CLEAR_ON_ALLOC + memSetVal(data, aBlockSize, CLEAR_ALLOC_VAL); +#endif + + return data; +} + +void HeapAllocGlobal::deallocate(void* aPtr) { + if (!aPtr) return; + + // 1) Restore the pointers + auto head = ((MemHead*) ((int1*) aPtr - WRAP_SIZE)) - 1; + auto wrap_top = (int1*) (head + 1); + auto data = wrap_top + WRAP_SIZE; + auto wrap_bottom = data + head->mBlockSize; + + // 2) Unlink with blocks + mMutex.lock(); + mNumAllocations--; + DEBUG_ASSERT(!mEntry->mNext) + if (head->mNext) head->mNext->mPrev = head->mPrev; + if (head->mPrev) head->mPrev->mNext = head->mNext; + if (head == mEntry) { + mEntry = head->mPrev; + } + mMutex.unlock(); + + if (!head->mIgnored) { + // 3) Check the wrap + if (memCompareVal(wrap_top, WRAP_SIZE, WRAP_VAL)) { + CallStackCapture::printSnapshot(head->mCallStack); + ASSERT(!"Allocated Block Wrap Corrupted!") + } + + if (memCompareVal(wrap_bottom, WRAP_SIZE, WRAP_VAL)) { + CallStackCapture::printSnapshot(head->mCallStack); + ASSERT(!"Allocated Block Wrap Corrupted!") + } + +// 4) clear data +#ifdef MEM_CLEAR_ON_ALLOC + memSetVal(data, head->mBlockSize, CLEAR_DEALLOC_VAL); +#endif + } + + // 5) free the block + free(head); +} + +bool HeapAllocGlobal::checkLeaks() { + ualni ignoredCount = 0; + for (auto iter = mEntry; iter; iter = iter->mPrev) { + ignoredCount += iter->mIgnored; + } + + // 1) Check for not deallocated memory + if (mNumAllocations && ignoredCount < mNumAllocations) { + +#ifdef MEM_STACK_TRACE + for (auto iter = mEntry; iter; iter = iter->mPrev) { + if (!iter->mIgnored) CallStackCapture::printSnapshot(iter->mCallStack); + } +#endif + + printf(" Count : %llu", mNumAllocations - ignoredCount); + + ASSERT(!"Destruction of not freed Allocator") + return true; + } + return false; +} + +void HeapAllocGlobal::startIgnore() { + mMutex.lock(); + mIgnore = true; + mMutex.unlock(); +} + +void HeapAllocGlobal::stopIgnore() { + mMutex.lock(); + mIgnore = false; + mMutex.unlock(); +} + +HeapAllocGlobal::~HeapAllocGlobal() = default; + +#endif diff --git a/Allocators/public/Allocators.hpp b/Allocators/public/Allocators.hpp index 0283c52..ad29c25 100644 --- a/Allocators/public/Allocators.hpp +++ b/Allocators/public/Allocators.hpp @@ -2,9 +2,9 @@ #include "Utils.hpp" -#include "HeapAllocatorGlobal.hpp" -#include "HeapAllocator.hpp" #include "ChunkAllocator.hpp" +#include "HeapAllocator.hpp" +#include "HeapAllocatorGlobal.hpp" #include "PoolAllocator.hpp" namespace tp { @@ -13,15 +13,15 @@ namespace tp { void* operator new(std::size_t aSize); void* operator new[](std::size_t aSize); -void operator delete(void* aPtr) noexcept; -void operator delete[](void* aPtr) noexcept; +void operator delete(void* aPtr) noexcept; +void operator delete[](void* aPtr) noexcept; void* operator new(std::size_t aSize, tp::HeapAlloc& aAlloc); void* operator new[](std::size_t aSize, tp::HeapAlloc& aAlloc); -void operator delete(void* aPtr, tp::HeapAlloc& aAlloc); -void operator delete[](void* aPtr, tp::HeapAlloc& aAlloc); +void operator delete(void* aPtr, tp::HeapAlloc& aAlloc); +void operator delete[](void* aPtr, tp::HeapAlloc& aAlloc); void* operator new(std::size_t aSize, tp::HeapAllocGlobal& aAlloc); void* operator new[](std::size_t aSize, tp::HeapAllocGlobal& aAlloc); -void operator delete(void* aPtr, tp::HeapAllocGlobal& aAlloc); -void operator delete[](void* aPtr, tp::HeapAllocGlobal& aAlloc); \ No newline at end of file +void operator delete(void* aPtr, tp::HeapAllocGlobal& aAlloc); +void operator delete[](void* aPtr, tp::HeapAllocGlobal& aAlloc); \ No newline at end of file diff --git a/Allocators/public/ChunkAllocator.hpp b/Allocators/public/ChunkAllocator.hpp index 2f9e678..42f84e6 100644 --- a/Allocators/public/ChunkAllocator.hpp +++ b/Allocators/public/ChunkAllocator.hpp @@ -14,8 +14,8 @@ * 2) updating list entry to that block. */ -#include "HeapAllocatorGlobal.hpp" #include "Environment.hpp" +#include "HeapAllocatorGlobal.hpp" #include "PrivateConfig.hpp" namespace tp { @@ -23,7 +23,7 @@ namespace tp { // Chunk Allocator // Constant time allocations and de-allocations in any order. // Memory blocks are fixed in size and number of blocks can not exceed given parameter. - template + template class ChunkAlloc { enum : ualni { @@ -76,24 +76,24 @@ namespace tp { // 2) Find free block and update next free block auto data = mNextBlock; - mNextBlock = (ualni*)(*data); + mNextBlock = (ualni*) (*data); mNumFreeBlocks--; - #ifdef MEM_DEBUG - // 3) Fill Wrap and offset data - auto wrap_top = data; - auto wrap_bottom = data + WRAP_SIZE_ALN + dataSize(); +#ifdef MEM_DEBUG + // 3) Fill Wrap and offset data + auto wrap_top = data; + auto wrap_bottom = data + WRAP_SIZE_ALN + dataSize(); - memSetVal(wrap_top, WRAP_SIZE, WRAP_VAL); - memSetVal(wrap_bottom, WRAP_SIZE, WRAP_VAL); + memSetVal(wrap_top, WRAP_SIZE, WRAP_VAL); + memSetVal(wrap_bottom, WRAP_SIZE, WRAP_VAL); - // 4) Clear data - #ifdef MEM_CLEAR_ON_ALLOC - memSetVal(data + WRAP_SIZE_ALN, dataSize() * ALIGNED_SIZE, CLEAR_ALLOC_VAL); - #endif +// 4) Clear data +#ifdef MEM_CLEAR_ON_ALLOC + memSetVal(data + WRAP_SIZE_ALN, dataSize() * ALIGNED_SIZE, CLEAR_ALLOC_VAL); +#endif - data += WRAP_SIZE_ALN; - #endif + data += WRAP_SIZE_ALN; +#endif return data; } @@ -101,26 +101,26 @@ namespace tp { void deallocate(void* aPtr) { DEBUG_ASSERT(aPtr >= mBuff && aPtr < mBuff + tNumBlocks * blockSize()) - auto block = (ualni*)aPtr; + auto block = (ualni*) aPtr; - #ifdef MEM_DEBUG - // 3) Check Wrap and offset data - auto wrap_bottom = block + dataSize(); - auto wrap_top = block - WRAP_SIZE_ALN; - block = wrap_top; +#ifdef MEM_DEBUG + // 3) Check Wrap and offset data + auto wrap_bottom = block + dataSize(); + auto wrap_top = block - WRAP_SIZE_ALN; + block = wrap_top; - // 3) Check the wrap - ASSERT(!memCompareVal(wrap_top, WRAP_SIZE, WRAP_VAL) && "Allocated Block Wrap Corrupted!") - ASSERT(!memCompareVal(wrap_bottom, WRAP_SIZE, WRAP_VAL) && "Allocated Block Wrap Corrupted!") + // 3) Check the wrap + ASSERT(!memCompareVal(wrap_top, WRAP_SIZE, WRAP_VAL) && "Allocated Block Wrap Corrupted!") + ASSERT(!memCompareVal(wrap_bottom, WRAP_SIZE, WRAP_VAL) && "Allocated Block Wrap Corrupted!") - // 4) Clear data - #ifdef MEM_CLEAR_ON_ALLOC - memSetVal(block, blockSize() * ALIGNED_SIZE, CLEAR_DEALLOC_VAL); - #endif +// 4) Clear data +#ifdef MEM_CLEAR_ON_ALLOC + memSetVal(block, blockSize() * ALIGNED_SIZE, CLEAR_DEALLOC_VAL); +#endif - #endif +#endif - (*block) = (ualni)mNextBlock; + (*block) = (ualni) mNextBlock; mNextBlock = block; mNumFreeBlocks++; } diff --git a/Allocators/public/PoolAllocator.hpp b/Allocators/public/PoolAllocator.hpp index 98f1596..40b1c1b 100644 --- a/Allocators/public/PoolAllocator.hpp +++ b/Allocators/public/PoolAllocator.hpp @@ -21,14 +21,14 @@ namespace tp { // Pool Allocator // Overcomes chunk allocator fixed number of max allocations - template + template class PoolAlloc { typedef ChunkAlloc Chunk; struct Chunks { - void add(Chunk* aChunk){ + void add(Chunk* aChunk) { if (!mBuff) { mLen = 16; @@ -57,7 +57,7 @@ namespace tp { } } - void remove(Chunk** del_address){ + void remove(Chunk** del_address) { if (mUsedLen == 1) { mLen = 0; mUsedLen = 0; @@ -74,18 +74,16 @@ namespace tp { mUsedLen--; // check for buff low usage - if ((halnf)mUsedLen / (halnf)mLen < 0.25f) { + if ((halnf) mUsedLen / (halnf) mLen < 0.25f) { auto prevBuff = mBuff; - mBuff = (Chunk**)HeapAllocGlobal::allocate(sizeof(Chunk*) * mLen / 2); + mBuff = (Chunk**) HeapAllocGlobal::allocate(sizeof(Chunk*) * mLen / 2); memCopy(mBuff, prevBuff, sizeof(Chunk*) * mUsedLen); mLen /= 2; HeapAllocGlobal::deallocate(prevBuff); } } - [[nodiscard]] Chunk** find(void* aPtr) { - return findUtil(mBuff, mBuff + mUsedLen, aPtr) - 1; - } + [[nodiscard]] Chunk** find(void* aPtr) { return findUtil(mBuff, mBuff + mUsedLen, aPtr) - 1; } [[nodiscard]] Chunk* findNotFull() const { for (ualni idx = 0; idx < mUsedLen; idx++) { @@ -137,9 +135,9 @@ namespace tp { auto chunk = mChunks.find(aPtr); (*chunk)->deallocate(aPtr); if ((*chunk)->isEmpty()) { - if (mFreeChunk == *chunk) mFreeChunk = nullptr; - HeapAllocGlobal::deallocate(*chunk); - mChunks.remove(chunk); + if (mFreeChunk == *chunk) mFreeChunk = nullptr; + HeapAllocGlobal::deallocate(*chunk); + mChunks.remove(chunk); } } @@ -153,7 +151,7 @@ namespace tp { if (i > j) { ASSERT(mChunks.mBuff[i] > mChunks.mBuff[j]) } else if (i < j) { - ASSERT(mChunks.mBuff[i] < mChunks.mBuff[j]) + ASSERT(mChunks.mBuff[i] < mChunks.mBuff[j]) } } } diff --git a/Allocators/tests/Tests.cpp b/Allocators/tests/Tests.cpp index 760d6c5..30c82c4 100644 --- a/Allocators/tests/Tests.cpp +++ b/Allocators/tests/Tests.cpp @@ -1,20 +1,20 @@ - -#include "Allocators.hpp" - -#include "Tests.hpp" - -using namespace tp; - -int main() { - - tp::ModuleManifest* deps[] = { &tp::gModuleAllocators, &tp::gModuleUtils, nullptr }; - tp::ModuleManifest testModule("AllocatorsTest", nullptr, nullptr, deps); - - if (!testModule.initialize()) { - return 1; - } - - testAll(); - - testModule.deinitialize(); -} + +#include "Allocators.hpp" + +#include "Tests.hpp" + +using namespace tp; + +int main() { + + tp::ModuleManifest* deps[] = { &tp::gModuleAllocators, &tp::gModuleUtils, nullptr }; + tp::ModuleManifest testModule("AllocatorsTest", nullptr, nullptr, deps); + + if (!testModule.initialize()) { + return 1; + } + + testAll(); + + testModule.deinitialize(); +} diff --git a/Allocators/tests/Tests.hpp b/Allocators/tests/Tests.hpp index 8345a9d..da63303 100644 --- a/Allocators/tests/Tests.hpp +++ b/Allocators/tests/Tests.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Utils.hpp" #include "Testing.hpp" +#include "Utils.hpp" void testAll(); \ No newline at end of file diff --git a/Allocators/tests/TestsAll.cpp b/Allocators/tests/TestsAll.cpp index cb90f78..e098fa7 100644 --- a/Allocators/tests/TestsAll.cpp +++ b/Allocators/tests/TestsAll.cpp @@ -1,248 +1,245 @@ - -#include "Utils.hpp" -#include "Testing.hpp" - -#include "HeapAllocatorGlobal.hpp" -#include "HeapAllocator.hpp" -#include "ChunkAllocator.hpp" -#include "PoolAllocator.hpp" - -#include - -using namespace tp; - -struct TestStruct { - alni val = 0; - - TestStruct() : val(0) {} - explicit TestStruct(alni val) : val(val) {} - TestStruct(const TestStruct& in) : val(in.val) {} - - ~TestStruct() { val = -1; } - - bool operator==(const TestStruct& in) const { - return in.val == val; - } -}; - -template -class TestBenches { - - tAllocator mAlloc{}; - TestStruct mData[tSize]{}; - TestStruct* mLoaded[tSize]{}; - bool mIsLoaded[tSize]{}; - alni mLoadedNum = 0; - -public: - TestBenches() { - for (alni i = 0; i < tSize; i++) { - mData[i].val = i; - mIsLoaded[i] = false; - mLoaded[i] = nullptr; - } - } - - void runTests() { - try { - test1(); - test2(); - test3(); - test4(); - test5(); - test6(); - } catch (...) { - ASSERT(false) - } - } - -private: - alni randomIdx(bool state, Range range = { 0, tSize }) { - RAND: - auto idx = alni(alnf(range.idxBegin()) + randomFloat() * alnf(range.idxDiff() + 1)); - idx = clamp(idx, alni(0), tSize - 1); - if (state == mIsLoaded[idx]) goto RAND; - return idx; - } - - void verifyIntegrity() { - mAlloc.checkValid(); - ASSERT(!mAlloc.checkWrap()) - for (alni i = 0; i < tSize; i++) { - if (mIsLoaded[i]) { - ASSERT(*mLoaded[i] == mData[i]) - } - } - } - - void loadItem(alni idx) { - if (mIsLoaded[idx]) return; - verifyIntegrity(); - mLoaded[idx] = new (mAlloc.allocate(sizeof(TestStruct))) TestStruct(mData[idx]); - TEST(mLoaded[idx]); - mIsLoaded[idx] = true; - mLoadedNum++; - verifyIntegrity(); - } - - void unloadItem(alni idx) { - if (!mIsLoaded[idx]) return; - verifyIntegrity(); - mLoaded[idx]->~TestStruct(); - mAlloc.deallocate(mLoaded[idx]); - mIsLoaded[idx] = false; - mLoadedNum--; - verifyIntegrity(); - } - - void changeStates(Range rg, bool load, bool reversed = false, bool random = false) { - for (auto i : rg) { - alni idx = i; - if (random) { - idx = randomIdx(load, rg); - } else if (reversed) { - idx = rg.idxEnd() - i - 1; - } - (load) ? loadItem(idx) : unloadItem(idx); - } - } - - // full down-up load then up-down unload - void test1() { - changeStates({ 0, tSize }, true); - changeStates({ 0, tSize }, false, true); - } - - // full down-up load then down-up unload - void test2() { - changeStates({0, tSize}, true); - changeStates({0, tSize}, false); - } - - // full random load then random unload - void test3() { - changeStates({0, tSize}, true, false, true); - changeStates({0, tSize}, false, false, true); - } - - // combo tests 1-3 - void test4() { - test1(); - test1(); - - test2(); - test2(); - - test3(); - test3(); - } - - static alnf sineUpFunction(alnf aSize, alnf aX, bool aReverse) { - alnf end = 4 * 3.14159; - alnf a = (2 / 7.f) * aSize; - alnf b = end / aSize; - - alni c = ((-1 * aReverse) + (1 * !aReverse)); - alnf c1 = (aX - (end * aReverse)) / b; - alnf c2 = (a * sin(aX - (end * aReverse))); - alnf out = c1 + c2; - return (alnf) c * out; - } - - // sin load & sin unload with ~1/2 drop factor - void test5() { - alnf end = 4 * 3.14159; - alnf step = end / 4.f; - - for (char i = 0; i < 2; i++) { - for (alnf x = 0; x <= end; x += step) { - - alni target_alloc_count = (alni) ceil(sineUpFunction(tSize, x, i)); - target_alloc_count = clamp(target_alloc_count, alni(0), tSize); - - while (mLoadedNum > target_alloc_count) { - unloadItem(randomIdx(0)); - } - while (mLoadedNum < target_alloc_count) { - loadItem(randomIdx(1)); - } - } - } - } - - void checkWrap(ualni offset, bool after) { - offset = clamp(offset, (ualni) 1, (ualni) MEM_WRAP_SIZE); - - TestStruct* ts = mLoaded[randomIdx(0)]; - ualni shift = (sizeof(TestStruct) * after) + (offset - 1) * after - offset * (!after); - uint1* address = (((uint1*)ts) + shift); - - uint1 val = *address; - *address = 5; - - TEST(!mAlloc.checkWrap()); - - *address = val; - } - - // mem guards test - void test6() { - changeStates({0, tSize}, 1); - #ifdef MEM_DEBUG - for (alni after = 0; after < 2; after++) { - for (alni offset = 1; offset <= MEM_WRAP_SIZE; offset++) { - checkWrap(offset, after); - } - } - #endif - changeStates({0, tSize}, 0); - } -}; - -const ualni size = 1000; - -template -void testAlloc() { - try { - TestBenches heapTests{}; - heapTests.runTests(); - } catch (...) { - TEST(false); - } -} - -TEST_DEF_STATIC(GlobalHeap) { - testAlloc(); -} - -TEST_DEF_STATIC(Heap) { - testAlloc(); -} - -TEST_DEF_STATIC(Chunk) { - testAlloc>(); - testAlloc>(); -} - -TEST_DEF_STATIC(Pool) { - testAlloc>(); - testAlloc>(); - testAlloc>(); -} - -TEST_DEF_STATIC(Simple) { - auto a = new TestStruct(-1); - delete a; -} - -TEST_DEF(All) { - testSimple(); - - testGlobalHeap(); - testHeap(); - testChunk(); - testPool(); - - // TEST(HeapAllocGlobal::checkLeaks()); - // TEST(false); + +#include "Testing.hpp" +#include "Utils.hpp" + +#include "ChunkAllocator.hpp" +#include "HeapAllocator.hpp" +#include "HeapAllocatorGlobal.hpp" +#include "PoolAllocator.hpp" + +#include + +using namespace tp; + +struct TestStruct { + alni val = 0; + + TestStruct() : + val(0) {} + explicit TestStruct(alni val) : + val(val) {} + TestStruct(const TestStruct& in) : + val(in.val) {} + + ~TestStruct() { val = -1; } + + bool operator==(const TestStruct& in) const { return in.val == val; } +}; + +template +class TestBenches { + + tAllocator mAlloc{}; + TestStruct mData[tSize]{}; + TestStruct* mLoaded[tSize]{}; + bool mIsLoaded[tSize]{}; + alni mLoadedNum = 0; + +public: + TestBenches() { + for (alni i = 0; i < tSize; i++) { + mData[i].val = i; + mIsLoaded[i] = false; + mLoaded[i] = nullptr; + } + } + + void runTests() { + try { + test1(); + test2(); + test3(); + test4(); + test5(); + test6(); + } catch (...) { + ASSERT(false) + } + } + +private: + alni randomIdx(bool state, Range range = { 0, tSize }) { + RAND: + auto idx = alni(alnf(range.idxBegin()) + randomFloat() * alnf(range.idxDiff() + 1)); + idx = clamp(idx, alni(0), tSize - 1); + if (state == mIsLoaded[idx]) goto RAND; + return idx; + } + + void verifyIntegrity() { + mAlloc.checkValid(); + ASSERT(!mAlloc.checkWrap()) + for (alni i = 0; i < tSize; i++) { + if (mIsLoaded[i]) { + ASSERT(*mLoaded[i] == mData[i]) + } + } + } + + void loadItem(alni idx) { + if (mIsLoaded[idx]) return; + verifyIntegrity(); + mLoaded[idx] = new (mAlloc.allocate(sizeof(TestStruct))) TestStruct(mData[idx]); + TEST(mLoaded[idx]); + mIsLoaded[idx] = true; + mLoadedNum++; + verifyIntegrity(); + } + + void unloadItem(alni idx) { + if (!mIsLoaded[idx]) return; + verifyIntegrity(); + mLoaded[idx]->~TestStruct(); + mAlloc.deallocate(mLoaded[idx]); + mIsLoaded[idx] = false; + mLoadedNum--; + verifyIntegrity(); + } + + void changeStates(Range rg, bool load, bool reversed = false, bool random = false) { + for (auto i : rg) { + alni idx = i; + if (random) { + idx = randomIdx(load, rg); + } else if (reversed) { + idx = rg.idxEnd() - i - 1; + } + (load) ? loadItem(idx) : unloadItem(idx); + } + } + + // full down-up load then up-down unload + void test1() { + changeStates({ 0, tSize }, true); + changeStates({ 0, tSize }, false, true); + } + + // full down-up load then down-up unload + void test2() { + changeStates({ 0, tSize }, true); + changeStates({ 0, tSize }, false); + } + + // full random load then random unload + void test3() { + changeStates({ 0, tSize }, true, false, true); + changeStates({ 0, tSize }, false, false, true); + } + + // combo tests 1-3 + void test4() { + test1(); + test1(); + + test2(); + test2(); + + test3(); + test3(); + } + + static alnf sineUpFunction(alnf aSize, alnf aX, bool aReverse) { + alnf end = 4 * 3.14159; + alnf a = (2 / 7.f) * aSize; + alnf b = end / aSize; + + alni c = ((-1 * aReverse) + (1 * !aReverse)); + alnf c1 = (aX - (end * aReverse)) / b; + alnf c2 = (a * sin(aX - (end * aReverse))); + alnf out = c1 + c2; + return (alnf) c * out; + } + + // sin load & sin unload with ~1/2 drop factor + void test5() { + alnf end = 4 * 3.14159; + alnf step = end / 4.f; + + for (char i = 0; i < 2; i++) { + for (alnf x = 0; x <= end; x += step) { + + alni target_alloc_count = (alni) ceil(sineUpFunction(tSize, x, i)); + target_alloc_count = clamp(target_alloc_count, alni(0), tSize); + + while (mLoadedNum > target_alloc_count) { + unloadItem(randomIdx(0)); + } + while (mLoadedNum < target_alloc_count) { + loadItem(randomIdx(1)); + } + } + } + } + + void checkWrap(ualni offset, bool after) { + offset = clamp(offset, (ualni) 1, (ualni) MEM_WRAP_SIZE); + + TestStruct* ts = mLoaded[randomIdx(0)]; + ualni shift = (sizeof(TestStruct) * after) + (offset - 1) * after - offset * (!after); + uint1* address = (((uint1*) ts) + shift); + + uint1 val = *address; + *address = 5; + + TEST(!mAlloc.checkWrap()); + + *address = val; + } + + // mem guards test + void test6() { + changeStates({ 0, tSize }, 1); +#ifdef MEM_DEBUG + for (alni after = 0; after < 2; after++) { + for (alni offset = 1; offset <= MEM_WRAP_SIZE; offset++) { + checkWrap(offset, after); + } + } +#endif + changeStates({ 0, tSize }, 0); + } +}; + +const ualni size = 1000; + +template +void testAlloc() { + try { + TestBenches heapTests{}; + heapTests.runTests(); + } catch (...) { + TEST(false); + } +} + +TEST_DEF_STATIC(GlobalHeap) { testAlloc(); } + +TEST_DEF_STATIC(Heap) { testAlloc(); } + +TEST_DEF_STATIC(Chunk) { + testAlloc>(); + testAlloc>(); +} + +TEST_DEF_STATIC(Pool) { + testAlloc>(); + testAlloc>(); + testAlloc>(); +} + +TEST_DEF_STATIC(Simple) { + auto a = new TestStruct(-1); + delete a; +} + +TEST_DEF(All) { + testSimple(); + + testGlobalHeap(); + testHeap(); + testChunk(); + testPool(); + + // TEST(HeapAllocGlobal::checkLeaks()); + // TEST(false); } \ No newline at end of file diff --git a/CommandLine/private/CmdLineInterpreter.cpp b/CommandLine/private/CmdLineInterpreter.cpp index e7b6cca..3d31ad6 100644 --- a/CommandLine/private/CmdLineInterpreter.cpp +++ b/CommandLine/private/CmdLineInterpreter.cpp @@ -38,14 +38,11 @@ void CmdLineInterpreter::help(const CommandLine& args) const { } CmdLineInterpreter::CmdLineInterpreter() { - auto helpArgs = new CommandLine{ - { "CommandName", "_none_" } - }; + auto helpArgs = new CommandLine{ { "CommandName", "_none_" } }; addCommand("help", helpArgs, (CommandFunction) helpFunction, this); } - void CmdLineInterpreter::addCommand(const String& id, CommandLine* args, CommandFunction function, void* customData) { ASSERT(!mCommands.presents(id)) mCommands.put(id, { args, function, customData }); diff --git a/CommandLine/private/CommandLine.cpp b/CommandLine/private/CommandLine.cpp index a7172b7..dd112b1 100644 --- a/CommandLine/private/CommandLine.cpp +++ b/CommandLine/private/CommandLine.cpp @@ -1,412 +1,466 @@ -#include "NewPlacement.hpp" - -#include "CommandLine.hpp" - -using namespace tp; - -static ModuleManifest* sModuleDependencies[] = { &gModuleTokenizer, &gModuleConnection, nullptr }; -ModuleManifest tp::gModuleCommandLine = ModuleManifest("CommandLine", nullptr, nullptr, sModuleDependencies); - -const char* regexSpace = "\n|\t| |\r"; -const char* regexFalse = "N|n|(False)|(false)"; -const char* regexTrue = "Y|y|(True)|(true)"; -const char* regexInt = "((\\-)|(\\+))?[0-9]+"; -const char* regexFloat = R"(((\-)|(\+))?([0-9]+)(\.)([0-9]*)?)"; -const char* regexString = "'{'-'}*'"; - -CommandLine::Arg::Arg(const Arg& arg) { - mId = arg.mId; - switch (arg.mType) { - case CommandLine::Arg::INT: mType = INT; mInt = arg.mInt; break; - case CommandLine::Arg::FLOAT: mType = FLOAT; mFloat = arg.mFloat; break; - case CommandLine::Arg::BOOL: mType = BOOL; mBool = arg.mBool; break; - case CommandLine::Arg::STR: mType = STR; new (&mStr) StringArg(); mStr = arg.mStr; break; - case CommandLine::Arg::FILE_IN: mType = FILE_IN; new (&mFile) FileInputArg(); mFile = arg.mFile; break; - default: - ASSERT(false) - } - mOptional = arg.mOptional; -} - -CommandLine::Arg::Arg(const String& id, Type type) { - mId = id; - switch (type) { - case CommandLine::Arg::INT: mType = INT; new (&mInt) IntArg(); break; - case CommandLine::Arg::FLOAT: mType = FLOAT; new (&mFloat) FloatArg(); break; - case CommandLine::Arg::BOOL: mType = BOOL; new (&mBool) BoolArg(); break; - case CommandLine::Arg::STR: mType = STR; new (&mStr) StringArg(); break; - case CommandLine::Arg::FILE_IN: mType = FILE_IN; new (&mFile) FileInputArg(); break; - default: ASSERT(false) - } - mOptional = false; -} - -CommandLine::Arg::Arg(const String& id, const Range& aAcceptingRange) { - mId = id; - mType = FLOAT; - mInt = { 0, 0, aAcceptingRange }; - mOptional = false; -} - -CommandLine::Arg::Arg(const String& id, const Range& aAcceptingRange) { - mId = id; - mType = FLOAT; - mFloat = { 0, 0, aAcceptingRange }; - mOptional = false; -} - -CommandLine::Arg::Arg(const String& id, const Range& aAcceptingRange, alni aDefault) { - mId = id; - mType = INT; - mInt = { 0, aDefault, aAcceptingRange }; -} - -CommandLine::Arg::Arg(const String& id, const Range& aAcceptingRange, alnf aDefault) { - mId = id; - mType = FLOAT; - mFloat = { 0, aDefault, aAcceptingRange }; -} - -CommandLine::Arg::Arg(const String& id, bool aDefault) { - mId = id; - mType = BOOL; - mBool.mDefault = aDefault; -} - -CommandLine::Arg::Arg(const String& id, const char* aDefault) { - mId = id; - mType = STR; - new (&mStr) StringArg(); - mStr.mDefault = aDefault; -} - -CommandLine::Arg::~Arg() { - switch (mType) { - case CommandLine::Arg::STR: - mStr.~StringArg(); - break; - case CommandLine::Arg::FILE_IN: - mFile.~FileInputArg(); - break; - default: - break; - } -} - -CommandLine::CommandLine(const InitialierList& args) { - bool optional_start = false; - - for (auto& arg : args) { - ASSERT(!mArgs.presents(arg.mId) && "Argument Redefinition") - - auto copy_arg = new Arg(arg); - - mArgs.put(arg.mId, copy_arg); - mArgsOrder.pushBack(mArgs.get(arg.mId)); - - if (arg.mOptional) { - mOptionals++; - } - - if (optional_start) { - ASSERT(arg.mOptional && "Not Optional Argument After Optionals") - } - else if (arg.mOptional) { - optional_start = true; - } - } - - mTokenizer.build({ - { regexSpace, TokType::SPACE }, - { regexFalse, TokType::BOOL_FALSE }, - { regexTrue, TokType::BOOL_TRUE }, - { regexInt, TokType::INT }, - { regexFloat, TokType::FLOAT }, - { regexString, TokType::STR }, - }); - - ASSERT(mTokenizer.isBuild() && "Internal Error") - - mArgumentTokenizer.build({ - { regexSpace, ArgTokType::SPACE }, - { "{ - }*", ArgTokType::ARG } - }); - - ASSERT(mTokenizer.isBuild() && "Internal Error") -} - -CommandLine::~CommandLine() { - for (auto arg : mArgsOrder) { - delete arg.data(); - } -} - -bool CommandLine::parse(char argc, const char* argv[], bool logError, ualni skipArgs) { - // discard some arguments - argc -= (char) skipArgs; - argv += skipArgs; - - if (argc < mArgs.size() - mOptionals) { - ErrInvalidArgCount(); - if (logError) { - ErrLog(); - } - return false; - } - - ualni idx = 0; - for (auto arg : mArgsOrder) { - if (idx < argc) { - parseArg(*arg.data(), argv[idx]); - } else { - initDefault(*arg.data()); - } - if (mError) { - if (logError) ErrLog(); - return false; - } - idx++; - } - return true; -} - -bool CommandLine::parse(const char* args, bool logError) { - mArgumentTokenizer.bindSource(args); - mArgumentTokenizer.reset(); - - ualni argc = 0; - auto tok = mArgumentTokenizer.readTok(); - auto argument = mArgsOrder.first(); - - while (tok != ArgTokType::FAILURE && tok != ArgTokType::END) { - if (tok != ArgTokType::ARG) { - tok = mArgumentTokenizer.readTok(); - continue; - } - - if (!argument) { - ErrInvalidArgCount(); - if (logError) ErrLog(); - return false; - } - - parseArg(*argument->data, mArgumentTokenizer.extractVal().read()); - - if (mError && logError) { - ErrLog(); - return false; - } - - argc++; - argument = argument->next; - tok = mArgumentTokenizer.readTok(); - } - - ualni idx = 0; - for (auto arg : mArgsOrder) { - if (idx >= argc) { - initDefault(*arg.data()); - } - if (mError) { - if (logError) ErrLog(); - return false; - } - idx++; - } - return true; -} - -alni CommandLine::getInt(const String& id) const { auto& arg = getArg(id, Arg::INT); return arg.mInt.mVal; } -alnf CommandLine::getFloat(const String& id) const { auto& arg = getArg(id, Arg::FLOAT); return arg.mFloat.mVal; } -bool CommandLine::getBool(const String& id) const { auto& arg = getArg(id, Arg::BOOL); return arg.mBool.mFlag; } -const String& CommandLine::getString(const String& id) const { auto& arg = getArg(id, Arg::STR); return arg.mStr.mStr; } -const LocalConnection::Location& CommandLine::getFile(const String& id) const { auto& arg = getArg(id, Arg::FILE_IN); return arg.mFile.mFileLocation; } - - -CommandLine::Arg& CommandLine::getArg(const String& id, Arg::Type type) { - auto idx = mArgs.presents(id); - ASSERT(idx && "Invalid Id") - auto& arg = mArgs.getSlotVal(idx); - ASSERT(arg->mType == type && "Invalid Type Requested") - return *arg; -} - -const CommandLine::Arg& CommandLine::getArg(const String& id, Arg::Type type) const { - auto idx = mArgs.presents(id); - ASSERT(idx && "Invalid Id") - auto& arg = mArgs.getSlotVal(idx); - ASSERT(arg->mType == type && "Invalid Type Requested") - return *arg; -} - -void CommandLine::ErrInvalidArgCount() { mError = { "Invalid Number Of Arguments Passed", nullptr }; } -void CommandLine::ErrInvalidArgSyntax(Arg* arg) { mError = { "Invalid Syntax Of Argument", arg }; } -void CommandLine::ErrInvalidArgType(Arg* arg) { mError = { "Invalid Type Of Argument", arg }; } -void CommandLine::ErrFileNotExists(Arg* arg) { mError = { "File Not Exists", arg }; } -void CommandLine::ErrFileCouldNotOpen(Arg* arg) { mError = { "Could Not Open File", arg }; } -void CommandLine::ErrValNotinRange(Arg* arg) { mError = { "Value Not In Range", arg }; } - -void CommandLine::ErrLog() { - printf("\nERROR : Invalid Command Line\n"); - - if (mError.mArg) { - alni idx = 0; - for (auto arg : mArgsOrder) { - if (mError.mArg == arg.data()) break; - idx++; - } - - printf("\nArgument: %lli\n", idx); - logArg(*mError.mArg); - } - - printf("Error Description: %s. \n", mError.mDescr); - - printf("\nExpected Arguments are: \n"); - ualni idx = 0; - for (auto arg : mArgsOrder) { - printf(" -- %lli -- \n", idx); - logArg(*arg.data()); - idx++; - } - - printf("\nNote regex for types are:\n"); - printf(" False - %s\n", regexFalse); - printf(" True - %s\n", regexTrue); - printf(" Int - %s\n", regexInt); - printf(" Float - %s\n", regexFloat); - printf(" String - %s\n", regexString); - printf(" File - else\n"); -} - -void CommandLine::logArg(const Arg& arg) { - switch (arg.mType) { - case Arg::INT: { - printf("Type : Int\n"); - printf("Range : %lli - %lli\n", arg.mInt.mAcceptingRange.mBegin, arg.mInt.mAcceptingRange.mEnd); - if (arg.mOptional) { - printf("Default : %lli\n", arg.mInt.mDefault); - } - printf("Value : %lli\n", arg.mInt.mVal); - } break; - case Arg::FLOAT: { - printf("Type : Float\n"); - printf("Range : %f - %f\n", (halnf) arg.mFloat.mAcceptingRange.mBegin, (halnf) arg.mFloat.mAcceptingRange.mEnd); - if (arg.mOptional) { - printf("Default : %f\n", arg.mFloat.mDefault); - } - printf("Value : %f\n", arg.mFloat.mVal); - } break; - case Arg::BOOL: { - printf("Type : Bool\n"); - if (arg.mOptional) { - printf("Default : %s\n", arg.mBool.mDefault ? "True" : "False"); - } - printf("Value : %s\n", arg.mBool.mFlag ? "True" : "False"); - } break; - case Arg::STR: { - printf("Type : String\n"); - if (arg.mOptional) { - printf("Default : %s\n", arg.mStr.mDefault.read()); - } - printf("Value : %s\n", arg.mStr.mStr.read()); - } break; - case Arg::FILE_IN: { - printf("Type : File Input\n"); - printf("Value Path : %s\n", arg.mFile.mFileLocation.getLocation().read()); - } break; - default: ASSERT(false) - } -} - -void CommandLine::initDefault(Arg& arg) { - switch (arg.mType) { - case Arg::INT: arg.mInt.mVal = arg.mInt.mDefault; break; - case Arg::FLOAT: arg.mFloat.mVal = arg.mFloat.mDefault; break; - case Arg::BOOL: arg.mBool.mFlag = arg.mBool.mDefault; break; - case Arg::STR: arg.mStr.mStr = arg.mStr.mDefault; break; - default: - break; - } -} - -void CommandLine::parseArg(Arg& arg, const char* src) { - mTokenizer.reset(); - mTokenizer.bindSource(src); - - auto tok = mTokenizer.readTok(); - if (tok < TokType::INT || tok > TokType::STR) { - ErrInvalidArgSyntax(&arg); - return; - } - - auto val = mTokenizer.extractVal(); - - switch (arg.mType) { - case Arg::INT: { - if (tok != TokType::INT) { - ErrInvalidArgType(&arg); - return; - } - auto converted = String::Logic::convertStringToValue(val.read(), arg.mInt.mVal); - if (converted && arg.mInt.mVal < arg.mInt.mAcceptingRange.mBegin || arg.mInt.mVal > arg.mInt.mAcceptingRange.mEnd) { - ErrValNotinRange(&arg); - return; - } - } break; - - case Arg::FLOAT: { - if (tok != TokType::FLOAT) { - ErrInvalidArgType(&arg); - return; - } - auto converted = String::Logic::convertStringToValue(val.read(), arg.mFloat.mVal); - if (converted && arg.mFloat.mVal < arg.mFloat.mAcceptingRange.mBegin || arg.mFloat.mVal > arg.mFloat.mAcceptingRange.mEnd) { - ErrValNotinRange(&arg); - return; - } - } break; - - case Arg::STR: { - if (tok != TokType::STR) { - ErrInvalidArgType(&arg); - return; - } - arg.mStr.mStr.resize(val.size() - 2); - memCopy(arg.mStr.mStr.write(), val.read() + 1, val.size() - 2); - } break; - - case Arg::BOOL: { - if (tok != TokType::BOOL_FALSE && tok != TokType::BOOL_TRUE) { - ErrInvalidArgType(&arg); - return; - } - arg.mBool.mFlag = tok == TokType::BOOL_TRUE; - } break; - - case Arg::FILE_IN: { - if (tok != TokType::STR) { - ErrInvalidArgType(&arg); - return; - } - - arg.mFile.mFileLocation.setLocation(val); - - if (!arg.mFile.mFileLocation.exists()) { - ErrFileNotExists(&arg); - return; - } - - } break; - default: ASSERT(false) - } - - arg.mIsPassed = true; -} - -void CommandLine::help() const { - printf("Arguments:\n"); - for (auto arg : mArgsOrder) { - logArg(*arg.data()); - } +#include "NewPlacement.hpp" + +#include "CommandLine.hpp" + +using namespace tp; + +static ModuleManifest* sModuleDependencies[] = { &gModuleTokenizer, &gModuleConnection, nullptr }; +ModuleManifest tp::gModuleCommandLine = ModuleManifest("CommandLine", nullptr, nullptr, sModuleDependencies); + +const char* regexSpace = "\n|\t| |\r"; +const char* regexFalse = "N|n|(False)|(false)"; +const char* regexTrue = "Y|y|(True)|(true)"; +const char* regexInt = "((\\-)|(\\+))?[0-9]+"; +const char* regexFloat = R"(((\-)|(\+))?([0-9]+)(\.)([0-9]*)?)"; +const char* regexString = "'{'-'}*'"; + +CommandLine::Arg::Arg(const Arg& arg) { + mId = arg.mId; + switch (arg.mType) { + case CommandLine::Arg::INT: + mType = INT; + mInt = arg.mInt; + break; + case CommandLine::Arg::FLOAT: + mType = FLOAT; + mFloat = arg.mFloat; + break; + case CommandLine::Arg::BOOL: + mType = BOOL; + mBool = arg.mBool; + break; + case CommandLine::Arg::STR: + mType = STR; + new (&mStr) StringArg(); + mStr = arg.mStr; + break; + case CommandLine::Arg::FILE_IN: + mType = FILE_IN; + new (&mFile) FileInputArg(); + mFile = arg.mFile; + break; + default: ASSERT(false) + } + mOptional = arg.mOptional; +} + +CommandLine::Arg::Arg(const String& id, Type type) { + mId = id; + switch (type) { + case CommandLine::Arg::INT: + mType = INT; + new (&mInt) IntArg(); + break; + case CommandLine::Arg::FLOAT: + mType = FLOAT; + new (&mFloat) FloatArg(); + break; + case CommandLine::Arg::BOOL: + mType = BOOL; + new (&mBool) BoolArg(); + break; + case CommandLine::Arg::STR: + mType = STR; + new (&mStr) StringArg(); + break; + case CommandLine::Arg::FILE_IN: + mType = FILE_IN; + new (&mFile) FileInputArg(); + break; + default: ASSERT(false) + } + mOptional = false; +} + +CommandLine::Arg::Arg(const String& id, const Range& aAcceptingRange) { + mId = id; + mType = FLOAT; + mInt = { 0, 0, aAcceptingRange }; + mOptional = false; +} + +CommandLine::Arg::Arg(const String& id, const Range& aAcceptingRange) { + mId = id; + mType = FLOAT; + mFloat = { 0, 0, aAcceptingRange }; + mOptional = false; +} + +CommandLine::Arg::Arg(const String& id, const Range& aAcceptingRange, alni aDefault) { + mId = id; + mType = INT; + mInt = { 0, aDefault, aAcceptingRange }; +} + +CommandLine::Arg::Arg(const String& id, const Range& aAcceptingRange, alnf aDefault) { + mId = id; + mType = FLOAT; + mFloat = { 0, aDefault, aAcceptingRange }; +} + +CommandLine::Arg::Arg(const String& id, bool aDefault) { + mId = id; + mType = BOOL; + mBool.mDefault = aDefault; +} + +CommandLine::Arg::Arg(const String& id, const char* aDefault) { + mId = id; + mType = STR; + new (&mStr) StringArg(); + mStr.mDefault = aDefault; +} + +CommandLine::Arg::~Arg() { + switch (mType) { + case CommandLine::Arg::STR: mStr.~StringArg(); break; + case CommandLine::Arg::FILE_IN: mFile.~FileInputArg(); break; + default: break; + } +} + +CommandLine::CommandLine(const InitialierList& args) { + bool optional_start = false; + + for (auto& arg : args) { + ASSERT(!mArgs.presents(arg.mId) && "Argument Redefinition") + + auto copy_arg = new Arg(arg); + + mArgs.put(arg.mId, copy_arg); + mArgsOrder.pushBack(mArgs.get(arg.mId)); + + if (arg.mOptional) { + mOptionals++; + } + + if (optional_start) { + ASSERT(arg.mOptional && "Not Optional Argument After Optionals") + } else if (arg.mOptional) { + optional_start = true; + } + } + + mTokenizer.build({ + { regexSpace, TokType::SPACE }, + { regexFalse, TokType::BOOL_FALSE }, + { regexTrue, TokType::BOOL_TRUE }, + { regexInt, TokType::INT }, + { regexFloat, TokType::FLOAT }, + { regexString, TokType::STR }, + }); + + ASSERT(mTokenizer.isBuild() && "Internal Error") + + mArgumentTokenizer.build({ { regexSpace, ArgTokType::SPACE }, { "{ - }*", ArgTokType::ARG } }); + + ASSERT(mTokenizer.isBuild() && "Internal Error") +} + +CommandLine::~CommandLine() { + for (auto arg : mArgsOrder) { + delete arg.data(); + } +} + +bool CommandLine::parse(char argc, const char* argv[], bool logError, ualni skipArgs) { + // discard some arguments + argc -= (char) skipArgs; + argv += skipArgs; + + if (argc < mArgs.size() - mOptionals) { + ErrInvalidArgCount(); + if (logError) { + ErrLog(); + } + return false; + } + + ualni idx = 0; + for (auto arg : mArgsOrder) { + if (idx < argc) { + parseArg(*arg.data(), argv[idx]); + } else { + initDefault(*arg.data()); + } + if (mError) { + if (logError) ErrLog(); + return false; + } + idx++; + } + return true; +} + +bool CommandLine::parse(const char* args, bool logError) { + mArgumentTokenizer.bindSource(args); + mArgumentTokenizer.reset(); + + ualni argc = 0; + auto tok = mArgumentTokenizer.readTok(); + auto argument = mArgsOrder.first(); + + while (tok != ArgTokType::FAILURE && tok != ArgTokType::END) { + if (tok != ArgTokType::ARG) { + tok = mArgumentTokenizer.readTok(); + continue; + } + + if (!argument) { + ErrInvalidArgCount(); + if (logError) ErrLog(); + return false; + } + + parseArg(*argument->data, mArgumentTokenizer.extractVal().read()); + + if (mError && logError) { + ErrLog(); + return false; + } + + argc++; + argument = argument->next; + tok = mArgumentTokenizer.readTok(); + } + + ualni idx = 0; + for (auto arg : mArgsOrder) { + if (idx >= argc) { + initDefault(*arg.data()); + } + if (mError) { + if (logError) ErrLog(); + return false; + } + idx++; + } + return true; +} + +alni CommandLine::getInt(const String& id) const { + auto& arg = getArg(id, Arg::INT); + return arg.mInt.mVal; +} +alnf CommandLine::getFloat(const String& id) const { + auto& arg = getArg(id, Arg::FLOAT); + return arg.mFloat.mVal; +} +bool CommandLine::getBool(const String& id) const { + auto& arg = getArg(id, Arg::BOOL); + return arg.mBool.mFlag; +} +const String& CommandLine::getString(const String& id) const { + auto& arg = getArg(id, Arg::STR); + return arg.mStr.mStr; +} +const LocalConnection::Location& CommandLine::getFile(const String& id) const { + auto& arg = getArg(id, Arg::FILE_IN); + return arg.mFile.mFileLocation; +} + +CommandLine::Arg& CommandLine::getArg(const String& id, Arg::Type type) { + auto idx = mArgs.presents(id); + ASSERT(idx && "Invalid Id") + auto& arg = mArgs.getSlotVal(idx); + ASSERT(arg->mType == type && "Invalid Type Requested") + return *arg; +} + +const CommandLine::Arg& CommandLine::getArg(const String& id, Arg::Type type) const { + auto idx = mArgs.presents(id); + ASSERT(idx && "Invalid Id") + auto& arg = mArgs.getSlotVal(idx); + ASSERT(arg->mType == type && "Invalid Type Requested") + return *arg; +} + +void CommandLine::ErrInvalidArgCount() { mError = { "Invalid Number Of Arguments Passed", nullptr }; } +void CommandLine::ErrInvalidArgSyntax(Arg* arg) { mError = { "Invalid Syntax Of Argument", arg }; } +void CommandLine::ErrInvalidArgType(Arg* arg) { mError = { "Invalid Type Of Argument", arg }; } +void CommandLine::ErrFileNotExists(Arg* arg) { mError = { "File Not Exists", arg }; } +void CommandLine::ErrFileCouldNotOpen(Arg* arg) { mError = { "Could Not Open File", arg }; } +void CommandLine::ErrValNotinRange(Arg* arg) { mError = { "Value Not In Range", arg }; } + +void CommandLine::ErrLog() { + printf("\nERROR : Invalid Command Line\n"); + + if (mError.mArg) { + alni idx = 0; + for (auto arg : mArgsOrder) { + if (mError.mArg == arg.data()) break; + idx++; + } + + printf("\nArgument: %lli\n", idx); + logArg(*mError.mArg); + } + + printf("Error Description: %s. \n", mError.mDescr); + + printf("\nExpected Arguments are: \n"); + ualni idx = 0; + for (auto arg : mArgsOrder) { + printf(" -- %lli -- \n", idx); + logArg(*arg.data()); + idx++; + } + + printf("\nNote regex for types are:\n"); + printf(" False - %s\n", regexFalse); + printf(" True - %s\n", regexTrue); + printf(" Int - %s\n", regexInt); + printf(" Float - %s\n", regexFloat); + printf(" String - %s\n", regexString); + printf(" File - else\n"); +} + +void CommandLine::logArg(const Arg& arg) { + switch (arg.mType) { + case Arg::INT: + { + printf("Type : Int\n"); + printf("Range : %lli - %lli\n", arg.mInt.mAcceptingRange.mBegin, arg.mInt.mAcceptingRange.mEnd); + if (arg.mOptional) { + printf("Default : %lli\n", arg.mInt.mDefault); + } + printf("Value : %lli\n", arg.mInt.mVal); + } + break; + case Arg::FLOAT: + { + printf("Type : Float\n"); + printf("Range : %f - %f\n", (halnf) arg.mFloat.mAcceptingRange.mBegin, (halnf) arg.mFloat.mAcceptingRange.mEnd); + if (arg.mOptional) { + printf("Default : %f\n", arg.mFloat.mDefault); + } + printf("Value : %f\n", arg.mFloat.mVal); + } + break; + case Arg::BOOL: + { + printf("Type : Bool\n"); + if (arg.mOptional) { + printf("Default : %s\n", arg.mBool.mDefault ? "True" : "False"); + } + printf("Value : %s\n", arg.mBool.mFlag ? "True" : "False"); + } + break; + case Arg::STR: + { + printf("Type : String\n"); + if (arg.mOptional) { + printf("Default : %s\n", arg.mStr.mDefault.read()); + } + printf("Value : %s\n", arg.mStr.mStr.read()); + } + break; + case Arg::FILE_IN: + { + printf("Type : File Input\n"); + printf("Value Path : %s\n", arg.mFile.mFileLocation.getLocation().read()); + } + break; + default: ASSERT(false) + } +} + +void CommandLine::initDefault(Arg& arg) { + switch (arg.mType) { + case Arg::INT: arg.mInt.mVal = arg.mInt.mDefault; break; + case Arg::FLOAT: arg.mFloat.mVal = arg.mFloat.mDefault; break; + case Arg::BOOL: arg.mBool.mFlag = arg.mBool.mDefault; break; + case Arg::STR: arg.mStr.mStr = arg.mStr.mDefault; break; + default: break; + } +} + +void CommandLine::parseArg(Arg& arg, const char* src) { + mTokenizer.reset(); + mTokenizer.bindSource(src); + + auto tok = mTokenizer.readTok(); + if (tok < TokType::INT || tok > TokType::STR) { + ErrInvalidArgSyntax(&arg); + return; + } + + auto val = mTokenizer.extractVal(); + + switch (arg.mType) { + case Arg::INT: + { + if (tok != TokType::INT) { + ErrInvalidArgType(&arg); + return; + } + auto converted = String::Logic::convertStringToValue(val.read(), arg.mInt.mVal); + if (converted && arg.mInt.mVal < arg.mInt.mAcceptingRange.mBegin || arg.mInt.mVal > arg.mInt.mAcceptingRange.mEnd) { + ErrValNotinRange(&arg); + return; + } + } + break; + + case Arg::FLOAT: + { + if (tok != TokType::FLOAT) { + ErrInvalidArgType(&arg); + return; + } + auto converted = String::Logic::convertStringToValue(val.read(), arg.mFloat.mVal); + if (converted && arg.mFloat.mVal < arg.mFloat.mAcceptingRange.mBegin || arg.mFloat.mVal > arg.mFloat.mAcceptingRange.mEnd) { + ErrValNotinRange(&arg); + return; + } + } + break; + + case Arg::STR: + { + if (tok != TokType::STR) { + ErrInvalidArgType(&arg); + return; + } + arg.mStr.mStr.resize(val.size() - 2); + memCopy(arg.mStr.mStr.write(), val.read() + 1, val.size() - 2); + } + break; + + case Arg::BOOL: + { + if (tok != TokType::BOOL_FALSE && tok != TokType::BOOL_TRUE) { + ErrInvalidArgType(&arg); + return; + } + arg.mBool.mFlag = tok == TokType::BOOL_TRUE; + } + break; + + case Arg::FILE_IN: + { + if (tok != TokType::STR) { + ErrInvalidArgType(&arg); + return; + } + + arg.mFile.mFileLocation.setLocation(val); + + if (!arg.mFile.mFileLocation.exists()) { + ErrFileNotExists(&arg); + return; + } + } + break; + default: ASSERT(false) + } + + arg.mIsPassed = true; +} + +void CommandLine::help() const { + printf("Arguments:\n"); + for (auto arg : mArgsOrder) { + logArg(*arg.data()); + } } \ No newline at end of file diff --git a/CommandLine/public/CmdLineInterpreter.hpp b/CommandLine/public/CmdLineInterpreter.hpp index 5839544..5a0943a 100644 --- a/CommandLine/public/CmdLineInterpreter.hpp +++ b/CommandLine/public/CmdLineInterpreter.hpp @@ -1,36 +1,34 @@ -#pragma once - -#include "CommandLine.hpp" -#include "Map.hpp" - -namespace tp { - - class CmdLineInterpreter { - public: - - typedef bool (*CommandFunction)(void* customData, const CommandLine& args); - - private: - - struct Command { - CommandLine* args; - CommandFunction function; - void* customData = nullptr; - }; - - Map mCommands; - String mName = "InterpName"; - - public: - CmdLineInterpreter(); - ~CmdLineInterpreter(); - - void setName(const String& name) { mName = name; } - [[nodiscard]] const String& getName() const { return mName; } - - void help(const CommandLine& args) const; - void addCommand(const String& id, CommandLine* args, CommandFunction function, void* customData = nullptr); - void run(); - bool processCommand(int1* command); - }; +#pragma once + +#include "CommandLine.hpp" +#include "Map.hpp" + +namespace tp { + + class CmdLineInterpreter { + public: + typedef bool (*CommandFunction)(void* customData, const CommandLine& args); + + private: + struct Command { + CommandLine* args; + CommandFunction function; + void* customData = nullptr; + }; + + Map mCommands; + String mName = "InterpName"; + + public: + CmdLineInterpreter(); + ~CmdLineInterpreter(); + + void setName(const String& name) { mName = name; } + [[nodiscard]] const String& getName() const { return mName; } + + void help(const CommandLine& args) const; + void addCommand(const String& id, CommandLine* args, CommandFunction function, void* customData = nullptr); + void run(); + bool processCommand(int1* command); + }; } \ No newline at end of file diff --git a/CommandLine/public/CommandLine.hpp b/CommandLine/public/CommandLine.hpp index 9573dc9..1d2ff81 100644 --- a/CommandLine/public/CommandLine.hpp +++ b/CommandLine/public/CommandLine.hpp @@ -1,114 +1,130 @@ -#pragma once - -#include "Map.hpp" -#include "LocalConnection.hpp" -#include "Tokenizer.hpp" - -namespace tp { - - extern ModuleManifest gModuleCommandLine; - - struct CommandLine { - - struct IntArg { - alni mVal = 0; - alni mDefault = 0; - Range mAcceptingRange = { -(std::numeric_limits::max() - 1), std::numeric_limits::max() }; - }; - - struct FloatArg { - alnf mVal = 0.f; - alnf mDefault = 0.f; - Range mAcceptingRange = { -(std::numeric_limits::max() - 1), std::numeric_limits::max() }; - }; - - struct BoolArg { - bool mFlag = false; - bool mDefault = false; - }; - - struct StringArg { - String mStr; - String mDefault; - }; - - struct FileInputArg { - LocalConnection::Location mFileLocation; - }; - - struct Arg { - String mId; - enum Type { INT, FLOAT, BOOL, STR, FILE_IN, NONE } mType = NONE; - union { - IntArg mInt; - FloatArg mFloat; - BoolArg mBool; - StringArg mStr; - FileInputArg mFile; - }; - - bool mOptional = true; - bool mIsPassed = false; - - Arg(const Arg& arg); - Arg(const String& id, Type type); - Arg(const String& id, const Range& aAcceptingRange); - Arg(const String& id, const Range& aAcceptingRange); - Arg(const String& id, const Range& aAcceptingRange, alni aDefault); - Arg(const String& id, const Range& aAcceptingRange, alnf aDefault); - Arg(const String& id, bool aDefault); - Arg(const String& id, const char* aDefault); - ~Arg(); - }; - - struct Error { - const char* mDescr = nullptr; - Arg* mArg = nullptr; - operator bool() { return mDescr != nullptr; } - } mError; - - CommandLine(const InitialierList& args); - ~CommandLine(); - - void resetError() { mError.mDescr = nullptr; } - - bool parse(char argc, const char* argv[], bool logError = true, ualni skipArgs = 1); - bool parse(const char* args, bool logError = true); - - void help() const; - - [[nodiscard]] alni getInt(const String& id) const; - [[nodiscard]] alnf getFloat(const String& id) const; - [[nodiscard]] bool getBool(const String& id) const; - [[nodiscard]] const String& getString(const String& id) const; - [[nodiscard]] const LocalConnection::Location& getFile(const String& id) const; - - const CommandLine& operator=(const CommandLine&) = delete; - - private: - enum class TokType { SPACE, INT, FLOAT, BOOL_FALSE, BOOL_TRUE, STR, NONE, FAILURE, END, }; - typedef SimpleTokenizer Tokenizer; - - Tokenizer mTokenizer; - Map mArgs; - List mArgsOrder; - ualni mOptionals = 0; - - enum class ArgTokType { SPACE, ARG, NONE, FAILURE, END, }; - SimpleTokenizer mArgumentTokenizer; - - Arg& getArg(const String& id, Arg::Type type); - [[nodiscard]] const Arg& getArg(const String& id, Arg::Type type) const; - - void ErrInvalidArgCount(); - void ErrInvalidArgSyntax(Arg* arg); - void ErrInvalidArgType(Arg* arg); - void ErrFileNotExists(Arg* arg); - void ErrFileCouldNotOpen(Arg* arg); - void ErrValNotinRange(Arg* arg); - void ErrLog(); - static void logArg(const Arg& arg); - static void initDefault(Arg& arg); - void parseArg(Arg& arg, const char* src); - }; +#pragma once + +#include "LocalConnection.hpp" +#include "Map.hpp" +#include "Tokenizer.hpp" + +namespace tp { + + extern ModuleManifest gModuleCommandLine; + + struct CommandLine { + + struct IntArg { + alni mVal = 0; + alni mDefault = 0; + Range mAcceptingRange = { -(std::numeric_limits::max() - 1), std::numeric_limits::max() }; + }; + + struct FloatArg { + alnf mVal = 0.f; + alnf mDefault = 0.f; + Range mAcceptingRange = { -(std::numeric_limits::max() - 1), std::numeric_limits::max() }; + }; + + struct BoolArg { + bool mFlag = false; + bool mDefault = false; + }; + + struct StringArg { + String mStr; + String mDefault; + }; + + struct FileInputArg { + LocalConnection::Location mFileLocation; + }; + + struct Arg { + String mId; + enum Type { INT, FLOAT, BOOL, STR, FILE_IN, NONE } mType = NONE; + union { + IntArg mInt; + FloatArg mFloat; + BoolArg mBool; + StringArg mStr; + FileInputArg mFile; + }; + + bool mOptional = true; + bool mIsPassed = false; + + Arg(const Arg& arg); + Arg(const String& id, Type type); + Arg(const String& id, const Range& aAcceptingRange); + Arg(const String& id, const Range& aAcceptingRange); + Arg(const String& id, const Range& aAcceptingRange, alni aDefault); + Arg(const String& id, const Range& aAcceptingRange, alnf aDefault); + Arg(const String& id, bool aDefault); + Arg(const String& id, const char* aDefault); + ~Arg(); + }; + + struct Error { + const char* mDescr = nullptr; + Arg* mArg = nullptr; + operator bool() { return mDescr != nullptr; } + } mError; + + CommandLine(const InitialierList& args); + ~CommandLine(); + + void resetError() { mError.mDescr = nullptr; } + + bool parse(char argc, const char* argv[], bool logError = true, ualni skipArgs = 1); + bool parse(const char* args, bool logError = true); + + void help() const; + + [[nodiscard]] alni getInt(const String& id) const; + [[nodiscard]] alnf getFloat(const String& id) const; + [[nodiscard]] bool getBool(const String& id) const; + [[nodiscard]] const String& getString(const String& id) const; + [[nodiscard]] const LocalConnection::Location& getFile(const String& id) const; + + const CommandLine& operator=(const CommandLine&) = delete; + + private: + enum class TokType { + SPACE, + INT, + FLOAT, + BOOL_FALSE, + BOOL_TRUE, + STR, + NONE, + FAILURE, + END, + }; + typedef SimpleTokenizer Tokenizer; + + Tokenizer mTokenizer; + Map mArgs; + List mArgsOrder; + ualni mOptionals = 0; + + enum class ArgTokType { + SPACE, + ARG, + NONE, + FAILURE, + END, + }; + SimpleTokenizer mArgumentTokenizer; + + Arg& getArg(const String& id, Arg::Type type); + [[nodiscard]] const Arg& getArg(const String& id, Arg::Type type) const; + + void ErrInvalidArgCount(); + void ErrInvalidArgSyntax(Arg* arg); + void ErrInvalidArgType(Arg* arg); + void ErrFileNotExists(Arg* arg); + void ErrFileCouldNotOpen(Arg* arg); + void ErrValNotinRange(Arg* arg); + void ErrLog(); + static void logArg(const Arg& arg); + static void initDefault(Arg& arg); + void parseArg(Arg& arg, const char* src); + }; } \ No newline at end of file diff --git a/CommandLine/tests/TestCommandLine.cpp b/CommandLine/tests/TestCommandLine.cpp index bbc5ceb..f74ff8c 100644 --- a/CommandLine/tests/TestCommandLine.cpp +++ b/CommandLine/tests/TestCommandLine.cpp @@ -6,10 +6,10 @@ using namespace tp; static CommandLine createCmdLine() { CommandLine cmd({ - { "bool", CommandLine::Arg::BOOL }, - { "int", CommandLine::Arg::INT }, - { "string", CommandLine::Arg::STR }, - { "float", CommandLine::Arg::FLOAT }, + { "bool", CommandLine::Arg::BOOL }, + { "int", CommandLine::Arg::INT }, + { "string", CommandLine::Arg::STR }, + { "float", CommandLine::Arg::FLOAT }, }); return cmd; } @@ -20,6 +20,4 @@ TEST_DEF_STATIC(Simple) { cmd.parse(4, args, true, 0); } -TEST_DEF(CommandLine) { - testSimple(); -} +TEST_DEF(CommandLine) { testSimple(); } diff --git a/CommandLine/tests/TestInterpreter.cpp b/CommandLine/tests/TestInterpreter.cpp index c32777f..c853cf2 100644 --- a/CommandLine/tests/TestInterpreter.cpp +++ b/CommandLine/tests/TestInterpreter.cpp @@ -1,7 +1,7 @@ #include "NewPlacement.hpp" -#include "Tests.hpp" #include "CmdLineInterpreter.hpp" +#include "Tests.hpp" using namespace tp; @@ -14,7 +14,6 @@ TEST_DEF_STATIC(Simple) { printf("Test Val - %i\n", (int) args.getBool("bool")); return false; } - }; TestStruct self; @@ -32,5 +31,5 @@ TEST_DEF_STATIC(Simple) { } TEST_DEF(Interpreter) { - //testSimple(); + // testSimple(); } diff --git a/CommandLine/tests/Tests.cpp b/CommandLine/tests/Tests.cpp index 81b3595..45e0203 100644 --- a/CommandLine/tests/Tests.cpp +++ b/CommandLine/tests/Tests.cpp @@ -1,18 +1,18 @@ -#include "NewPlacement.hpp" - -#include "Tests.hpp" - -int main() { - - tp::ModuleManifest* deps[] = { &tp::gModuleUtils, &tp::gModuleTokenizer, nullptr }; - tp::ModuleManifest testModule("CommandLineTest", nullptr, nullptr, deps); - - if (!testModule.initialize()) { - return 1; - } - - // testCommandLine(); - testInterpreter(); - - testModule.deinitialize(); -} +#include "NewPlacement.hpp" + +#include "Tests.hpp" + +int main() { + + tp::ModuleManifest* deps[] = { &tp::gModuleUtils, &tp::gModuleTokenizer, nullptr }; + tp::ModuleManifest testModule("CommandLineTest", nullptr, nullptr, deps); + + if (!testModule.initialize()) { + return 1; + } + + // testCommandLine(); + testInterpreter(); + + testModule.deinitialize(); +} diff --git a/CommandLine/tests/Tests.hpp b/CommandLine/tests/Tests.hpp index eaac059..5e2bbe1 100644 --- a/CommandLine/tests/Tests.hpp +++ b/CommandLine/tests/Tests.hpp @@ -1,8 +1,8 @@ #pragma once -#include "Testing.hpp" #include "Allocators.hpp" #include "CommandLine.hpp" +#include "Testing.hpp" void testCommandLine(); void testInterpreter(); diff --git a/Connection/private/ConnectionCommon.cpp b/Connection/private/ConnectionCommon.cpp index 0592308..d9a05fe 100644 --- a/Connection/private/ConnectionCommon.cpp +++ b/Connection/private/ConnectionCommon.cpp @@ -1,9 +1,6 @@ #include "ConnectionCommon.hpp" -static tp::ModuleManifest* sModuleDependencies[] = { - &tp::gModuleStrings, - nullptr -}; +static tp::ModuleManifest* sModuleDependencies[] = { &tp::gModuleStrings, nullptr }; tp::ModuleManifest tp::gModuleConnection = ModuleManifest("Storage", nullptr, nullptr, sModuleDependencies); \ No newline at end of file diff --git a/Connection/private/LocalConnection.cpp b/Connection/private/LocalConnection.cpp index cf90e2e..606d7bc 100644 --- a/Connection/private/LocalConnection.cpp +++ b/Connection/private/LocalConnection.cpp @@ -25,16 +25,11 @@ bool LocalConnection::connect(const Location& location, const Type& connectionIn auto handle = new LocalConnectionContext(); switch (connectionInfo.getType()) { - case Type::READ: - handle->open(location.getLocation().read(), true); - break; + case Type::READ: handle->open(location.getLocation().read(), true); break; - case Type::WRITE: - handle->open(location.getLocation().read(), false); - break; + case Type::WRITE: handle->open(location.getLocation().read(), false); break; - default: - break; + default: break; }; if (!handle->isOpen()) { diff --git a/Connection/private/bindings/Disk.cpp b/Connection/private/bindings/Disk.cpp index caf6bdc..97d8cc9 100644 --- a/Connection/private/bindings/Disk.cpp +++ b/Connection/private/bindings/Disk.cpp @@ -14,9 +14,7 @@ ualni tp::LocalConnectionContext::size() { return out; } -LocalConnectionContext::LocalConnectionContext() { - stream = new std::fstream(); -} +LocalConnectionContext::LocalConnectionContext() { stream = new std::fstream(); } LocalConnectionContext::~LocalConnectionContext() { auto strm = (std::fstream*) stream; @@ -50,8 +48,6 @@ void LocalConnectionContext::write(const int1* in, ualni size) { void LocalConnectionContext::open(const char* path, bool read) { auto strm = (std::fstream*) stream; - if (read) - strm->open(path, std::ios::in | std::ios::binary | std::ios::app); - else - strm->open(path, std::ios::out | std::ios::binary | std::ios::trunc); + if (read) strm->open(path, std::ios::in | std::ios::binary | std::ios::app); + else strm->open(path, std::ios::out | std::ios::binary | std::ios::trunc); } diff --git a/Connection/private/bindings/Disk.hpp b/Connection/private/bindings/Disk.hpp index 02d247b..ad53c43 100644 --- a/Connection/private/bindings/Disk.hpp +++ b/Connection/private/bindings/Disk.hpp @@ -3,6 +3,7 @@ namespace tp { class LocalConnectionContext { void* stream; + public: LocalConnectionContext(); ~LocalConnectionContext(); diff --git a/Connection/private/bindings/Network.cpp b/Connection/private/bindings/Network.cpp index 779de03..8cdcc92 100644 --- a/Connection/private/bindings/Network.cpp +++ b/Connection/private/bindings/Network.cpp @@ -13,7 +13,8 @@ class tp::ServerContext { asio::ip::tcp::acceptor socket; typedef asio::ip::tcp::socket Socket; - ServerContext() : socket(context) {} + ServerContext() : + socket(context) {} ~ServerContext() { context.stop(); @@ -28,7 +29,8 @@ class tp::ClientContext { asio::ip::tcp::socket socket; public: - ClientContext() : socket(context) {} + ClientContext() : + socket(context) {} ~ClientContext() { context.stop(); @@ -38,11 +40,9 @@ public: // --------------------------------------------------------------------------------------- // -Server::Server() { - mContext = new ServerContext(); -} +Server::Server() { mContext = new ServerContext(); } -Server::~Server() { +Server::~Server() { delete mContext; assert(0); } @@ -57,20 +57,20 @@ void Server::start(ualni port) { Server::Socket Server::accept() { auto clientSocket = new asio::ip::tcp::socket(mContext->context); mContext->socket.accept(*clientSocket); - std::cout << "New client accepted "<< std::endl; + std::cout << "New client accepted " << std::endl; return clientSocket; } int1* Server::read(Socket client) { short messageSize; - if (asio::read(*(ServerContext::Socket*)client, asio::buffer(&messageSize, 2)) == -1) { + if (asio::read(*(ServerContext::Socket*) client, asio::buffer(&messageSize, 2)) == -1) { std::cerr << "Failed to read from socket" << std::endl; - ((ServerContext::Socket*)client)->close(); + ((ServerContext::Socket*) client)->close(); return nullptr; } auto message = new char[messageSize + 1]; message[messageSize] = '\0'; - if (asio::read(*(ServerContext::Socket*)client, asio::buffer(message, messageSize)) == -1) { + if (asio::read(*(ServerContext::Socket*) client, asio::buffer(message, messageSize)) == -1) { std::cerr << "Failed to read from socket" << std::endl; memcpy(message, "Client wanna say something but i cant read", 100); } @@ -79,19 +79,17 @@ int1* Server::read(Socket client) { void Server::write(Socket client, const char* message) { auto messageSize = (short) strlen(message); - if (asio::write(*(ServerContext::Socket*)client, asio::buffer(&messageSize, 2)) == -1) { + if (asio::write(*(ServerContext::Socket*) client, asio::buffer(&messageSize, 2)) == -1) { std::cerr << "Failed to write to socket" << std::endl; } - if (asio::write(*(ServerContext::Socket*)client, asio::buffer(message, messageSize)) == -1) { + if (asio::write(*(ServerContext::Socket*) client, asio::buffer(message, messageSize)) == -1) { std::cerr << "Failed to write to socket" << std::endl; } } // --------------------------------------------------------------------------------------- // -Client::Client() { - mContext = new ClientContext(); -} +Client::Client() { mContext = new ClientContext(); } Client::~Client() { delete mContext; @@ -118,7 +116,7 @@ char* Client::read() { return message; } -void Client::write( const char* message ) { +void Client::write(const char* message) { auto messageSize = (short) strlen(message); if (asio::write(mContext->socket, asio::buffer(&messageSize, 2)) == -1) { std::cerr << "Failed to write to socket" << std::endl; @@ -127,4 +125,3 @@ void Client::write( const char* message ) { std::cerr << "Failed to write to socket" << std::endl; } } - diff --git a/Connection/public/ConnectionCommon.hpp b/Connection/public/ConnectionCommon.hpp index 6c3cc1f..9d8f1f4 100644 --- a/Connection/public/ConnectionCommon.hpp +++ b/Connection/public/ConnectionCommon.hpp @@ -45,8 +45,10 @@ namespace tp { public: Type() = default; - explicit Type(bool read) : mHandleType((State) read) {} - explicit Type(State handleType) : mHandleType(handleType) {} + explicit Type(bool read) : + mHandleType((State) read) {} + explicit Type(State handleType) : + mHandleType(handleType) {} [[nodiscard]] State getType() const { return mHandleType; } [[nodiscard]] bool isRead() const { return mHandleType == READ; } [[nodiscard]] bool isWrite() const { return mHandleType == WRITE; } diff --git a/Connection/public/LocalConnection.hpp b/Connection/public/LocalConnection.hpp index d8d84d1..4c031b2 100644 --- a/Connection/public/LocalConnection.hpp +++ b/Connection/public/LocalConnection.hpp @@ -9,18 +9,19 @@ namespace tp { public: class Location { String mLocation; + public: - Location() : mLocation("tmp") {}; - explicit Location(const String& location) : mLocation(location) {} + Location() : + mLocation("tmp"){}; + explicit Location(const String& location) : + mLocation(location) {} void setLocation(const String& location) { mLocation = location; } [[nodiscard]] const String& getLocation() const { return mLocation; } [[nodiscard]] bool exists() const; }; public: - LocalConnection() { - MODULE_SANITY_CHECK(gModuleConnection) - }; + LocalConnection(){ MODULE_SANITY_CHECK(gModuleConnection) }; virtual ~LocalConnection() { if (mStatus.isOpened()) LocalConnection::disconnect(); diff --git a/Connection/public/RemoteConnection.hpp b/Connection/public/RemoteConnection.hpp index fd8f872..13c3f5e 100644 --- a/Connection/public/RemoteConnection.hpp +++ b/Connection/public/RemoteConnection.hpp @@ -11,14 +11,13 @@ namespace tp { public: class Location { ualni mId = 0; + public: Location() = default; }; public: - RemoteConnection() { - MODULE_SANITY_CHECK(gModuleConnection) - }; + RemoteConnection(){ MODULE_SANITY_CHECK(gModuleConnection) }; virtual ~RemoteConnection() { if (mStatus.isOpened()) RemoteConnection::disconnect(); diff --git a/Connection/tests/TestLocal.cpp b/Connection/tests/TestLocal.cpp index 0732de4..1fdb4b1 100644 --- a/Connection/tests/TestLocal.cpp +++ b/Connection/tests/TestLocal.cpp @@ -30,6 +30,4 @@ TEST_DEF_STATIC(Simple) { } } -TEST_DEF(LocalConnection) { - testSimple(); -} \ No newline at end of file +TEST_DEF(LocalConnection) { testSimple(); } \ No newline at end of file diff --git a/Containers/private/Containers.cpp b/Containers/private/Containers.cpp index b680dc5..4aef4db 100644 --- a/Containers/private/Containers.cpp +++ b/Containers/private/Containers.cpp @@ -1,18 +1,14 @@ - -#include "ContainersCommon.hpp" - -#include - -namespace tp { - - static ModuleManifest* sModuleDependencies[] = { &gModuleBase,nullptr }; - ModuleManifest gModuleContainers = ModuleManifest("Containers", nullptr, nullptr, sModuleDependencies); - - void* DefaultAllocator::allocate(ualni size) { - return malloc(size); - } - - void DefaultAllocator::deallocate(void* p) { - free(p); - } + +#include "ContainersCommon.hpp" + +#include + +namespace tp { + + static ModuleManifest* sModuleDependencies[] = { &gModuleBase, nullptr }; + ModuleManifest gModuleContainers = ModuleManifest("Containers", nullptr, nullptr, sModuleDependencies); + + void* DefaultAllocator::allocate(ualni size) { return malloc(size); } + + void DefaultAllocator::deallocate(void* p) { free(p); } } \ No newline at end of file diff --git a/Containers/public/Buffer.hpp b/Containers/public/Buffer.hpp index 1e68d9e..dddd7ca 100644 --- a/Containers/public/Buffer.hpp +++ b/Containers/public/Buffer.hpp @@ -5,20 +5,27 @@ namespace tp { - template - inline ualni BufferResizeScaling(ualni const size) { return size * tScale; } + template + inline ualni BufferResizeScaling(const ualni size) { + return size * tScale; + } - template - inline ualni BufferResizeScalingDown(ualni const size) { return size / tScale; } + template + inline ualni BufferResizeScalingDown(const ualni size) { + return size / tScale; + } - template - inline ualni BufferResizeAddition(ualni const size) { return size + tAddition; } + template + inline ualni BufferResizeAddition(const ualni size) { + return size + tAddition; + } - template - inline ualni BufferResizeAdditionDown(ualni const size) { return size - tAddition; } + template + inline ualni BufferResizeAdditionDown(const ualni size) { + return size - tAddition; + } - - template + template class ConstSizeBuffer { typedef SelectValueOrReference Arg; @@ -37,6 +44,7 @@ namespace tp { public: [[nodiscard]] ualni size() const { return mLoad; } + [[nodiscard]] ualni getBuffSize() const { return tSize; } tType& first() { @@ -94,28 +102,32 @@ namespace tp { } public: - class IteratorPointer { protected: tType* mIter; + public: IteratorPointer() = default; + tType& operator->() { return *mIter; } + const tType& operator->() const { return *mIter; } }; class IteratorReference { protected: tType* mIter; + public: IteratorReference() = default; + tType* operator->() { return mIter; } + const tType* operator->() const { return mIter; } }; class Iterator : public TypeSelect::isPointer, IteratorPointer, IteratorReference>::Result { public: - explicit Iterator(tType* iter) { this->mIter = iter; } const Iterator& operator*() const { return *this; } @@ -126,19 +138,16 @@ namespace tp { } bool operator==(const Iterator& left) const { return left.mIter == this->mIter; } + bool operator!=(const Iterator& left) const { return left.mIter != this->mIter; } }; - [[nodiscard]] Iterator begin() const { - return Iterator(mBuff); - } + [[nodiscard]] Iterator begin() const { return Iterator(mBuff); } - [[nodiscard]] Iterator end() const { - return Iterator(mBuff + mLoad); - } + [[nodiscard]] Iterator end() const { return Iterator(mBuff + mLoad); } public: - template + template void archiveWrite(tArchiver& ar) const { ar << mLoad; for (auto item : *this) { @@ -146,7 +155,7 @@ namespace tp { } } - template + template void archiveRead(tArchiver& ar) { clear(); ar >> mLoad; @@ -156,13 +165,7 @@ namespace tp { } }; - template< - typename tType, - class tAllocator = DefaultAllocator, - ualni (tResizePolicy)(ualni) = BufferResizeScaling<2>, - ualni (tResizePolicyDown)(ualni) = BufferResizeScalingDown<2>, - ualni tMinSize = 4 - > + template , ualni(tResizePolicyDown)(ualni) = BufferResizeScalingDown<2>, ualni tMinSize = 4> class Buffer { typedef SelectValueOrReference Arg; @@ -173,17 +176,25 @@ namespace tp { ualni mLoad; public: - Buffer() : mSize(tMinSize), mLoad(0) { + Buffer() : + mSize(tMinSize), + mLoad(0) { mBuff = (tType*) mAllocator.allocate(sizeof(tType) * tMinSize); } - explicit Buffer(ualni size) : mSize(size), mLoad(0) { + explicit Buffer(ualni size) : + mSize(size), + mLoad(0) { mBuff = (tType*) mAllocator.allocate(sizeof(tType) * size); } - Buffer(const Buffer& in) : mSize(in.mSize), mLoad(in.mLoad) { + Buffer(const Buffer& in) : + mSize(in.mSize), + mLoad(in.mLoad) { mBuff = (tType*) mAllocator.allocate(sizeof(tType) * mSize); - for (ualni i = 0; i < mLoad; i++) new (&mBuff[i]) tType(in.mBuff[i]); + for (ualni i = 0; i < mLoad; i++) { + new (&mBuff[i]) tType(in.mBuff[i]); + } } void clear() { @@ -192,44 +203,48 @@ namespace tp { } Buffer& operator=(const Buffer& in) { - if (this == &in) return *this; + if (this == &in) { + return *this; + } this->~Buffer(); - new (this) Buffer(in); - return *this; + new (this) Buffer(in); + return *this; } ~Buffer() { - for (ualni i = 0; i < mLoad; i++) mBuff[i].~tType(); + for (ualni i = 0; i < mLoad; i++) { + mBuff[i].~tType(); + } mAllocator.deallocate(mBuff); } public: - [[nodiscard]] ualni size() const { - return mLoad; - } + [[nodiscard]] ualni size() const { return mLoad; } + + [[nodiscard]] ualni getBuffSize() const { return mSize; } + + [[nodiscard]] const tType* getBuff() const { return mBuff; } + + [[nodiscard]] tType* getBuff() { return mBuff; } - [[nodiscard]] ualni getBuffSize() const { - return mSize; - } - tType& first() { - DEBUG_ASSERT(mLoad) - return *mBuff; + DEBUG_ASSERT(mLoad) + return *mBuff; } const tType& first() const { - DEBUG_ASSERT(mLoad) - return *mBuff; + DEBUG_ASSERT(mLoad) + return *mBuff; } tType& last() { - DEBUG_ASSERT(mLoad) - return mBuff[mLoad - 1]; + DEBUG_ASSERT(mLoad) + return mBuff[mLoad - 1]; } const tType& last() const { - DEBUG_ASSERT(mLoad) - return mBuff[mLoad - 1]; + DEBUG_ASSERT(mLoad) + return mBuff[mLoad - 1]; } tType& operator[](ualni idx) { @@ -244,10 +259,16 @@ namespace tp { public: bool operator==(const Buffer& in) const { - if (this == &in) return true; - if (mLoad != in.mLoad) return false; + if (this == &in) { + return true; + } + if (mLoad != in.mLoad) { + return false; + } for (ualni i = 0; i < mLoad; i++) { - if (mBuff[i] != in.mBuff[i]) return false; + if (mBuff[i] != in.mBuff[i]) { + return false; + } } return true; } @@ -262,67 +283,86 @@ namespace tp { } void append(Arg data) { - if (mLoad == mSize) resizeBuffer(tResizePolicy(mSize)); + if (mLoad == mSize) { + resizeBuffer(tResizePolicy(mSize)); + } new (&mBuff[mLoad]) tType(data); mLoad++; } - void append(const Buffer& in) { - if (!in.mLoad) return; - auto newLoad = mLoad + in.mLoad; - auto newSize = mSize; - while (newLoad >= newSize) newSize = tResizePolicy(newSize); - if (newSize != mSize) resizeBuffer(newSize); - for (auto i = mLoad; i < newLoad; i++) new (&mBuff[i]) tType(in.mBuff[i - mLoad]); - mLoad = newLoad; - } + void append(const Buffer& in) { + if (!in.mLoad) { + return; + } + auto newLoad = mLoad + in.mLoad; + auto newSize = mSize; + while (newLoad >= newSize) { + newSize = tResizePolicy(newSize); + } + if (newSize != mSize) { + resizeBuffer(newSize); + } + for (auto i = mLoad; i < newLoad; i++) { + new (&mBuff[i]) tType(in.mBuff[i - mLoad]); + } + mLoad = newLoad; + } void pop() { DEBUG_ASSERT(mLoad) mBuff[mLoad].~tType(); mLoad--; ualni prevSize = tResizePolicyDown(mSize); - DEBUG_ASSERT(prevSize < mSize) - if (prevSize > mLoad) resizeBuffer(prevSize); + DEBUG_ASSERT(prevSize < mSize) + if (prevSize > mLoad) { + resizeBuffer(prevSize); + } } void reserve(ualni aSize) { - for (ualni i = 0; i < mLoad; i++) mBuff[i].~tType(); + for (ualni i = 0; i < mLoad; i++) { + mBuff[i].~tType(); + } mBuff = (tType*) mAllocator.allocate(sizeof(tType) * aSize); mSize = aSize; mLoad = aSize; - for (ualni i = 0; i < mLoad; i++) new (mBuff + i) tType(); + for (ualni i = 0; i < mLoad; i++) { + new (mBuff + i) tType(); + } } public: class IteratorPointer { protected: tType* mIter; + public: IteratorPointer() = default; + tType& operator->() { return *mIter; } + const tType& operator->() const { return *mIter; } }; class IteratorReference { protected: tType* mIter; + public: IteratorReference() = default; + tType* operator->() { return mIter; } + const tType* operator->() const { return mIter; } }; class Iterator : public TypeSelect::isPointer, IteratorPointer, IteratorReference>::Result { public: - explicit Iterator(tType* iter) { this->mIter = iter; } const Iterator& operator*() const { return *this; } - tType& data() { - return *this->mIter; - } + tType& data() { return *this->mIter; } Iterator& operator++() { this->mIter++; @@ -330,20 +370,16 @@ namespace tp { } bool operator==(const Iterator& left) const { return left.mIter == this->mIter; } + bool operator!=(const Iterator& left) const { return left.mIter != this->mIter; } }; - [[nodiscard]] Iterator begin() const { - return Iterator(mBuff); - } - - [[nodiscard]] Iterator end() const { - return Iterator(mBuff + mLoad); - } + [[nodiscard]] Iterator begin() const { return Iterator(mBuff); } + [[nodiscard]] Iterator end() const { return Iterator(mBuff + mLoad); } public: - template + template void archiveWrite(tArchiver& ar) const { ar << mLoad; for (auto item : *this) { @@ -351,45 +387,56 @@ namespace tp { } } - template + template void archiveRead(tArchiver& ar) { clear(); decltype(mLoad) len; ar >> len; for (auto i = len; i; i--) { // TODO : optimize - if (mLoad == mSize) resizeBuffer(tResizePolicy(mSize)); + if (mLoad == mSize) { + resizeBuffer(tResizePolicy(mSize)); + } ar >> mBuff[mLoad]; mLoad++; } } - private: - void resizeBuffer(ualni newSize) { - DEBUG_ASSERT(newSize >= mLoad) - auto const oldBuff = mBuff; - mBuff = (tType*) mAllocator.allocate(sizeof(tType) * newSize); - for (ualni i = 0; i < mLoad; i++) new (&mBuff[i]) tType(oldBuff[i]); - for (ualni i = 0; i < mLoad; i++) oldBuff[i].~tType(); - mAllocator.deallocate(oldBuff); - mSize = newSize; - } + private: + void resizeBuffer(ualni newSize) { + DEBUG_ASSERT(newSize >= mLoad) + const auto oldBuff = mBuff; + mBuff = (tType*) mAllocator.allocate(sizeof(tType) * newSize); + for (ualni i = 0; i < mLoad; i++) { + new (&mBuff[i]) tType(oldBuff[i]); + } + for (ualni i = 0; i < mLoad; i++) { + oldBuff[i].~tType(); + } + mAllocator.deallocate(oldBuff); + mSize = newSize; + } }; - - template + template void generatePermutations(const Buffer>& in, Buffer>& out) { typedef long long Idx; // sanity check - for (const auto & vec : in) { - if (!vec.size()) return; + for (const auto& vec : in) { + if (!vec.size()) { + return; + } } out.resize(in.size()); auto len = Idx(1); - for (const auto & vec : in) len *= (Idx) vec.size(); - for (auto i = 0; i < in.size(); i++) out[i].resize(len); + for (const auto& vec : in) { + len *= (Idx) vec.size(); + } + for (auto i = 0; i < in.size(); i++) { + out[i].resize(len); + } auto dub = Idx(1); for (auto power = (Idx) in.size() - 1; power >= 0; power--) { diff --git a/Containers/public/Buffer2D.hpp b/Containers/public/Buffer2D.hpp index a5c16ba..097d651 100644 --- a/Containers/public/Buffer2D.hpp +++ b/Containers/public/Buffer2D.hpp @@ -1,125 +1,125 @@ - -#pragma once - -#include "Buffer.hpp" -#include "Utils.hpp" - -namespace tp { - - template - using ConstSizeBuffer2D = ConstSizeBuffer, tSizeY>; - - template - class Buffer2D { - public: - typedef ualni Index; - typedef Pair Index2D; - typedef SelectValueOrReference tTypeArg; - - private: - tAllocator mAlloc; - tType* mBuff = nullptr; - Index2D mSize = {0, 0}; - - void deleteBuffer() { - if (!mBuff) { - return; - } - for (ualni i = 0; i < mSize.x * mSize.y; i++) { - mBuff[i].~tType(); - } - mAlloc.deallocate(mBuff); - } - - void allocateBuffer(Index2D size) { - deleteBuffer(); - mBuff = (tType*) mAlloc.allocate(sizeof(tType) * size.x * size.y); - for (ualni i = 0; i < mSize.x * mSize.y; i++) { - new (mBuff + i) tType(); - } - } - - public: - Buffer2D() = default; - - ~Buffer2D() { - deleteBuffer(); - mSize = {0, 0}; - } - - explicit Buffer2D(Index2D aSize) { reserve(aSize); } - - [[nodiscard]] Index2D size() const { return {mSize.x, mSize.y}; } - - tType* getBuff() const { return mBuff; } - - inline tType& get(const Index2D& at) { - DEBUG_ASSERT(mBuff && at.x < mSize.x && at.y < mSize.y && at.x >= 0 && at.y >= 0) - return *(mBuff + mSize.x * at.y + at.x); - } - - inline const tType& get(const Index2D& at) const { - DEBUG_ASSERT(mBuff && at.x < mSize.x && at.y < mSize.y && at.x >= 0 && at.y >= 0) - return *(mBuff + mSize.x * at.y + at.x); - } - - inline void set(const Index2D& at, tTypeArg value) { - DEBUG_ASSERT(mBuff && at.x < mSize.x && at.y < mSize.y && at.x >= 0 && at.y >= 0) - *(mBuff + mSize.x * at.y + at.x) = value; - } - - void reserve(const Index2D& newSize) { - if (mSize.x != newSize.x || mSize.y != newSize.y) { - allocateBuffer(newSize); - mSize = newSize; - } - } - - void assign(tType value) { - DEBUG_ASSERT(mBuff); - Index len = mSize.x * mSize.y; - for (Index i = 0; i < len; i++) { - mBuff[i] = value; - } - } - - bool operator==(const Buffer2D& in) const { - if (&in == this) { - return true; - } - if (in.size() != size()) { - return false; - } - for (auto i = 0; i < mSize.x * mSize.y; i++) { - if (mBuff[i] != in.mBuff[i]) { - return false; - } - } - return true; - } - - public: - template - void archiveWrite(tArchiver& ar) const { - ar << mSize; - for (auto i = 0; i < mSize.x; i++) { - for (auto j = 0; j < mSize.y; j++) { - ar << get(i, j); - } - } - } - - template - void archiveRead(tArchiver& ar) { - decltype(mSize) size; - deleteBuffer(); - ar >> size; - reserve(size); - for (auto i = 0; i < mSize.x; i++) { - for (auto j = 0; j < mSize.y; j++) { - ar >> get(i, j); - } - } - } - }; -} + +#pragma once + +#include "Buffer.hpp" +#include "Utils.hpp" + +namespace tp { + + template + using ConstSizeBuffer2D = ConstSizeBuffer, tSizeY>; + + template + class Buffer2D { + public: + typedef ualni Index; + typedef Pair Index2D; + typedef SelectValueOrReference tTypeArg; + + private: + tAllocator mAlloc; + tType* mBuff = nullptr; + Index2D mSize = { 0, 0 }; + + void deleteBuffer() { + if (!mBuff) { + return; + } + for (ualni i = 0; i < mSize.x * mSize.y; i++) { + mBuff[i].~tType(); + } + mAlloc.deallocate(mBuff); + } + + void allocateBuffer(Index2D size) { + deleteBuffer(); + mBuff = (tType*) mAlloc.allocate(sizeof(tType) * size.x * size.y); + for (ualni i = 0; i < mSize.x * mSize.y; i++) { + new (mBuff + i) tType(); + } + } + + public: + Buffer2D() = default; + + ~Buffer2D() { + deleteBuffer(); + mSize = { 0, 0 }; + } + + explicit Buffer2D(Index2D aSize) { reserve(aSize); } + + [[nodiscard]] Index2D size() const { return { mSize.x, mSize.y }; } + + tType* getBuff() const { return mBuff; } + + inline tType& get(const Index2D& at) { + DEBUG_ASSERT(mBuff && at.x < mSize.x && at.y < mSize.y && at.x >= 0 && at.y >= 0) + return *(mBuff + mSize.x * at.y + at.x); + } + + inline const tType& get(const Index2D& at) const { + DEBUG_ASSERT(mBuff && at.x < mSize.x && at.y < mSize.y && at.x >= 0 && at.y >= 0) + return *(mBuff + mSize.x * at.y + at.x); + } + + inline void set(const Index2D& at, tTypeArg value) { + DEBUG_ASSERT(mBuff && at.x < mSize.x && at.y < mSize.y && at.x >= 0 && at.y >= 0) + *(mBuff + mSize.x * at.y + at.x) = value; + } + + void reserve(const Index2D& newSize) { + if (mSize.x != newSize.x || mSize.y != newSize.y) { + allocateBuffer(newSize); + mSize = newSize; + } + } + + void assign(tType value) { + DEBUG_ASSERT(mBuff); + Index len = mSize.x * mSize.y; + for (Index i = 0; i < len; i++) { + mBuff[i] = value; + } + } + + bool operator==(const Buffer2D& in) const { + if (&in == this) { + return true; + } + if (in.size() != size()) { + return false; + } + for (auto i = 0; i < mSize.x * mSize.y; i++) { + if (mBuff[i] != in.mBuff[i]) { + return false; + } + } + return true; + } + + public: + template + void archiveWrite(tArchiver& ar) const { + ar << mSize; + for (auto i = 0; i < mSize.x; i++) { + for (auto j = 0; j < mSize.y; j++) { + ar << get(i, j); + } + } + } + + template + void archiveRead(tArchiver& ar) { + decltype(mSize) size; + deleteBuffer(); + ar >> size; + reserve(size); + for (auto i = 0; i < mSize.x; i++) { + for (auto j = 0; j < mSize.y; j++) { + ar >> get(i, j); + } + } + } + }; +} diff --git a/Containers/public/ContainersCommon.hpp b/Containers/public/ContainersCommon.hpp index 43552d8..f3ac219 100644 --- a/Containers/public/ContainersCommon.hpp +++ b/Containers/public/ContainersCommon.hpp @@ -9,18 +9,18 @@ namespace tp { class DefaultAllocator { public: DefaultAllocator() = default; - static void *allocate(ualni); - static void deallocate(void *); + static void* allocate(ualni); + static void deallocate(void*); }; class DefaultSaverLoader { public: DefaultSaverLoader() = default; - template + template static void write(const Type&) {} - template + template static void read(Type&) {} }; } \ No newline at end of file diff --git a/Containers/public/List.hpp b/Containers/public/List.hpp index 075c45f..eba0d95 100644 --- a/Containers/public/List.hpp +++ b/Containers/public/List.hpp @@ -1,327 +1,325 @@ - -#pragma once - -#include "ContainersCommon.hpp" - -#include "TypeInfo.hpp" - -namespace tp { - - template - class List { - - typedef SelectValueOrReference TypeArg; - typedef ualni Index; - - public: - - struct Node { - Type data; - Node* next = nullptr; - Node* prev = nullptr; - Node() = default; - explicit Node(TypeArg p_data) : data(p_data) {} - Type& operator->() { return data; } - }; - - class IteratorPointer { - protected: - Node* mIter; - public: - IteratorPointer() = default; - Type& operator->() { return (mIter->data); } - const Type& operator->() const { return (mIter->data); } - }; - - class IteratorReference { - protected: - Node* mIter; - public: - IteratorReference() = default; - Type* operator->() { return &(mIter->data); } - const Type* operator->() const { return &(mIter->data); } - }; - - class Iterator : public TypeSelect::isPointer, IteratorPointer, IteratorReference>::Result { - public: - - explicit Iterator(Node* iter) { this->mIter = iter; } - - Node* node() { return this->mIter; } - Type& data() { return this->mIter->data; } - const Node* node() const { return this->mIter; } - const Type& data() const { return this->mIter->data; } - - const Iterator& operator*() const { return *this; } - - Iterator& operator++() { - this->mIter = this->mIter->next; - return *this; - } - - bool operator==(const Iterator& left) const { return left.mIter == this->mIter; } - bool operator!=(const Iterator& left) const { return left.mIter != this->mIter; } - }; - - private: - Node* mFirst = nullptr; - Node* mLast = nullptr; - Index mLength = 0; - Allocator mAlloc; - - public: - - List() = default; - List(const List& in) { this->operator=(in); } - List(const InitialierList& list) { operator=(list); } - - [[nodiscard]] inline Node* first() const { return mFirst; } - [[nodiscard]] inline Node* last() const { return mLast; } - [[nodiscard]] inline Index length() const { return mLength; } - - [[nodiscard]] Node* newNode() { return new (mAlloc.allocate(sizeof(Node))) Node(); } - [[nodiscard]] Node* newNode(TypeArg arg) { return new (mAlloc.allocate(sizeof(Node))) Node(arg); } - [[nodiscard]] Node* newNodeNotConstructed() { - auto node = (Node*) mAlloc.allocate(sizeof(Node)); - node->next = node->prev = nullptr; - return node; - } - - [[nodiscard]] const Allocator& getAllocator() const { return mAlloc; } - - void deleteNode(Node* node) { - node->~Node(); - mAlloc.deallocate(node); - } - - Node* addNodeBack() { - auto const out = newNode(); - pushBack(out); - return out; - } - - Node* addNodeFront() { - auto const out = newNode(); - pushFront(out); - return out; - } - - void attach(Node* node, Node* node_to) { - if (node_to) { - if (node_to->next) { - node->next = node_to->next; - node->next->prev = node; - } - node_to->next = node; - node->prev = node_to; - if (node_to == mLast) { - mLast = node; - } - } else { - if (mFirst) { - mFirst->prev = node; - node->next = mFirst; - mFirst = node; - } else { - mFirst = mLast = node; - } - } - mLength++; - } - - void detach(Node* node) { - if (node->next) { - node->next->prev = node->prev; - } - if (node->prev) { - node->prev->next = node->next; - } - if (node == mLast) { - mLast = mLast->prev; - } - if (node == mFirst) { - mFirst = mFirst->next; - } - mLength--; - } - - [[nodiscard]] Node* findIdx(Index idx) const { - DEBUG_ASSERT(mFirst && idx < mLength && idx >= 0) - Node* found = mFirst; - for (int i = 0; i != idx; i++) { - found = found->next; - } - return found; - } - - [[nodiscard]] Node* find(const TypeArg data) const { - Node* found = mFirst; - for (alni i = 0; data != found->data; i++) { - if (i == length()) return nullptr; - if (!found->next) { - return nullptr; - } - found = found->next; - } - return found; - } - - [[nodiscard]] inline const Type& operator[](Index idx) const { - DEBUG_ASSERT(idx < mLength) - return find(idx)->data; - } - - void pushBack(Node* new_node) { attach(new_node, mLast); } - void pushFront(Node* new_node) { attach(new_node, nullptr); } - void pushBack(TypeArg data) { pushBack(newNode(data)); } - void pushFront(TypeArg data) { pushFront(newNode(data)); } - - void popBack() { - DEBUG_ASSERT(mLast) - auto const tmp = mLast; - detach(mLast); - deleteNode(tmp); - } - - void popFront() { - DEBUG_ASSERT(mFirst) - auto temp = mFirst; - detach(mFirst); - deleteNode(temp); - } - - void insert(Node* node, Index idx) { - if (!mLength) { - attach(node, mLast); - } else if (idx >= mLength) { - attach(node, nullptr); - } else { - attach(node, find(idx)->prev); - } - } - - void insert(TypeArg data, Index idx) { - insert(newNode(data), idx); - } - - void removeNode(Node* node) { - detach(node); - deleteNode(node); - } - - void removeAll() { - while (mFirst) { - popFront(); - } - } - - // copies data - List& operator+=(const List& in) { - for (auto node : in) { - pushBack(node.data()); - } - return *this; - } - - List& operator+=(const InitialierList& list) { - for (auto item : list) { - pushBack(item); - } - return *this; - } - - List& operator=(const List& in) { - if (this == &in) { return *this; } - removeAll(); - (*this) += in; - return *this; - } - - List& operator=(const InitialierList& list) { - removeAll(); - *this += list; - return *this; - } - - [[nodiscard]] bool operator==(const List& in) const { - if (&in == this) { return true; } - if (in.length() != length()) { - return false; - } - Node* left = in.first(); - Node* right = first(); - while (left && right) { - if (left->data != right->data) { - return false; - } - left = left->next; - right = right->next; - } - if (left != right) { - return false; - } - return true; - } - - template - [[nodiscard]] Node* find(bool (*found)(Node* node, compare_val val), compare_val value) const { - for (Node* node = mFirst; node; node = node->next) { - if (found(node, value)) { - return node; - } - } - return nullptr; - } - - [[nodiscard]] Iterator begin() const { - Iterator out(mFirst); - return out; - } - - [[nodiscard]] Iterator end() const { - return Iterator(nullptr); - } - - void invert() { - Node* iter = mFirst; - Node* tmp; - while (iter) { - tmp = iter; - iter = iter->next; - swap(tmp->next, tmp->prev); - } - swap(mFirst, mLast); - } - - void detachAll() { - while (mFirst) { - detach(mFirst); - } - } - - public: - template - void archiveWrite(tArchiver& ar) const { - ar << mLength; - for (auto item : *this) { - ar << item.data(); - } - } - - template - void archiveRead(tArchiver& ar) { - removeAll(); - decltype(mLength) len; - ar >> len; - for (auto i = len; i; i--) { - auto node = newNodeNotConstructed(); - ar >> node->data; - pushBack(node); - } - } - - ~List() { - removeAll(); - } - }; + +#pragma once + +#include "ContainersCommon.hpp" + +#include "TypeInfo.hpp" + +namespace tp { + + template + class List { + + typedef SelectValueOrReference TypeArg; + typedef ualni Index; + + public: + struct Node { + Type data; + Node* next = nullptr; + Node* prev = nullptr; + Node() = default; + explicit Node(TypeArg p_data) : + data(p_data) {} + Type& operator->() { return data; } + }; + + class IteratorPointer { + protected: + Node* mIter; + + public: + IteratorPointer() = default; + Type& operator->() { return (mIter->data); } + const Type& operator->() const { return (mIter->data); } + }; + + class IteratorReference { + protected: + Node* mIter; + + public: + IteratorReference() = default; + Type* operator->() { return &(mIter->data); } + const Type* operator->() const { return &(mIter->data); } + }; + + class Iterator : public TypeSelect::isPointer, IteratorPointer, IteratorReference>::Result { + public: + explicit Iterator(Node* iter) { this->mIter = iter; } + + Node* node() { return this->mIter; } + Type& data() { return this->mIter->data; } + const Node* node() const { return this->mIter; } + const Type& data() const { return this->mIter->data; } + + const Iterator& operator*() const { return *this; } + + Iterator& operator++() { + this->mIter = this->mIter->next; + return *this; + } + + bool operator==(const Iterator& left) const { return left.mIter == this->mIter; } + bool operator!=(const Iterator& left) const { return left.mIter != this->mIter; } + }; + + private: + Node* mFirst = nullptr; + Node* mLast = nullptr; + Index mLength = 0; + Allocator mAlloc; + + public: + List() = default; + List(const List& in) { this->operator=(in); } + List(const InitialierList& list) { operator=(list); } + + [[nodiscard]] inline Node* first() const { return mFirst; } + [[nodiscard]] inline Node* last() const { return mLast; } + [[nodiscard]] inline Index length() const { return mLength; } + + [[nodiscard]] Node* newNode() { return new (mAlloc.allocate(sizeof(Node))) Node(); } + [[nodiscard]] Node* newNode(TypeArg arg) { return new (mAlloc.allocate(sizeof(Node))) Node(arg); } + [[nodiscard]] Node* newNodeNotConstructed() { + auto node = (Node*) mAlloc.allocate(sizeof(Node)); + node->next = node->prev = nullptr; + return node; + } + + [[nodiscard]] const Allocator& getAllocator() const { return mAlloc; } + + void deleteNode(Node* node) { + node->~Node(); + mAlloc.deallocate(node); + } + + Node* addNodeBack() { + auto const out = newNode(); + pushBack(out); + return out; + } + + Node* addNodeFront() { + auto const out = newNode(); + pushFront(out); + return out; + } + + void attach(Node* node, Node* node_to) { + if (node_to) { + if (node_to->next) { + node->next = node_to->next; + node->next->prev = node; + } + node_to->next = node; + node->prev = node_to; + if (node_to == mLast) { + mLast = node; + } + } else { + if (mFirst) { + mFirst->prev = node; + node->next = mFirst; + mFirst = node; + } else { + mFirst = mLast = node; + } + } + mLength++; + } + + void detach(Node* node) { + if (node->next) { + node->next->prev = node->prev; + } + if (node->prev) { + node->prev->next = node->next; + } + if (node == mLast) { + mLast = mLast->prev; + } + if (node == mFirst) { + mFirst = mFirst->next; + } + mLength--; + } + + [[nodiscard]] Node* findIdx(Index idx) const { + DEBUG_ASSERT(mFirst && idx < mLength && idx >= 0) + Node* found = mFirst; + for (int i = 0; i != idx; i++) { + found = found->next; + } + return found; + } + + [[nodiscard]] Node* find(const TypeArg data) const { + Node* found = mFirst; + for (alni i = 0; data != found->data; i++) { + if (i == length()) return nullptr; + if (!found->next) { + return nullptr; + } + found = found->next; + } + return found; + } + + [[nodiscard]] inline const Type& operator[](Index idx) const { + DEBUG_ASSERT(idx < mLength) + return find(idx)->data; + } + + void pushBack(Node* new_node) { attach(new_node, mLast); } + void pushFront(Node* new_node) { attach(new_node, nullptr); } + void pushBack(TypeArg data) { pushBack(newNode(data)); } + void pushFront(TypeArg data) { pushFront(newNode(data)); } + + void popBack() { + DEBUG_ASSERT(mLast) + auto const tmp = mLast; + detach(mLast); + deleteNode(tmp); + } + + void popFront() { + DEBUG_ASSERT(mFirst) + auto temp = mFirst; + detach(mFirst); + deleteNode(temp); + } + + void insert(Node* node, Index idx) { + if (!mLength) { + attach(node, mLast); + } else if (idx >= mLength) { + attach(node, nullptr); + } else { + attach(node, find(idx)->prev); + } + } + + void insert(TypeArg data, Index idx) { insert(newNode(data), idx); } + + void removeNode(Node* node) { + detach(node); + deleteNode(node); + } + + void removeAll() { + while (mFirst) { + popFront(); + } + } + + // copies data + List& operator+=(const List& in) { + for (auto node : in) { + pushBack(node.data()); + } + return *this; + } + + List& operator+=(const InitialierList& list) { + for (auto item : list) { + pushBack(item); + } + return *this; + } + + List& operator=(const List& in) { + if (this == &in) { + return *this; + } + removeAll(); + (*this) += in; + return *this; + } + + List& operator=(const InitialierList& list) { + removeAll(); + *this += list; + return *this; + } + + [[nodiscard]] bool operator==(const List& in) const { + if (&in == this) { + return true; + } + if (in.length() != length()) { + return false; + } + Node* left = in.first(); + Node* right = first(); + while (left && right) { + if (left->data != right->data) { + return false; + } + left = left->next; + right = right->next; + } + if (left != right) { + return false; + } + return true; + } + + template + [[nodiscard]] Node* find(bool (*found)(Node* node, compare_val val), compare_val value) const { + for (Node* node = mFirst; node; node = node->next) { + if (found(node, value)) { + return node; + } + } + return nullptr; + } + + [[nodiscard]] Iterator begin() const { + Iterator out(mFirst); + return out; + } + + [[nodiscard]] Iterator end() const { return Iterator(nullptr); } + + void invert() { + Node* iter = mFirst; + Node* tmp; + while (iter) { + tmp = iter; + iter = iter->next; + swap(tmp->next, tmp->prev); + } + swap(mFirst, mLast); + } + + void detachAll() { + while (mFirst) { + detach(mFirst); + } + } + + public: + template + void archiveWrite(tArchiver& ar) const { + ar << mLength; + for (auto item : *this) { + ar << item.data(); + } + } + + template + void archiveRead(tArchiver& ar) { + removeAll(); + decltype(mLength) len; + ar >> len; + for (auto i = len; i; i--) { + auto node = newNodeNotConstructed(); + ar >> node->data; + pushBack(node); + } + } + + ~List() { removeAll(); } + }; } \ No newline at end of file diff --git a/Containers/public/Map.hpp b/Containers/public/Map.hpp index 2c398c4..70e15e0 100644 --- a/Containers/public/Map.hpp +++ b/Containers/public/Map.hpp @@ -1,405 +1,378 @@ - -#pragma once - -#include "ContainersCommon.hpp" -#include "Common.hpp" - -namespace tp { - - template - ualni DefaultHashFunc(SelectValueOrReference key) { - return hash(key); - } - - template) = DefaultHashFunc, int tTableInitialSize = 4> - class Map { - - enum { - MAP_PERTURB_SHIFT = 5, - MAP_MIN_SIZE = 4, - MAP_MAX_LOAD_PERCENTAGE = 66, - }; - - typedef SelectValueOrReference KeyArg; - typedef SelectValueOrReference ValArg; - - public: - - class Node { - friend Map; - Node(KeyArg aKey, ValArg aVal) : key(aKey), val(aVal) {} - public: - tKey key; - tVal val; - }; - - struct Idx { - alni idx = -1; - [[nodiscard]] bool isValid() const { return bool(*this); } - explicit operator bool() const { return idx != -1; } - }; - - private: - tAllocator mAlloc; - Node** mTable = nullptr; - ualni mNSlots = 0; - ualni mNEntries = 0; - - private: - - constexpr halnf maxLoadFactor() { return halnf(MAP_MAX_LOAD_PERCENTAGE) / 100.f; } - - inline Node** newTable(const ualni len) { - return new(mAlloc.allocate(sizeof(Node*) * len)) Node*[len](); - } - - inline Node* newNode(KeyArg key, ValArg val) { - return new(mAlloc.allocate(sizeof(Node))) Node(key, val); - } - - inline Node* newNodeNotConstructed() { - return (Node*) mAlloc.allocate(sizeof(Node)); - } - - inline void deleteTable(Node** table) { - mAlloc.deallocate(table); - } - - inline void deleteNode(Node* p) { - p->~Node(); - mAlloc.deallocate(p); - } - - void markDeletedSlot(ualni idx) const { - mTable[idx] = (Node*)-1; - } - - static bool isDeletedNode(Node* node) { - return node == (Node*)-1; - } - - void rehash() { - alni nSlotsOld = mNSlots; - Node** tableOld = mTable; - - mNSlots = next2pow((uhalni)((1.f / (maxLoadFactor())) * mNEntries + 1)); - mTable = newTable(mNSlots); - mNEntries = 0; - - for (alni i = 0; i < nSlotsOld; i++) { - if (!tableOld[i] || isDeletedNode(tableOld[i])) { - continue; - } - - alni idx = findSlotWrite(tableOld[i]->key); - mTable[idx] = tableOld[i]; - mNEntries++; - } - - deleteTable(tableOld); - } - - alni findSlotRead(KeyArg key) const { - ualni const hashed_key = tHashFunc(key); - ualni const mask = mNSlots - 1; - ualni const shift = (hashed_key >> MAP_PERTURB_SHIFT) & ~1; - alni idx = hashed_key & mask; - NEXT: - if (isDeletedNode(mTable[idx])) { - goto SKIP; - } - if (!mTable[idx]) { - return -1; - } - if (mTable[idx]->key == key) { - return idx; - } - SKIP: - idx = ((5 * idx) + 1 + shift) & mask; - goto NEXT; - } - - // compares keys only when collisions occur - alni findSlotReadExisting(KeyArg key) const { - ualni const hashed_key = tHashFunc(key); - ualni const mask = mNSlots - 1; - ualni const shift = (hashed_key >> MAP_PERTURB_SHIFT) & ~1; - alni idx = hashed_key & mask; - NEXT: - if (isDeletedNode(mTable[idx])) { - goto SKIP; - } - if (!mTable[idx]) { - return -1; - } - if (mTable[((5 * idx) + 1 + shift) & mask] == nullptr) { - return idx; - } - if (mTable[idx]->key == key) { - return idx; - } - SKIP: - idx = ((5 * idx) + 1 + shift) & mask; - goto NEXT; - } - - ualni findSlotWrite(KeyArg key) const { - ualni const hashed_key = tHashFunc(key); - ualni const mask = mNSlots - 1; - ualni const shift = (hashed_key >> MAP_PERTURB_SHIFT) & ~1; - ualni idx = hashed_key & mask; - NEXT: - if (isDeletedNode(mTable[idx]) || !mTable[idx]) { - return idx; - } - if (mTable[idx]->key == key) { - return idx; - } - idx = ((5 * idx) + 1 + shift) & mask; - goto NEXT; - } - - void put(Node* node) { - const ualni idx = findSlotWrite(node->key); - - if (!mTable[idx] || isDeletedNode(mTable[idx])) { - mNEntries++; - } - - mTable[idx] = node; - - if ((halnf)mNEntries / mNSlots > maxLoadFactor()) { - rehash(); - } - } - - public: - - Map() { - MODULE_SANITY_CHECK(gModuleContainers) - mNSlots = next2pow(uhalni(tTableInitialSize - 1)); - mTable = newTable(mNSlots); - } - - Map(const Map& in) { - this->operator=(in); - } - - Node** buff() const { - return mTable; - } - - [[nodiscard]] ualni size() const { - return mNEntries; - } - - [[nodiscard]] ualni slotsSize() const { - return mNEntries; - } - - [[nodiscard]] const tAllocator& getAllocator() const { - return mAlloc; - } - - void put(KeyArg key, ValArg val) { - const ualni idx = findSlotWrite(key); - if (!mTable[idx] || isDeletedNode(mTable[idx])) { - mTable[idx] = newNode(key, val); - mNEntries++; - } else { - mTable[idx]->val = val; - } - if ((halnf) mNEntries / mNSlots > maxLoadFactor()) { - rehash(); - } - } - - // undefined behavior if item is not presents - tVal& get(KeyArg key) { - DEBUG_ASSERT(findSlotRead(key) != -1 && "Key Error") - return mTable[findSlotReadExisting(key)]->val; - } - - const tVal& get(KeyArg key) const { - DEBUG_ASSERT(findSlotRead(key) != -1 && "Key Error") - return mTable[findSlotReadExisting(key)]->val; - } - - [[nodiscard]] Idx presents(KeyArg key) const { return { findSlotRead(key) }; } - - void remove(KeyArg key) { - DEBUG_ASSERT(findSlotRead(key) != -1 && "Key Error") - auto idx = findSlotReadExisting(key); - - deleteNode(mTable[idx]); - - markDeletedSlot(idx); - - mNEntries--; - if (halnf(mNEntries / mNSlots) < 1.f - maxLoadFactor()) { - rehash(); - } - } - - const tVal& getSlotVal(ualni slot) const { - DEBUG_ASSERT(slot < mNSlots && (mTable[slot] && !isDeletedNode(mTable[slot])) && "Key Error") - return mTable[slot]->val; - } - - tVal& getSlotVal(ualni slot) { - DEBUG_ASSERT(slot < mNSlots && (mTable[slot] && !isDeletedNode(mTable[slot])) && "Key Error") - return mTable[slot]->val; - } - - const tVal& getSlotVal(Idx slot) const { - DEBUG_ASSERT(slot.idx < mNSlots && (mTable[slot.idx] && !isDeletedNode(mTable[slot.idx])) && "Key Error") - return mTable[slot.idx]->val; - } - - tVal& getSlotVal(Idx slot) { - DEBUG_ASSERT(slot.idx < mNSlots && (mTable[slot.idx] && !isDeletedNode(mTable[slot.idx])) && "Key Error") - return mTable[slot.idx]->val; - } - - Map& operator=(const Map& in) { - if (this == &in) { - return *this; - } - removeAll(); - mNSlots = in.mNSlots; - mTable = newTable(mNSlots); - for (alni i = 0; i < mNSlots; i++) { - if (in.mTable[i] && !isDeletedNode(in.mTable[i])) { - put(in.mTable[i]->key, in.mTable[i]->val); - } - } - return *this; - } - - [[nodiscard]] bool operator==(const Map& in) const { - if (this == &in) { - return true; - } - if (in.mNEntries != mNEntries) { - return false; - } - for (auto i : in) { - if (!presents(i->key) || get(i->key) != i->val) { - return false; - } - } - return true; - } - - void removeAll() { - for (ualni i = 0; i < mNSlots; i++) { - if (mTable[i] && !isDeletedNode(mTable[i])) { - deleteNode(mTable[i]); - } - } - deleteTable(mTable); - mTable = newTable(tTableInitialSize); - mNSlots = tTableInitialSize; - mNEntries = 0; - } - - [[nodiscard]] alni slotIdx(alni entry_idx_in) const { - alni entry_idx = -1; - for (alni slot_idx = 0; slot_idx < mNSlots; slot_idx++) { - if (mTable[slot_idx]) { - entry_idx++; - } - if (entry_idx == entry_idx_in) { - return slot_idx; - } - } - return -1; - } - - Node* GetEntry(ualni idx) { - auto slot = slotIdx(idx); - DEBUG_ASSERT(slot != -1 && "Key error") - return mTable[slot]; - } - - const Node* GetEntry(ualni idx) const { - auto slot = slotIdx(idx); - DEBUG_ASSERT(slot != -1 && "Key error") - return mTable[slot]; - } - - public: - - class Iterator { - const Map* map; - Node* mIter; - alni mSlot; - alni mEntry; - - friend Map; - explicit Iterator(const Map* _map) { - mSlot = -1; - mEntry = -1; - map = _map; - this->operator++(); - } - - public: - Node* operator->() { return mIter; } - const Node* operator->() const { return mIter; } - const Iterator& operator*() const { return *this; } - - bool operator!=(ualni idx) const { return mSlot != idx; } - - void operator++() { - mSlot++; - while ((map->isDeletedNode(map->mTable[mSlot]) || !map->mTable[mSlot]) && (mSlot != map->mNSlots)) { - mSlot++; - } - if (mSlot != map->mNSlots) { - mIter = map->mTable[mSlot]; - mEntry++; - } - } - }; - - [[nodiscard]] Iterator begin() const { - return Iterator(this); - } - - [[nodiscard]] ualni end() const { - return mNSlots; - } - - template - void archiveWrite(Archiver& ar) const { - ar << mNEntries; - for (auto item : *this) { - ar << item->val; - ar << item->key; - } - } - - template - void archiveRead(Archiver& ar) { - removeAll(); - decltype(mNSlots) len; - ar >> len; - for (auto i = len; i; i--) { - auto node = newNodeNotConstructed(); - ar >> node->val; - ar >> node->key; - put(node); - } - } - - ~Map() { - for (ualni i = 0; i < mNSlots; i++) { - if (mTable[i] && !isDeletedNode(mTable[i])) { - deleteNode(mTable[i]); - } - } - deleteTable(mTable); - } - }; + +#pragma once + +#include "Common.hpp" +#include "ContainersCommon.hpp" + +namespace tp { + + template + ualni DefaultHashFunc(SelectValueOrReference key) { + return hash(key); + } + + template ) = DefaultHashFunc, int tTableInitialSize = 4> + class Map { + + enum { + MAP_PERTURB_SHIFT = 5, + MAP_MIN_SIZE = 4, + MAP_MAX_LOAD_PERCENTAGE = 66, + }; + + typedef SelectValueOrReference KeyArg; + typedef SelectValueOrReference ValArg; + + public: + class Node { + friend Map; + Node(KeyArg aKey, ValArg aVal) : + key(aKey), + val(aVal) {} + + public: + tKey key; + tVal val; + }; + + struct Idx { + alni idx = -1; + [[nodiscard]] bool isValid() const { return bool(*this); } + explicit operator bool() const { return idx != -1; } + }; + + private: + tAllocator mAlloc; + Node** mTable = nullptr; + ualni mNSlots = 0; + ualni mNEntries = 0; + + private: + constexpr halnf maxLoadFactor() { return halnf(MAP_MAX_LOAD_PERCENTAGE) / 100.f; } + + inline Node** newTable(const ualni len) { return new (mAlloc.allocate(sizeof(Node*) * len)) Node*[len](); } + + inline Node* newNode(KeyArg key, ValArg val) { return new (mAlloc.allocate(sizeof(Node))) Node(key, val); } + + inline Node* newNodeNotConstructed() { return (Node*) mAlloc.allocate(sizeof(Node)); } + + inline void deleteTable(Node** table) { mAlloc.deallocate(table); } + + inline void deleteNode(Node* p) { + p->~Node(); + mAlloc.deallocate(p); + } + + void markDeletedSlot(ualni idx) const { mTable[idx] = (Node*) -1; } + + static bool isDeletedNode(Node* node) { return node == (Node*) -1; } + + void rehash() { + alni nSlotsOld = mNSlots; + Node** tableOld = mTable; + + mNSlots = next2pow((uhalni) ((1.f / (maxLoadFactor())) * mNEntries + 1)); + mTable = newTable(mNSlots); + mNEntries = 0; + + for (alni i = 0; i < nSlotsOld; i++) { + if (!tableOld[i] || isDeletedNode(tableOld[i])) { + continue; + } + + alni idx = findSlotWrite(tableOld[i]->key); + mTable[idx] = tableOld[i]; + mNEntries++; + } + + deleteTable(tableOld); + } + + alni findSlotRead(KeyArg key) const { + ualni const hashed_key = tHashFunc(key); + ualni const mask = mNSlots - 1; + ualni const shift = (hashed_key >> MAP_PERTURB_SHIFT) & ~1; + alni idx = hashed_key & mask; + NEXT: + if (isDeletedNode(mTable[idx])) { + goto SKIP; + } + if (!mTable[idx]) { + return -1; + } + if (mTable[idx]->key == key) { + return idx; + } + SKIP: + idx = ((5 * idx) + 1 + shift) & mask; + goto NEXT; + } + + // compares keys only when collisions occur + alni findSlotReadExisting(KeyArg key) const { + ualni const hashed_key = tHashFunc(key); + ualni const mask = mNSlots - 1; + ualni const shift = (hashed_key >> MAP_PERTURB_SHIFT) & ~1; + alni idx = hashed_key & mask; + NEXT: + if (isDeletedNode(mTable[idx])) { + goto SKIP; + } + if (!mTable[idx]) { + return -1; + } + if (mTable[((5 * idx) + 1 + shift) & mask] == nullptr) { + return idx; + } + if (mTable[idx]->key == key) { + return idx; + } + SKIP: + idx = ((5 * idx) + 1 + shift) & mask; + goto NEXT; + } + + ualni findSlotWrite(KeyArg key) const { + ualni const hashed_key = tHashFunc(key); + ualni const mask = mNSlots - 1; + ualni const shift = (hashed_key >> MAP_PERTURB_SHIFT) & ~1; + ualni idx = hashed_key & mask; + NEXT: + if (isDeletedNode(mTable[idx]) || !mTable[idx]) { + return idx; + } + if (mTable[idx]->key == key) { + return idx; + } + idx = ((5 * idx) + 1 + shift) & mask; + goto NEXT; + } + + void put(Node* node) { + const ualni idx = findSlotWrite(node->key); + + if (!mTable[idx] || isDeletedNode(mTable[idx])) { + mNEntries++; + } + + mTable[idx] = node; + + if ((halnf) mNEntries / mNSlots > maxLoadFactor()) { + rehash(); + } + } + + public: + Map() { + MODULE_SANITY_CHECK(gModuleContainers) + mNSlots = next2pow(uhalni(tTableInitialSize - 1)); + mTable = newTable(mNSlots); + } + + Map(const Map& in) { this->operator=(in); } + + Node** buff() const { return mTable; } + + [[nodiscard]] ualni size() const { return mNEntries; } + + [[nodiscard]] ualni slotsSize() const { return mNEntries; } + + [[nodiscard]] const tAllocator& getAllocator() const { return mAlloc; } + + void put(KeyArg key, ValArg val) { + const ualni idx = findSlotWrite(key); + if (!mTable[idx] || isDeletedNode(mTable[idx])) { + mTable[idx] = newNode(key, val); + mNEntries++; + } else { + mTable[idx]->val = val; + } + if ((halnf) mNEntries / mNSlots > maxLoadFactor()) { + rehash(); + } + } + + // undefined behavior if item is not presents + tVal& get(KeyArg key) { + DEBUG_ASSERT(findSlotRead(key) != -1 && "Key Error") + return mTable[findSlotReadExisting(key)]->val; + } + + const tVal& get(KeyArg key) const { + DEBUG_ASSERT(findSlotRead(key) != -1 && "Key Error") + return mTable[findSlotReadExisting(key)]->val; + } + + [[nodiscard]] Idx presents(KeyArg key) const { return { findSlotRead(key) }; } + + void remove(KeyArg key) { + DEBUG_ASSERT(findSlotRead(key) != -1 && "Key Error") + auto idx = findSlotReadExisting(key); + + deleteNode(mTable[idx]); + + markDeletedSlot(idx); + + mNEntries--; + if (halnf(mNEntries / mNSlots) < 1.f - maxLoadFactor()) { + rehash(); + } + } + + const tVal& getSlotVal(ualni slot) const { + DEBUG_ASSERT(slot < mNSlots && (mTable[slot] && !isDeletedNode(mTable[slot])) && "Key Error") + return mTable[slot]->val; + } + + tVal& getSlotVal(ualni slot) { + DEBUG_ASSERT(slot < mNSlots && (mTable[slot] && !isDeletedNode(mTable[slot])) && "Key Error") + return mTable[slot]->val; + } + + const tVal& getSlotVal(Idx slot) const { + DEBUG_ASSERT(slot.idx < mNSlots && (mTable[slot.idx] && !isDeletedNode(mTable[slot.idx])) && "Key Error") + return mTable[slot.idx]->val; + } + + tVal& getSlotVal(Idx slot) { + DEBUG_ASSERT(slot.idx < mNSlots && (mTable[slot.idx] && !isDeletedNode(mTable[slot.idx])) && "Key Error") + return mTable[slot.idx]->val; + } + + Map& operator=(const Map& in) { + if (this == &in) { + return *this; + } + removeAll(); + mNSlots = in.mNSlots; + mTable = newTable(mNSlots); + for (alni i = 0; i < mNSlots; i++) { + if (in.mTable[i] && !isDeletedNode(in.mTable[i])) { + put(in.mTable[i]->key, in.mTable[i]->val); + } + } + return *this; + } + + [[nodiscard]] bool operator==(const Map& in) const { + if (this == &in) { + return true; + } + if (in.mNEntries != mNEntries) { + return false; + } + for (auto i : in) { + if (!presents(i->key) || get(i->key) != i->val) { + return false; + } + } + return true; + } + + void removeAll() { + for (ualni i = 0; i < mNSlots; i++) { + if (mTable[i] && !isDeletedNode(mTable[i])) { + deleteNode(mTable[i]); + } + } + deleteTable(mTable); + mTable = newTable(tTableInitialSize); + mNSlots = tTableInitialSize; + mNEntries = 0; + } + + [[nodiscard]] alni slotIdx(alni entry_idx_in) const { + alni entry_idx = -1; + for (alni slot_idx = 0; slot_idx < mNSlots; slot_idx++) { + if (mTable[slot_idx]) { + entry_idx++; + } + if (entry_idx == entry_idx_in) { + return slot_idx; + } + } + return -1; + } + + Node* GetEntry(ualni idx) { + auto slot = slotIdx(idx); + DEBUG_ASSERT(slot != -1 && "Key error") + return mTable[slot]; + } + + const Node* GetEntry(ualni idx) const { + auto slot = slotIdx(idx); + DEBUG_ASSERT(slot != -1 && "Key error") + return mTable[slot]; + } + + public: + class Iterator { + const Map* map; + Node* mIter; + alni mSlot; + alni mEntry; + + friend Map; + explicit Iterator(const Map* _map) { + mSlot = -1; + mEntry = -1; + map = _map; + this->operator++(); + } + + public: + Node* operator->() { return mIter; } + const Node* operator->() const { return mIter; } + const Iterator& operator*() const { return *this; } + + bool operator!=(ualni idx) const { return mSlot != idx; } + + void operator++() { + mSlot++; + while ((map->isDeletedNode(map->mTable[mSlot]) || !map->mTable[mSlot]) && (mSlot != map->mNSlots)) { + mSlot++; + } + if (mSlot != map->mNSlots) { + mIter = map->mTable[mSlot]; + mEntry++; + } + } + }; + + [[nodiscard]] Iterator begin() const { return Iterator(this); } + + [[nodiscard]] ualni end() const { return mNSlots; } + + template + void archiveWrite(Archiver& ar) const { + ar << mNEntries; + for (auto item : *this) { + ar << item->val; + ar << item->key; + } + } + + template + void archiveRead(Archiver& ar) { + removeAll(); + decltype(mNSlots) len; + ar >> len; + for (auto i = len; i; i--) { + auto node = newNodeNotConstructed(); + ar >> node->val; + ar >> node->key; + put(node); + } + } + + ~Map() { + for (ualni i = 0; i < mNSlots; i++) { + if (mTable[i] && !isDeletedNode(mTable[i])) { + deleteNode(mTable[i]); + } + } + deleteTable(mTable); + } + }; } \ No newline at end of file diff --git a/Containers/public/Tree.hpp b/Containers/public/Tree.hpp index 2dd1ec7..9506b16 100644 --- a/Containers/public/Tree.hpp +++ b/Containers/public/Tree.hpp @@ -1,400 +1,375 @@ -#pragma once - -#include "ContainersCommon.hpp" - -namespace tp { - - template - struct AvlNumericKey { - - NumericType val; - - AvlNumericKey() = default; - AvlNumericKey(NumericType val) : val(val) {} - - inline bool descentRight(AvlNumericKey in) const { return in.val > val; } - inline bool descentLeft(AvlNumericKey in) const { return in.val < val; } - inline bool exactNode(AvlNumericKey in) const { return in.val == val; } - - inline AvlNumericKey getFindKey(/**/) const { return *this; } - inline AvlNumericKey keyInRightSubtree(AvlNumericKey in) const { return in; } - inline AvlNumericKey keyInLeftSubtree(AvlNumericKey in) const { return in; } - - inline void updateTreeCacheCallBack() {} - }; - - template - class AvlTree { - typedef SelectValueOrReference KeyArg; - typedef SelectValueOrReference DataArg; - - public: - class Node { - friend AvlTree; - - private: - Node(KeyArg aKey, DataArg aData) : key(aKey), data(aData) {} - - public: - Data data; - Key key; - - private: - Node* mLeft = nullptr; - Node* mRight = nullptr; - Node* mParent = nullptr; - ualni mHeight = 0; - - private: - inline bool descentRight(KeyArg aKey) const { return key.descentRight(aKey); } - inline bool descentLeft(KeyArg aKey) const { return key.descentLeft(aKey); } - inline bool exactNode(KeyArg aKey) const { return key.exactNode(aKey); } - - inline KeyArg getFindKey(const Node* node = nullptr) const { return key.getFindKey(/*node*/); } - inline KeyArg keyInRightSubtree(KeyArg aKey) const { return key.keyInRightSubtree(aKey); } - inline KeyArg keyInLeftSubtree(KeyArg aKey) const { return key.keyInLeftSubtree(aKey); } - - inline void updateTreeCacheCallBack() { key.updateTreeCacheCallBack(); } - }; - - private: - Node* mRoot = nullptr; - ualni mSize = 0; - Allocator mAlloc; - - private: - - inline void deleteNode(Node* node) { - node->~Node(); - mAlloc.deallocate(node); - } - - inline Node* newNode(KeyArg key, DataArg data) { - return new (mAlloc.allocate(sizeof(Node))) Node(key, data); - } - - inline void injectNodeInstead(Node* place, Node* inject) { - // TODO : swap instead of copy - place->data = inject->data; - place->key = inject->key; - } - - inline alni getNodeHeight(const Node* node) const { - return node ? node->mHeight : -1; - } - - // returns new head - Node* rotateLeft(Node* pivot) { - DEBUG_ASSERT(pivot); - - Node* const head = pivot; - Node* const right = pivot->mRight; - Node* const right_left = right->mLeft; - Node* const parent = pivot->mParent; - - // parents - if (right_left) right_left->mParent = head; - head->mParent = right; - right->mParent = parent; - - // children - head->mRight = right_left; - right->mLeft = head; - - // heights - head->mHeight = 1 + max(getNodeHeight(head->mLeft), getNodeHeight(head->mRight)); - right->mHeight = 1 + max(getNodeHeight(right->mLeft), getNodeHeight(right->mRight)); - - // cache - head->updateTreeCacheCallBack(); - right->updateTreeCacheCallBack(); - - return right; - } - - Node* rotateRight(Node* pivot) { - DEBUG_ASSERT(pivot); - - Node* const head = pivot; - Node* const left = pivot->mLeft; - Node* const left_right = left->mRight; - Node* const parent = pivot->mParent; - - // parents - if (left_right) left_right->mParent = head; - head->mParent = left; - left->mParent = parent; - - // children - head->mLeft = left_right; - left->mRight = head; - - // heights - head->mHeight = 1 + max(getNodeHeight(head->mLeft), getNodeHeight(head->mRight)); - left->mHeight = 1 + max(getNodeHeight(left->mLeft), getNodeHeight(left->mRight)); - - // cache - head->updateTreeCacheCallBack(); - left->updateTreeCacheCallBack(); - - return left; - } - - // recursively returns valid isLeft or isRight child or root - Node* insertUtil(Node* head, KeyArg key, DataArg data) { - - Node* insertedNode; - - if (head == nullptr) { - mSize++; - Node* out = newNode(key, data); - out->updateTreeCacheCallBack(); - return out; - } - else if (head->exactNode(key)) { - return head; - } - else if (head->descentRight(key)) { - insertedNode = insertUtil(head->mRight, head->keyInRightSubtree(key), data); - head->mRight = insertedNode; - insertedNode->mParent = head; - } - else { - insertedNode = insertUtil(head->mLeft, head->keyInLeftSubtree(key), data); - head->mLeft = insertedNode; - insertedNode->mParent = head; - } - - // update height - head->mHeight = 1 + max(getNodeHeight(head->mRight), getNodeHeight(head->mLeft)); - - alni balance = alni(getNodeHeight(head->mRight) - getNodeHeight(head->mLeft)); - - if (balance > 1) { - if (head->mRight->descentRight(head->keyInRightSubtree(key))) { - return rotateLeft(head); - } - else { - head->mRight = rotateRight(head->mRight); - return rotateLeft(head); - } - } - else if (balance < -1) { - if (head->mLeft->descentLeft(head->keyInLeftSubtree(key))) { - return rotateRight(head); - } - else { - head->mLeft = rotateLeft(head->mLeft); - return rotateRight(head); - } - } - - head->updateTreeCacheCallBack(); - - return head; - } - - Node* removeUtil(Node* head, KeyArg key) { - if (head == nullptr) return head; - - if (head->exactNode(key)) { - if (head->mRight && head->mLeft) { - Node* min = minNode(head->mRight); - auto const& newKey = min->getFindKey(head->mRight); - injectNodeInstead(head, min); - head->mRight = removeUtil(head->mRight, newKey); - } - else if (head->mRight) { - injectNodeInstead(head, head->mRight); - deleteNode(head->mRight); - head->mRight = nullptr; - mSize--; - } - else if (head->mLeft) { - injectNodeInstead(head, head->mLeft); - deleteNode(head->mLeft); - head->mLeft = nullptr; - mSize--; - } - else { - deleteNode(head); - mSize--; - head = nullptr; - } - } - else if (head->descentRight(key)) { - head->mRight = removeUtil(head->mRight, head->keyInRightSubtree(key)); - } - else if (head->descentLeft(key)) { - head->mLeft = removeUtil(head->mLeft, head->keyInLeftSubtree(key)); - } - - if (head == nullptr) return head; - - head->mHeight = 1 + max(getNodeHeight(head->mRight), getNodeHeight(head->mLeft)); - alni balance = getNodeHeight(head->mRight) - getNodeHeight(head->mLeft); - - if (balance < -1) { - if (getNodeHeight(head->mLeft->mLeft) >= getNodeHeight(head->mLeft->mRight)) { - return rotateRight(head); - } - else { - head->mLeft = rotateLeft(head->mLeft); - return rotateRight(head); - } - } - else if (balance > 1) { - if (getNodeHeight(head->mRight->mRight) >= getNodeHeight(head->mRight->mLeft)) { - return rotateLeft(head); - } - else { - head->mRight = rotateRight(head->mRight); - return rotateLeft(head); - } - } - - head->updateTreeCacheCallBack(); - - return head; - } - - public: - - AvlTree() { - MODULE_SANITY_CHECK(gModuleContainers) - } - - [[nodiscard]] ualni size() const { - return mSize; - } - - Node* head() const { - return this->mRoot; - } - - void insert(KeyArg key, DataArg data) { - mRoot = insertUtil(mRoot, key, data); - mRoot->mParent = nullptr; - } - - void remove(KeyArg key) { - mRoot = removeUtil(mRoot, key); - if (mRoot) mRoot->mParent = nullptr; - } - - Node* maxNode(Node* head) const { - if (!head) return nullptr; - while (head->mRight != nullptr) { - head = head->mRight; - } - return head; - } - - Node* minNode(Node* head) const { - if (!head) return nullptr; - while (head->mLeft != nullptr) { - head = head->mLeft; - } - return head; - } - - Node* find(KeyArg key) const { - Node* iter = mRoot; - while (true) { - if (!iter) return nullptr; - if (iter->exactNode(key)) return iter; - if (iter->descentLeft(key)) { - key = iter->keyInLeftSubtree(key); - iter = iter->mLeft; - } else { - key = iter->keyInRightSubtree(key); - iter = iter->mRight; - } - } - } - - Node* findLessOrEq(KeyArg key) const { - Node* iter = mRoot; - while (true) { - if (!iter) return nullptr; - if (iter->exactNode(key)) return iter; - if (iter->descentLeft(key)) { - if (iter->mLeft) { - key = iter->keyInLeftSubtree(key); - iter = iter->mLeft; - } else { - return iter; - } - } else { - if (iter->mRight) { - key = iter->keyInRightSubtree(key); - iter = iter->mRight; - } else { - return iter; - } - } - } - } - - // returns first invalid node - const Node* findInvalidNode(const Node* head) const { - if (head == nullptr) return nullptr; - - if (head->mLeft) { - // TODO: incomplete test - if (!head->descentLeft(head->mLeft->getFindKey(head))) return head; - if (head->mLeft->mParent != head) return head; - if (!head->mRight && head->mLeft->mHeight != head->mHeight - 1) return head; - } - - if (head->mRight) { - if (!head->descentRight(head->mRight->getFindKey(head))) return head; - if (head->mRight->mParent != head) return head; - if (!head->mLeft && head->mRight->mHeight != head->mHeight - 1) return head; - } - - if (head->mLeft && head->mRight) { - if (max(head->mLeft->mHeight, head->mRight->mHeight) != head->mHeight - 1) return head; - } - - int balance = getNodeHeight(head->mRight) - getNodeHeight(head->mLeft); - - if (balance > 1 || balance < -1) return head; - - const Node* ret = findInvalidNode(head->mRight); - - if (ret) return ret; - - return findInvalidNode(head->mLeft); - } - - bool isValid() { return findInvalidNode(head()) == nullptr; } - - template - void traverse(Node* node, bool after, tFunctor functor) { - if (!after) functor(node); - if (node->mLeft) traverse(node->mLeft, after, functor); - if (node->mRight) traverse(node->mRight, after, functor); - if (after) functor(node); - } - - void removeAll() { - traverse(mRoot, true, [this](Node* node) { - deleteNode(node); - }); - mRoot = nullptr; - mSize = 0; - } - - public: - template - void archiveWrite(tArchiver& file) const { - FAIL("not implemented") - } - - template - void archiveRead(tArchiver&) { - FAIL("not implemented") - } - }; +#pragma once + +#include "ContainersCommon.hpp" + +namespace tp { + + template + struct AvlNumericKey { + + NumericType val; + + AvlNumericKey() = default; + AvlNumericKey(NumericType val) : + val(val) {} + + inline bool descentRight(AvlNumericKey in) const { return in.val > val; } + inline bool descentLeft(AvlNumericKey in) const { return in.val < val; } + inline bool exactNode(AvlNumericKey in) const { return in.val == val; } + + inline AvlNumericKey getFindKey(/**/) const { return *this; } + inline AvlNumericKey keyInRightSubtree(AvlNumericKey in) const { return in; } + inline AvlNumericKey keyInLeftSubtree(AvlNumericKey in) const { return in; } + + inline void updateTreeCacheCallBack() {} + }; + + template + class AvlTree { + typedef SelectValueOrReference KeyArg; + typedef SelectValueOrReference DataArg; + + public: + class Node { + friend AvlTree; + + private: + Node(KeyArg aKey, DataArg aData) : + key(aKey), + data(aData) {} + + public: + Data data; + Key key; + + private: + Node* mLeft = nullptr; + Node* mRight = nullptr; + Node* mParent = nullptr; + ualni mHeight = 0; + + private: + inline bool descentRight(KeyArg aKey) const { return key.descentRight(aKey); } + inline bool descentLeft(KeyArg aKey) const { return key.descentLeft(aKey); } + inline bool exactNode(KeyArg aKey) const { return key.exactNode(aKey); } + + inline KeyArg getFindKey(const Node* node = nullptr) const { return key.getFindKey(/*node*/); } + inline KeyArg keyInRightSubtree(KeyArg aKey) const { return key.keyInRightSubtree(aKey); } + inline KeyArg keyInLeftSubtree(KeyArg aKey) const { return key.keyInLeftSubtree(aKey); } + + inline void updateTreeCacheCallBack() { key.updateTreeCacheCallBack(); } + }; + + private: + Node* mRoot = nullptr; + ualni mSize = 0; + Allocator mAlloc; + + private: + inline void deleteNode(Node* node) { + node->~Node(); + mAlloc.deallocate(node); + } + + inline Node* newNode(KeyArg key, DataArg data) { return new (mAlloc.allocate(sizeof(Node))) Node(key, data); } + + inline void injectNodeInstead(Node* place, Node* inject) { + // TODO : swap instead of copy + place->data = inject->data; + place->key = inject->key; + } + + inline alni getNodeHeight(const Node* node) const { return node ? node->mHeight : -1; } + + // returns new head + Node* rotateLeft(Node* pivot) { + DEBUG_ASSERT(pivot); + + Node* const head = pivot; + Node* const right = pivot->mRight; + Node* const right_left = right->mLeft; + Node* const parent = pivot->mParent; + + // parents + if (right_left) right_left->mParent = head; + head->mParent = right; + right->mParent = parent; + + // children + head->mRight = right_left; + right->mLeft = head; + + // heights + head->mHeight = 1 + max(getNodeHeight(head->mLeft), getNodeHeight(head->mRight)); + right->mHeight = 1 + max(getNodeHeight(right->mLeft), getNodeHeight(right->mRight)); + + // cache + head->updateTreeCacheCallBack(); + right->updateTreeCacheCallBack(); + + return right; + } + + Node* rotateRight(Node* pivot) { + DEBUG_ASSERT(pivot); + + Node* const head = pivot; + Node* const left = pivot->mLeft; + Node* const left_right = left->mRight; + Node* const parent = pivot->mParent; + + // parents + if (left_right) left_right->mParent = head; + head->mParent = left; + left->mParent = parent; + + // children + head->mLeft = left_right; + left->mRight = head; + + // heights + head->mHeight = 1 + max(getNodeHeight(head->mLeft), getNodeHeight(head->mRight)); + left->mHeight = 1 + max(getNodeHeight(left->mLeft), getNodeHeight(left->mRight)); + + // cache + head->updateTreeCacheCallBack(); + left->updateTreeCacheCallBack(); + + return left; + } + + // recursively returns valid isLeft or isRight child or root + Node* insertUtil(Node* head, KeyArg key, DataArg data) { + + Node* insertedNode; + + if (head == nullptr) { + mSize++; + Node* out = newNode(key, data); + out->updateTreeCacheCallBack(); + return out; + } else if (head->exactNode(key)) { + return head; + } else if (head->descentRight(key)) { + insertedNode = insertUtil(head->mRight, head->keyInRightSubtree(key), data); + head->mRight = insertedNode; + insertedNode->mParent = head; + } else { + insertedNode = insertUtil(head->mLeft, head->keyInLeftSubtree(key), data); + head->mLeft = insertedNode; + insertedNode->mParent = head; + } + + // update height + head->mHeight = 1 + max(getNodeHeight(head->mRight), getNodeHeight(head->mLeft)); + + alni balance = alni(getNodeHeight(head->mRight) - getNodeHeight(head->mLeft)); + + if (balance > 1) { + if (head->mRight->descentRight(head->keyInRightSubtree(key))) { + return rotateLeft(head); + } else { + head->mRight = rotateRight(head->mRight); + return rotateLeft(head); + } + } else if (balance < -1) { + if (head->mLeft->descentLeft(head->keyInLeftSubtree(key))) { + return rotateRight(head); + } else { + head->mLeft = rotateLeft(head->mLeft); + return rotateRight(head); + } + } + + head->updateTreeCacheCallBack(); + + return head; + } + + Node* removeUtil(Node* head, KeyArg key) { + if (head == nullptr) return head; + + if (head->exactNode(key)) { + if (head->mRight && head->mLeft) { + Node* min = minNode(head->mRight); + auto const& newKey = min->getFindKey(head->mRight); + injectNodeInstead(head, min); + head->mRight = removeUtil(head->mRight, newKey); + } else if (head->mRight) { + injectNodeInstead(head, head->mRight); + deleteNode(head->mRight); + head->mRight = nullptr; + mSize--; + } else if (head->mLeft) { + injectNodeInstead(head, head->mLeft); + deleteNode(head->mLeft); + head->mLeft = nullptr; + mSize--; + } else { + deleteNode(head); + mSize--; + head = nullptr; + } + } else if (head->descentRight(key)) { + head->mRight = removeUtil(head->mRight, head->keyInRightSubtree(key)); + } else if (head->descentLeft(key)) { + head->mLeft = removeUtil(head->mLeft, head->keyInLeftSubtree(key)); + } + + if (head == nullptr) return head; + + head->mHeight = 1 + max(getNodeHeight(head->mRight), getNodeHeight(head->mLeft)); + alni balance = getNodeHeight(head->mRight) - getNodeHeight(head->mLeft); + + if (balance < -1) { + if (getNodeHeight(head->mLeft->mLeft) >= getNodeHeight(head->mLeft->mRight)) { + return rotateRight(head); + } else { + head->mLeft = rotateLeft(head->mLeft); + return rotateRight(head); + } + } else if (balance > 1) { + if (getNodeHeight(head->mRight->mRight) >= getNodeHeight(head->mRight->mLeft)) { + return rotateLeft(head); + } else { + head->mRight = rotateRight(head->mRight); + return rotateLeft(head); + } + } + + head->updateTreeCacheCallBack(); + + return head; + } + + public: + AvlTree() { MODULE_SANITY_CHECK(gModuleContainers) } + + [[nodiscard]] ualni size() const { return mSize; } + + Node* head() const { return this->mRoot; } + + void insert(KeyArg key, DataArg data) { + mRoot = insertUtil(mRoot, key, data); + mRoot->mParent = nullptr; + } + + void remove(KeyArg key) { + mRoot = removeUtil(mRoot, key); + if (mRoot) mRoot->mParent = nullptr; + } + + Node* maxNode(Node* head) const { + if (!head) return nullptr; + while (head->mRight != nullptr) { + head = head->mRight; + } + return head; + } + + Node* minNode(Node* head) const { + if (!head) return nullptr; + while (head->mLeft != nullptr) { + head = head->mLeft; + } + return head; + } + + Node* find(KeyArg key) const { + Node* iter = mRoot; + while (true) { + if (!iter) return nullptr; + if (iter->exactNode(key)) return iter; + if (iter->descentLeft(key)) { + key = iter->keyInLeftSubtree(key); + iter = iter->mLeft; + } else { + key = iter->keyInRightSubtree(key); + iter = iter->mRight; + } + } + } + + Node* findLessOrEq(KeyArg key) const { + Node* iter = mRoot; + while (true) { + if (!iter) return nullptr; + if (iter->exactNode(key)) return iter; + if (iter->descentLeft(key)) { + if (iter->mLeft) { + key = iter->keyInLeftSubtree(key); + iter = iter->mLeft; + } else { + return iter; + } + } else { + if (iter->mRight) { + key = iter->keyInRightSubtree(key); + iter = iter->mRight; + } else { + return iter; + } + } + } + } + + // returns first invalid node + const Node* findInvalidNode(const Node* head) const { + if (head == nullptr) return nullptr; + + if (head->mLeft) { + // TODO: incomplete test + if (!head->descentLeft(head->mLeft->getFindKey(head))) return head; + if (head->mLeft->mParent != head) return head; + if (!head->mRight && head->mLeft->mHeight != head->mHeight - 1) return head; + } + + if (head->mRight) { + if (!head->descentRight(head->mRight->getFindKey(head))) return head; + if (head->mRight->mParent != head) return head; + if (!head->mLeft && head->mRight->mHeight != head->mHeight - 1) return head; + } + + if (head->mLeft && head->mRight) { + if (max(head->mLeft->mHeight, head->mRight->mHeight) != head->mHeight - 1) return head; + } + + int balance = getNodeHeight(head->mRight) - getNodeHeight(head->mLeft); + + if (balance > 1 || balance < -1) return head; + + const Node* ret = findInvalidNode(head->mRight); + + if (ret) return ret; + + return findInvalidNode(head->mLeft); + } + + bool isValid() { return findInvalidNode(head()) == nullptr; } + + template + void traverse(Node* node, bool after, tFunctor functor) { + if (!after) functor(node); + if (node->mLeft) traverse(node->mLeft, after, functor); + if (node->mRight) traverse(node->mRight, after, functor); + if (after) functor(node); + } + + void removeAll() { + traverse(mRoot, true, [this](Node* node) { deleteNode(node); }); + mRoot = nullptr; + mSize = 0; + } + + public: + template + void archiveWrite(tArchiver& file) const { + FAIL("not implemented") + } + + template + void archiveRead(tArchiver&) { + FAIL("not implemented") + } + }; } \ No newline at end of file diff --git a/Containers/tests/Buffer2DTest.cpp b/Containers/tests/Buffer2DTest.cpp index 5afe95b..7b3de92 100644 --- a/Containers/tests/Buffer2DTest.cpp +++ b/Containers/tests/Buffer2DTest.cpp @@ -1,8 +1,8 @@ #include "NewPlacement.hpp" -#include "Tests.hpp" -#include "Testing.hpp" #include "Buffer2D.hpp" +#include "Testing.hpp" +#include "Tests.hpp" using namespace tp; @@ -11,8 +11,8 @@ const ualni size = 1000; TEST_DEF_STATIC(Simple1) { Buffer2D buff; buff.reserve({ 4, 4 }); - buff.set( { 2, 2 }, 5); - TEST(buff.get( { 2, 2 } ) == 5); + buff.set({ 2, 2 }, 5); + TEST(buff.get({ 2, 2 }) == 5); } TEST_DEF_STATIC(Simple2) { @@ -20,6 +20,6 @@ TEST_DEF_STATIC(Simple2) { } TEST_DEF(Buffer2d) { - testSimple1(); - testSimple2(); + testSimple1(); + testSimple2(); } \ No newline at end of file diff --git a/Containers/tests/BufferTest.cpp b/Containers/tests/BufferTest.cpp index a9f1adc..e30809a 100644 --- a/Containers/tests/BufferTest.cpp +++ b/Containers/tests/BufferTest.cpp @@ -1,34 +1,37 @@ #include "NewPlacement.hpp" -#include "Tests.hpp" #include "Buffer.hpp" #include "Testing.hpp" +#include "Tests.hpp" using namespace tp; const ualni size = 1000; TEST_DEF_STATIC(Simple1) { - Buffer buff; - TEST(buff.size() == 0); - for (auto i : Range(size * 10)) { - buff.append(TestClass(i)); - } - TEST(buff.size() == size * 10); - while (buff.size()) buff.pop(); - TEST(buff.size() == 0); + Buffer buff; + TEST(buff.size() == 0); + for (auto i : Range(size * 10)) { + buff.append(TestClass(i)); + } + TEST(buff.size() == size * 10); + while (buff.size()) + buff.pop(); + TEST(buff.size() == 0); } TEST_DEF_STATIC(Simple2) { - Buffer buff(size); - TEST(buff.size() == 0); - for (auto i : Range(size * 10)) buff.append(TestClass(i)); - TEST(buff.size() == size * 10); - while (buff.size()) buff.pop(); - TEST(buff.size() == 0); + Buffer buff(size); + TEST(buff.size() == 0); + for (auto i : Range(size * 10)) + buff.append(TestClass(i)); + TEST(buff.size() == size * 10); + while (buff.size()) + buff.pop(); + TEST(buff.size() == 0); } TEST_DEF(Buffer) { - testSimple1(); - testSimple2(); + testSimple1(); + testSimple2(); } \ No newline at end of file diff --git a/Containers/tests/ListTest.cpp b/Containers/tests/ListTest.cpp index 394826f..64801b1 100644 --- a/Containers/tests/ListTest.cpp +++ b/Containers/tests/ListTest.cpp @@ -1,8 +1,8 @@ #include "NewPlacement.hpp" -#include "Tests.hpp" -#include "Testing.hpp" #include "Archiver.hpp" +#include "Testing.hpp" +#include "Tests.hpp" using namespace tp; diff --git a/Containers/tests/MapTest.cpp b/Containers/tests/MapTest.cpp index 1afd47e..b18d8fd 100644 --- a/Containers/tests/MapTest.cpp +++ b/Containers/tests/MapTest.cpp @@ -1,9 +1,9 @@ #include "NewPlacement.hpp" -#include "Tests.hpp" -#include "Testing.hpp" -#include "Map.hpp" #include "Archiver.hpp" +#include "Map.hpp" +#include "Testing.hpp" +#include "Tests.hpp" using namespace tp; diff --git a/Containers/tests/Tests.cpp b/Containers/tests/Tests.cpp index 529e808..b051deb 100644 --- a/Containers/tests/Tests.cpp +++ b/Containers/tests/Tests.cpp @@ -1,26 +1,26 @@ - -#include "Tests.hpp" -#include "Testing.hpp" - -static bool init(const tp::ModuleManifest* self) { - tp::gTesting.setRootName(self->getName()); - return true; -} - -int main() { - - tp::ModuleManifest* deps[] = { &tp::gModuleUtils, &tp::gModuleAllocators, nullptr }; - tp::ModuleManifest testModule("ContainersTest", init, nullptr, deps); - - if (!testModule.initialize()) { - return 1; - } - - testList(); - testMap(); - testAvl(); - testBuffer(); - testBuffer2d(); - - testModule.deinitialize(); -} + +#include "Tests.hpp" +#include "Testing.hpp" + +static bool init(const tp::ModuleManifest* self) { + tp::gTesting.setRootName(self->getName()); + return true; +} + +int main() { + + tp::ModuleManifest* deps[] = { &tp::gModuleUtils, &tp::gModuleAllocators, nullptr }; + tp::ModuleManifest testModule("ContainersTest", init, nullptr, deps); + + if (!testModule.initialize()) { + return 1; + } + + testList(); + testMap(); + testAvl(); + testBuffer(); + testBuffer2d(); + + testModule.deinitialize(); +} diff --git a/Containers/tests/Tests.hpp b/Containers/tests/Tests.hpp index 20f09ef..090aed9 100644 --- a/Containers/tests/Tests.hpp +++ b/Containers/tests/Tests.hpp @@ -1,34 +1,32 @@ #pragma once -#include "Utils.hpp" #include "Allocators.hpp" +#include "Utils.hpp" class TestClass { tp::ualni val2 = 0; tp::ualni val1; + public: + explicit TestClass(tp::ualni val) : + val1(val) {} - explicit TestClass(tp::ualni val) : val1(val) {} - - template + template void write(Saver& file) const { file.write(val1); } - template + template void read(Loader& file) { file.read(val1); } - [[nodiscard]] bool operator==(const TestClass& in) const { - return in.val1 == val1; - } + [[nodiscard]] bool operator==(const TestClass& in) const { return in.val1 == val1; } [[nodiscard]] tp::ualni getVal() const { return val1; } void setVal(tp::ualni val) { val1 = val; } }; - void testList(); void testMap(); void testAvl(); diff --git a/Containers/tests/TreeTest.cpp b/Containers/tests/TreeTest.cpp index 5665342..d305eff 100644 --- a/Containers/tests/TreeTest.cpp +++ b/Containers/tests/TreeTest.cpp @@ -1,8 +1,8 @@ #include "NewPlacement.hpp" +#include "Testing.hpp" #include "Tests.hpp" #include "Tree.hpp" -#include "Testing.hpp" using namespace tp; @@ -29,7 +29,8 @@ TEST_DEF_STATIC(Persistance) { const auto size = 1000; struct Item { - Item() : data(0) {} + Item() : + data(0) {} bool presents = false; TestClass data; }; diff --git a/DataAnalysis/CMakeLists.txt b/DataAnalysis/CMakeLists.txt index 0e2e61b..9ad7ef1 100644 --- a/DataAnalysis/CMakeLists.txt +++ b/DataAnalysis/CMakeLists.txt @@ -12,12 +12,12 @@ file(GLOB HEADERS "./public/*.hpp" "./public/*/*.hpp" "./applications/*.hpp") add_library(${PROJECT_NAME} STATIC ${SOURCES} ${HEADERS}) target_include_directories(${PROJECT_NAME} PUBLIC ./public/) -target_link_libraries(${PROJECT_NAME} PUBLIC Math Containers) +target_link_libraries(${PROJECT_NAME} PUBLIC Math Containers Allocators) ### -------------------------- Applications -------------------------- ### add_executable(NumberRec ./applications/NumberRecognition.cpp) -target_link_libraries(NumberRec ${PROJECT_NAME}) -#file(COPY "applications/rsc" DESTINATION "${CMAKE_BINARY_DIR}/${PROJECT_NAME}/") +target_link_libraries(NumberRec ${PROJECT_NAME} Connection) +file(COPY "applications/rsc" DESTINATION "${CMAKE_BINARY_DIR}/${PROJECT_NAME}/") ### -------------------------- Tests -------------------------- ### enable_testing() diff --git a/DataAnalysis/applications/NumberRecognition.cpp b/DataAnalysis/applications/NumberRecognition.cpp index 80a5577..65c750f 100644 --- a/DataAnalysis/applications/NumberRecognition.cpp +++ b/DataAnalysis/applications/NumberRecognition.cpp @@ -1,3 +1,115 @@ -#include "FullyConnectedNN.hpp" - -int main() { return 0; } +#include "FullyConnectedNN.hpp" +#include "LocalConnection.hpp" +#include "NewPlacement.hpp" + +using namespace tp; + +struct Dataset { + ualni length = 0; + Pair imageSize = { 0, 0 }; + Buffer labels; + Buffer> images; +}; + +bool loadDataset(Dataset& out, const String& location) { + LocalConnection dataset; + dataset.connect(LocalConnection::Location(location), LocalConnection::Type(true)); + + if (!dataset.getConnectionStatus().isOpened()) { + return false; + } + + LocalConnection::Byte length; + dataset.readBytes(&length, 1); + + LocalConnection::Byte sizeX; + dataset.readBytes(&sizeX, 1); + + LocalConnection::Byte sizeY; + dataset.readBytes(&sizeY, 1); + + out.length = ((ualni) length) * 1000; + out.imageSize = { sizeX, sizeY }; + + out.labels.reserve(out.length); + out.images.reserve(out.length); + + for (auto i : Range(out.length)) { + auto& image = out.images[i]; + image.reserve(sizeX * sizeY); + dataset.readBytes((LocalConnection::Byte*) image.getBuff(), sizeX * sizeY); + } + + LocalConnection::Byte label; + dataset.readBytes((LocalConnection::Byte*) out.labels.getBuff(), out.length); + + return true; +} + +halnf test(const Dataset& dataset, FullyConnectedNN& nn, Range range) { + ualni numFailed = 0; + + for (auto i : range) { + auto& image = dataset.images[i]; + auto label = dataset.labels[i]; + + Buffer results; + Buffer input; + + results.reserve(10); + input.reserve(image.size()); + + for (auto pixelIdx : Range(image.size())) { + input[pixelIdx] = (halnf) image[pixelIdx] / 255.f; + } + + nn.evaluate(input, results); + + ualni resultNumber = 0; + for (auto resIdx : Range(results.size())) { + if (results[resIdx] > results[resultNumber]) { + resultNumber = resIdx; + } + } + + if (resultNumber != label) { + numFailed++; + } + } + + return (halnf) numFailed / (halnf) range.idxDiff(); +} + +void numRec() { + Dataset dataset; + FullyConnectedNN nn; + + Buffer layers; + layers = { 784, 128, 10 }; + + nn.initializeRandom(layers); + + if (!loadDataset(dataset, "rsc/mnist")) { + printf("Cant Load Mnist Dataset\n"); + return; + } + + auto errorPercentage = test(dataset, nn, { 0, 100 }); + + printf("Percentage error : %f\n", errorPercentage); +} + +int main() { + ModuleManifest* deps[] = { &gModuleDataAnalysis, &gModuleConnection, nullptr }; + ModuleManifest module = ModuleManifest("NumRec", nullptr, nullptr, deps); + + if (!module.initialize()) { + return 1; + } + + numRec(); + + module.deinitialize(); + + return 0; +} diff --git a/DataAnalysis/applications/rsc/mnist.gz b/DataAnalysis/applications/rsc/mnist.gz new file mode 100644 index 0000000..abb32ac Binary files /dev/null and b/DataAnalysis/applications/rsc/mnist.gz differ diff --git a/DataAnalysis/private/DataAnalysisCommon.cpp b/DataAnalysis/private/DataAnalysisCommon.cpp index ab328f8..d128c83 100644 --- a/DataAnalysis/private/DataAnalysisCommon.cpp +++ b/DataAnalysis/private/DataAnalysisCommon.cpp @@ -1,8 +1,9 @@ #include "DataAnalysisCommon.hpp" +#include "Allocators.hpp" #include "ContainersCommon.hpp" #include "MathCommon.hpp" namespace tp { - static ModuleManifest* deps[] = {&gModuleMath, &gModuleContainers, nullptr}; - ModuleManifest gModuleDataAnalysis = ModuleManifest("DataAnalysis", nullptr, nullptr, deps); + static ModuleManifest* deps[] = { &gModuleMath, &gModuleContainers, &gModuleAllocators, nullptr }; + ModuleManifest gModuleDataAnalysis = ModuleManifest("DataAnalysis", nullptr, nullptr, deps); } diff --git a/DataAnalysis/private/FullyConnectedNN.cpp b/DataAnalysis/private/FullyConnectedNN.cpp new file mode 100644 index 0000000..c9c0654 --- /dev/null +++ b/DataAnalysis/private/FullyConnectedNN.cpp @@ -0,0 +1,53 @@ +#include "FullyConnectedNN.hpp" +#include "NewPlacement.hpp" +#include "Utils.hpp" + +using namespace tp; + +static halnf sigmoid(halnf val) { return 0; } + +static halnf relu(halnf val) { return val < 0 ? 0 : val; } + +void FullyConnectedNN::initializeRandom(Buffer description) { + mLayers.reserve(description.size()); + + for (auto i : Range(0, (halni) description.size())) { + mLayers[i].mNeurons.reserve(description[i]); + if (i == 0) { + continue; + } + for (auto neuron : mLayers[i].mNeurons) { + neuron->mWeights.reserve(description[i - 1]); + for (auto weight : neuron->mWeights) { + weight.data() = (halnf) randomFloat(); + } + neuron->mBias = (halnf) randomFloat(); + } + } +} + +void FullyConnectedNN::evaluate(const Buffer& input, Buffer& output) { + ASSERT(output.size() == mLayers.last().mNeurons.size() && input.size() == mLayers.first().mNeurons.size()) + + for (auto idx : Range(input.size())) { + mLayers.first().mNeurons[idx].mActivationValue = input[idx]; + } + + for (auto layerIdx : Range(1, (halni) mLayers.size())) { + auto& layer = mLayers[layerIdx]; + auto& layerPrev = mLayers[layerIdx - 1]; + + for (auto neuron : layer.mNeurons) { + neuron->mActivationValue = 0; + for (auto connectionIdx : Range(neuron->mWeights.size())) { + neuron->mActivationValue += neuron->mWeights[connectionIdx] * layerPrev.mNeurons[connectionIdx].mActivationValue; + } + neuron->mActivationValue += neuron->mBias; + neuron->mActivationValue = relu(neuron->mActivationValue); + } + } + + for (auto idx : Range(output.size())) { + output[idx] = mLayers.last().mNeurons[idx].mActivationValue; + } +} diff --git a/DataAnalysis/public/DataAnalysisCommon.hpp b/DataAnalysis/public/DataAnalysisCommon.hpp index 66a43aa..8a1050c 100644 --- a/DataAnalysis/public/DataAnalysisCommon.hpp +++ b/DataAnalysis/public/DataAnalysisCommon.hpp @@ -3,5 +3,5 @@ #include "Module.hpp" namespace tp { - extern ModuleManifest gModuleDataAnalysis; + extern ModuleManifest gModuleDataAnalysis; } diff --git a/DataAnalysis/public/FullyConnectedNN.hpp b/DataAnalysis/public/FullyConnectedNN.hpp index 450e31b..5a1ceae 100644 --- a/DataAnalysis/public/FullyConnectedNN.hpp +++ b/DataAnalysis/public/FullyConnectedNN.hpp @@ -4,17 +4,24 @@ #include "DataAnalysisCommon.hpp" namespace tp { - class FullyConnectedNN { - public: - struct Layer { - halnf mBias; - Buffer mWeights; - }; + class FullyConnectedNN { + struct Layer { + struct Neuron { + halnf mBias = 0; + Buffer mWeights; + halnf mActivationValue = 0; + }; - public: - FullyConnectedNN() = default; + Buffer mNeurons; + }; - private: - Buffer mLayers; - }; + public: + FullyConnectedNN() = default; + + void initializeRandom(Buffer description); + void evaluate(const Buffer& input, Buffer& output); + + private: + Buffer mLayers; + }; }; diff --git a/DataAnalysis/tests/Tests.cpp b/DataAnalysis/tests/Tests.cpp index 0864c29..968f9f7 100644 --- a/DataAnalysis/tests/Tests.cpp +++ b/DataAnalysis/tests/Tests.cpp @@ -1,26 +1,26 @@ - -#include "FullyConnectedNN.hpp" -#include "Testing.hpp" -#include "Utils.hpp" - -static bool init(const tp::ModuleManifest* self) { - tp::gTesting.setRootName(self->getName()); - return true; -} - -void test() {} - -int main() { - tp::ModuleManifest* deps[] = {&tp::gModuleDataAnalysis, &tp::gModuleUtils, nullptr}; - tp::ModuleManifest testModule("DataAnalysisTest", init, nullptr, deps); - - if (!testModule.initialize()) { - return 1; - } - - test(); - - testModule.deinitialize(); - - return 0; -} + +#include "FullyConnectedNN.hpp" +#include "Testing.hpp" +#include "Utils.hpp" + +static bool init(const tp::ModuleManifest* self) { + tp::gTesting.setRootName(self->getName()); + return true; +} + +void test() {} + +int main() { + tp::ModuleManifest* deps[] = { &tp::gModuleDataAnalysis, &tp::gModuleUtils, nullptr }; + tp::ModuleManifest testModule("DataAnalysisTest", init, nullptr, deps); + + if (!testModule.initialize()) { + return 1; + } + + test(); + + testModule.deinitialize(); + + return 0; +} diff --git a/Graphics/private/Animations.cpp b/Graphics/private/Animations.cpp index 20d4e92..4e64f9e 100644 --- a/Graphics/private/Animations.cpp +++ b/Graphics/private/Animations.cpp @@ -1,104 +1,92 @@ - -#include "Animations.hpp" - -using namespace tp; - -bool AnimValue::gInTransition = false; - -halnf AnimValue::interpolate() const { - if (!mTimeAnim) { - return mVal; - } - - auto dt = gCurrentTime - mTimeStart; - if (dt > mTimeAnim) dt = mTimeAnim; - auto t = (halnf)dt / (halnf)mTimeAnim; - t = (halnf)(0.511 + atan((t - 0.36) * 28) / 2.9); - t = clamp(t, 0.f, 1.f); - auto out = mValPrev + (mVal - mValPrev) * t; - return out; -} - -AnimValue::AnimValue() = default; - -void AnimValue::setAnimTime(halni time) { - mTimeAnim = time; -} - -AnimValue::AnimValue(halnf val) { - mVal = val; - mValPrev = mVal; - mTimeStart = gCurrentTime; -} - -bool AnimValue::inTransition() const { - auto timePassed = gCurrentTime - mTimeStart >= mTimeAnim; - return !timePassed; -} - -void AnimValue::set(halnf val) { - if (!inTransition()) mValPrev = mVal; - if (val == mVal) return; - mValPrev = get(); - mVal = val; - if (!inTransition()) mTimeStart = (halni)gCurrentTime; -} - -halnf AnimValue::getTarget() const { - return mVal; -} - -void AnimValue::setNoTransition(halnf val) { - mValPrev = val; - mVal = val; - mTimeStart -= mTimeStart; -} - -halnf AnimValue::get() const { - if (inTransition()) { - gInTransition = true; - } - return interpolate(); -} - -AnimValue::operator halnf() const { - return get(); -} - -RectF AnimRect::get() const { - return { x.get(), y.get() , z.get(), w.get() }; -} - -RectF AnimRect::getTarget() const { - return { x.getTarget(), y.getTarget() , z.getTarget(), w.getTarget() }; -} - -void AnimRect::setNoTransition(RectF rec) { - x.setNoTransition(rec.x); - y.setNoTransition(rec.y); - z.setNoTransition(rec.z); - w.setNoTransition(rec.w); -} - -void AnimRect::setAnimTime(const halni time) { - x.setAnimTime(time); - y.setAnimTime(time); - z.setAnimTime(time); - w.setAnimTime(time); -} - -void AnimRect::set(const RectF& in) { - x.set(in.x); - y.set(in.y); - z.set(in.z); - w.set(in.w); -} - -RGBA AnimColor::get() const { - auto col = mColor.get(); - return {col.x, col.y, col.z, col.w}; -} - -void AnimColor::set(const RGBA& col) { - mColor.set(RectF(col.r, col.g, col.b, col.a)); -} \ No newline at end of file + +#include "Animations.hpp" + +using namespace tp; + +bool AnimValue::gInTransition = false; + +halnf AnimValue::interpolate() const { + if (!mTimeAnim) { + return mVal; + } + + auto dt = gCurrentTime - mTimeStart; + if (dt > mTimeAnim) dt = mTimeAnim; + auto t = (halnf) dt / (halnf) mTimeAnim; + t = (halnf) (0.511 + atan((t - 0.36) * 28) / 2.9); + t = clamp(t, 0.f, 1.f); + auto out = mValPrev + (mVal - mValPrev) * t; + return out; +} + +AnimValue::AnimValue() = default; + +void AnimValue::setAnimTime(halni time) { mTimeAnim = time; } + +AnimValue::AnimValue(halnf val) { + mVal = val; + mValPrev = mVal; + mTimeStart = gCurrentTime; +} + +bool AnimValue::inTransition() const { + auto timePassed = gCurrentTime - mTimeStart >= mTimeAnim; + return !timePassed; +} + +void AnimValue::set(halnf val) { + if (!inTransition()) mValPrev = mVal; + if (val == mVal) return; + mValPrev = get(); + mVal = val; + if (!inTransition()) mTimeStart = (halni) gCurrentTime; +} + +halnf AnimValue::getTarget() const { return mVal; } + +void AnimValue::setNoTransition(halnf val) { + mValPrev = val; + mVal = val; + mTimeStart -= mTimeStart; +} + +halnf AnimValue::get() const { + if (inTransition()) { + gInTransition = true; + } + return interpolate(); +} + +AnimValue::operator halnf() const { return get(); } + +RectF AnimRect::get() const { return { x.get(), y.get(), z.get(), w.get() }; } + +RectF AnimRect::getTarget() const { return { x.getTarget(), y.getTarget(), z.getTarget(), w.getTarget() }; } + +void AnimRect::setNoTransition(RectF rec) { + x.setNoTransition(rec.x); + y.setNoTransition(rec.y); + z.setNoTransition(rec.z); + w.setNoTransition(rec.w); +} + +void AnimRect::setAnimTime(const halni time) { + x.setAnimTime(time); + y.setAnimTime(time); + z.setAnimTime(time); + w.setAnimTime(time); +} + +void AnimRect::set(const RectF& in) { + x.set(in.x); + y.set(in.y); + z.set(in.z); + w.set(in.w); +} + +RGBA AnimColor::get() const { + auto col = mColor.get(); + return { col.x, col.y, col.z, col.w }; +} + +void AnimColor::set(const RGBA& col) { mColor.set(RectF(col.r, col.g, col.b, col.a)); } \ No newline at end of file diff --git a/Graphics/private/bindings/Canvas.cpp b/Graphics/private/bindings/Canvas.cpp index f917dc8..ce9546b 100644 --- a/Graphics/private/bindings/Canvas.cpp +++ b/Graphics/private/bindings/Canvas.cpp @@ -19,17 +19,11 @@ namespace tp { using namespace tp; -Graphics::Canvas::Canvas() { - mContext = new Context(); -} +Graphics::Canvas::Canvas() { mContext = new Context(); } -Graphics::Canvas::~Canvas() { - delete mContext; -} +Graphics::Canvas::~Canvas() { delete mContext; } -void Graphics::Canvas::init() { - mContext->vg = nvgCreateGL3(NVG_ANTIALIAS | NVG_STENCIL_STROKES); -} +void Graphics::Canvas::init() { mContext->vg = nvgCreateGL3(NVG_ANTIALIAS | NVG_STENCIL_STROKES); } void Graphics::Canvas::deinit() { // Cleanup diff --git a/Graphics/private/bindings/DebugGUI.cpp b/Graphics/private/bindings/DebugGUI.cpp index 5254806..62ad101 100644 --- a/Graphics/private/bindings/DebugGUI.cpp +++ b/Graphics/private/bindings/DebugGUI.cpp @@ -17,13 +17,9 @@ namespace tp { using namespace tp; -Graphics::GUI::GUI() { - mContext = new Context(); -} +Graphics::GUI::GUI() { mContext = new Context(); } -Graphics::GUI::~GUI() { - delete mContext; -} +Graphics::GUI::~GUI() { delete mContext; } void Graphics::GUI::init(Window* window) { IMGUI_CHECKVERSION(); diff --git a/Graphics/private/bindings/Window.cpp b/Graphics/private/bindings/Window.cpp index 88958d2..08facff 100644 --- a/Graphics/private/bindings/Window.cpp +++ b/Graphics/private/bindings/Window.cpp @@ -14,22 +14,18 @@ namespace tp { GLuint vao{}; GLuint vbo{}; GLfloat vertices[9] = { - -0.0f, -0.0f, 0.0f, // Left vertex - 1.0f, 0.0f, 0.0f, // Right vertex - 0.5f, 1.0f, 0.0f // Top vertex + -0.0f, -0.0f, 0.0f, // Left vertex + 1.0f, 0.0f, 0.0f, // Right vertex + 0.5f, 1.0f, 0.0f // Top vertex }; }; } using namespace tp; -Graphics::GL::GL() { - mContext = new Context(); -} +Graphics::GL::GL() { mContext = new Context(); } -Graphics::GL::~GL() { - delete mContext; -} +Graphics::GL::~GL() { delete mContext; } void Graphics::GL::init() { // Create a Vertex Array Object (VAO) @@ -51,13 +47,9 @@ void Graphics::GL::deinit() { glDeleteVertexArrays(1, &mContext->vao); } -void Graphics::GL::proc() { - glClear(GL_COLOR_BUFFER_BIT); -} +void Graphics::GL::proc() { glClear(GL_COLOR_BUFFER_BIT); } -void Graphics::GL::draw() { - glDrawArrays(GL_TRIANGLES, 0, 3); -} +void Graphics::GL::draw() { glDrawArrays(GL_TRIANGLES, 0, 3); } void Graphics::init(Window* window) { mGl.init(); @@ -110,7 +102,6 @@ Window::~Window() { delete mContext; } - Window* Window::createWindow(int width, int height, const char* title) { tp::HeapAllocGlobal::startIgnore(); @@ -128,9 +119,7 @@ Window* Window::createWindow(int width, int height, const char* title) { } // Set the GLFW error callback - glfwSetErrorCallback([] (int error, const char* description) { - printf("GLFW Error: %i %s\n", error, description); - }); + glfwSetErrorCallback([](int error, const char* description) { printf("GLFW Error: %i %s\n", error, description); }); auto out = new Window(width, height, title); @@ -143,9 +132,7 @@ void Window::destroyWindow(Window* window) { glfwTerminate(); } -bool Window::shouldClose() const { - return glfwWindowShouldClose(mContext->window); -} +bool Window::shouldClose() const { return glfwWindowShouldClose(mContext->window); } void Window::processEvents() { glfwPollEvents(); diff --git a/Graphics/private/bindings/WindowContext.hpp b/Graphics/private/bindings/WindowContext.hpp index 1f7599a..436d2e8 100644 --- a/Graphics/private/bindings/WindowContext.hpp +++ b/Graphics/private/bindings/WindowContext.hpp @@ -10,6 +10,7 @@ namespace tp { friend Graphics::GL; friend Graphics::GUI; friend Graphics::Canvas; + public: GLFWwindow* window; }; diff --git a/Graphics/public/Animations.hpp b/Graphics/public/Animations.hpp index f700383..41e0bca 100644 --- a/Graphics/public/Animations.hpp +++ b/Graphics/public/Animations.hpp @@ -1,53 +1,54 @@ -#pragma once - -#include "GraphicsCommon.hpp" - -namespace tp { - - class AnimValue { - halnf mValPrev = 0; - halnf mVal = 0; - time_ms mTimeStart = 0; - halni mTimeAnim = 250; - - static bool gInTransition; - - private: - [[nodiscard]] halnf interpolate() const; - - public: - AnimValue(); - explicit AnimValue(halnf val); - - [[nodiscard]] halnf prev() const { return mValPrev; } - void set(halnf val); - void setNoTransition(halnf); - void setAnimTime(halni time); - [[nodiscard]] halnf get() const; - [[nodiscard]] halnf getTarget() const; - [[nodiscard]] bool inTransition() const; - explicit operator halnf() const; - void operator=(halnf val); - }; - - class AnimRect : Rect { - public: - AnimRect() { - set({ 0, 0, 0, 0 }); - setAnimTime(450); - } - - [[nodiscard]] RectF get() const; - [[nodiscard]] RectF getTarget() const; - void setNoTransition(RectF); - void set(const RectF&); - void setAnimTime(halni time_ms); - }; - - class AnimColor { - AnimRect mColor; - public: - [[nodiscard]] RGBA get() const; - void set(const RGBA&); - }; +#pragma once + +#include "GraphicsCommon.hpp" + +namespace tp { + + class AnimValue { + halnf mValPrev = 0; + halnf mVal = 0; + time_ms mTimeStart = 0; + halni mTimeAnim = 250; + + static bool gInTransition; + + private: + [[nodiscard]] halnf interpolate() const; + + public: + AnimValue(); + explicit AnimValue(halnf val); + + [[nodiscard]] halnf prev() const { return mValPrev; } + void set(halnf val); + void setNoTransition(halnf); + void setAnimTime(halni time); + [[nodiscard]] halnf get() const; + [[nodiscard]] halnf getTarget() const; + [[nodiscard]] bool inTransition() const; + explicit operator halnf() const; + void operator=(halnf val); + }; + + class AnimRect : Rect { + public: + AnimRect() { + set({ 0, 0, 0, 0 }); + setAnimTime(450); + } + + [[nodiscard]] RectF get() const; + [[nodiscard]] RectF getTarget() const; + void setNoTransition(RectF); + void set(const RectF&); + void setAnimTime(halni time_ms); + }; + + class AnimColor { + AnimRect mColor; + + public: + [[nodiscard]] RGBA get() const; + void set(const RGBA&); + }; }; \ No newline at end of file diff --git a/Graphics/public/Graphics.hpp b/Graphics/public/Graphics.hpp index ef198b4..9efd8dd 100644 --- a/Graphics/public/Graphics.hpp +++ b/Graphics/public/Graphics.hpp @@ -10,6 +10,7 @@ namespace tp { class GL { class Context; Context* mContext; + private: friend Graphics; @@ -20,6 +21,7 @@ namespace tp { void deinit(); static void proc(); static void draw(); + public: // TODO : API }; @@ -27,6 +29,7 @@ namespace tp { class GUI { class Context; Context* mContext; + private: friend Graphics; @@ -45,6 +48,7 @@ namespace tp { class Canvas { class Context; Context* mContext; + private: friend Graphics; diff --git a/Graphics/public/GraphicsCommon.hpp b/Graphics/public/GraphicsCommon.hpp index 1ce1a09..33466d6 100644 --- a/Graphics/public/GraphicsCommon.hpp +++ b/Graphics/public/GraphicsCommon.hpp @@ -1,8 +1,8 @@ #pragma once -#include "Strings.hpp" -#include "Rect.hpp" #include "Color.hpp" +#include "Rect.hpp" +#include "Strings.hpp" #include "Timing.hpp" namespace tp { diff --git a/Graphics/public/Keycodes.hpp b/Graphics/public/Keycodes.hpp index 86f00db..f42b90d 100644 --- a/Graphics/public/Keycodes.hpp +++ b/Graphics/public/Keycodes.hpp @@ -1,166 +1,166 @@ - -#pragma once - -namespace tp { - - // basically copy of glfw keys - enum class Keycode { - - /* Printable keys */ - SPACE = 32, - APOSTROPHE = 39, /* ' */ - COMMA = 44, /* , */ - MINUS = 45, /* - */ - PERIOD = 46, /* . */ - SLASH = 0xBF, /* \ */ - N0 = 48, - N1 = 49, - N2 = 50, - N3 = 51, - N4 = 52, - N5 = 53, - N6 = 54, - N7 = 55, - N8 = 56, - N9 = 57, - SEMICOLON = 59, /* ; */ - EQUAL = 61, /* = */ - A = 65, - B = 66, - C = 67, - D = 68, - E = 69, - F = 70, - G = 71, - H = 72, - I = 73, - J = 74, - K = 75, - L = 76, - M = 77, - N = 78, - O = 79, - P = 80, - Q = 81, - R = 82, - S = 83, - T = 84, - U = 85, - V = 86, - W = 87, - X = 88, - Y = 89, - Z = 90, - LEFT_BRACKET = 91, /* [ */ - BACKSLASH = 92, /* \ */ - RIGHT_BRACKET = 93, /* ] */ - GRAVE_ACCENT = 96, /* ` */ - WORLD_1 = 161, /* non-US #1 */ - WORLD_2 = 162, /* non-US #2 */ - - /* function keys */ - - ESCAPE = 256, - ENTER = 257, - TAB = 258, - BACKSPACE = 259, - INSERT = 260, - DELETE = 261, - RIGHT = 262, - LEFT = 263, - DOWN = 264, - UP = 265, - PAGE_UP = 266, - PAGE_DOWN = 267, - HOME = 268, - END = 269, - CAPS_LOCK = 280, - SCROLL_LOCK = 281, - NUM_LOCK = 282, - PRINT_SCREEN = 283, - PAUSE = 284, - F1 = 290, - F2 = 291, - F3 = 292, - F4 = 293, - F5 = 294, - F6 = 295, - F7 = 296, - F8 = 297, - F9 = 298, - F10 = 299, - F11 = 300, - F12 = 301, - F13 = 302, - F14 = 303, - F15 = 304, - F16 = 305, - F17 = 306, - F18 = 307, - F19 = 308, - F20 = 309, - F21 = 310, - F22 = 311, - F23 = 312, - F24 = 313, - F25 = 314, - KP_0 = 320, - KP_1 = 321, - KP_2 = 322, - KP_3 = 323, - KP_4 = 324, - KP_5 = 325, - KP_6 = 326, - KP_7 = 327, - KP_8 = 328, - KP_9 = 329, - KP_DECIMAL = 330, - KP_DIVIDE = 331, - KP_MULTIPLY = 332, - KP_SUBTRACT = 333, - KP_ADD = 334, - KP_ENTER = 335, - KP_EQUAL = 336, - LEFT_SHIFT = 340, - LEFT_CONTROL = 341, - LEFT_ALT = 342, - LEFT_SUPER = 343, - RIGHT_SHIFT = 344, - RIGHT_CONTROL = 345, - RIGHT_ALT = 346, - RIGHT_SUPER = 347, - MENU = 348, - - INV_SLASH = 0xDC, - BRA = 0xDB, - KET = 0xDD, - TILDA = 0xC0, - DOUBLE_DOT = 0xBA, - QUOTES = 0xDE, - - MOUSE1 = 501, - MOUSE2 = 502, - MOUSE3 = 503, - MOUSE4 = 504, - MOUSE5 = 505, - MOUSE_UP = 506, - MOUSE_DOWN = 507, - }; - - enum class KeyState { - PRESSED, - RELEASED, - HOLD, - REPEAT, - NONE, - }; - - struct KeyEvent { - Keycode code; - enum class EventState { - RELEASED = 0, - PRESSED = 1, - REPEAT = 2, - } event_state; - }; + +#pragma once + +namespace tp { + + // basically copy of glfw keys + enum class Keycode { + + /* Printable keys */ + SPACE = 32, + APOSTROPHE = 39, /* ' */ + COMMA = 44, /* , */ + MINUS = 45, /* - */ + PERIOD = 46, /* . */ + SLASH = 0xBF, /* \ */ + N0 = 48, + N1 = 49, + N2 = 50, + N3 = 51, + N4 = 52, + N5 = 53, + N6 = 54, + N7 = 55, + N8 = 56, + N9 = 57, + SEMICOLON = 59, /* ; */ + EQUAL = 61, /* = */ + A = 65, + B = 66, + C = 67, + D = 68, + E = 69, + F = 70, + G = 71, + H = 72, + I = 73, + J = 74, + K = 75, + L = 76, + M = 77, + N = 78, + O = 79, + P = 80, + Q = 81, + R = 82, + S = 83, + T = 84, + U = 85, + V = 86, + W = 87, + X = 88, + Y = 89, + Z = 90, + LEFT_BRACKET = 91, /* [ */ + BACKSLASH = 92, /* \ */ + RIGHT_BRACKET = 93, /* ] */ + GRAVE_ACCENT = 96, /* ` */ + WORLD_1 = 161, /* non-US #1 */ + WORLD_2 = 162, /* non-US #2 */ + + /* function keys */ + + ESCAPE = 256, + ENTER = 257, + TAB = 258, + BACKSPACE = 259, + INSERT = 260, + DELETE = 261, + RIGHT = 262, + LEFT = 263, + DOWN = 264, + UP = 265, + PAGE_UP = 266, + PAGE_DOWN = 267, + HOME = 268, + END = 269, + CAPS_LOCK = 280, + SCROLL_LOCK = 281, + NUM_LOCK = 282, + PRINT_SCREEN = 283, + PAUSE = 284, + F1 = 290, + F2 = 291, + F3 = 292, + F4 = 293, + F5 = 294, + F6 = 295, + F7 = 296, + F8 = 297, + F9 = 298, + F10 = 299, + F11 = 300, + F12 = 301, + F13 = 302, + F14 = 303, + F15 = 304, + F16 = 305, + F17 = 306, + F18 = 307, + F19 = 308, + F20 = 309, + F21 = 310, + F22 = 311, + F23 = 312, + F24 = 313, + F25 = 314, + KP_0 = 320, + KP_1 = 321, + KP_2 = 322, + KP_3 = 323, + KP_4 = 324, + KP_5 = 325, + KP_6 = 326, + KP_7 = 327, + KP_8 = 328, + KP_9 = 329, + KP_DECIMAL = 330, + KP_DIVIDE = 331, + KP_MULTIPLY = 332, + KP_SUBTRACT = 333, + KP_ADD = 334, + KP_ENTER = 335, + KP_EQUAL = 336, + LEFT_SHIFT = 340, + LEFT_CONTROL = 341, + LEFT_ALT = 342, + LEFT_SUPER = 343, + RIGHT_SHIFT = 344, + RIGHT_CONTROL = 345, + RIGHT_ALT = 346, + RIGHT_SUPER = 347, + MENU = 348, + + INV_SLASH = 0xDC, + BRA = 0xDB, + KET = 0xDD, + TILDA = 0xC0, + DOUBLE_DOT = 0xBA, + QUOTES = 0xDE, + + MOUSE1 = 501, + MOUSE2 = 502, + MOUSE3 = 503, + MOUSE4 = 504, + MOUSE5 = 505, + MOUSE_UP = 506, + MOUSE_DOWN = 507, + }; + + enum class KeyState { + PRESSED, + RELEASED, + HOLD, + REPEAT, + NONE, + }; + + struct KeyEvent { + Keycode code; + enum class EventState { + RELEASED = 0, + PRESSED = 1, + REPEAT = 2, + } event_state; + }; }; \ No newline at end of file diff --git a/Graphics/public/Window.hpp b/Graphics/public/Window.hpp index 87d75bf..311131c 100644 --- a/Graphics/public/Window.hpp +++ b/Graphics/public/Window.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Graphics.hpp" #include "Buffer.hpp" +#include "Graphics.hpp" #include "Keycodes.hpp" namespace tp { diff --git a/Graphics/tests/tests.cpp b/Graphics/tests/tests.cpp index 560e551..c272dab 100644 --- a/Graphics/tests/tests.cpp +++ b/Graphics/tests/tests.cpp @@ -1,3 +1 @@ - int main() { - - } \ No newline at end of file +int main() {} \ No newline at end of file diff --git a/Math/private/Camera.cpp b/Math/private/Camera.cpp index 17a81d5..546705d 100644 --- a/Math/private/Camera.cpp +++ b/Math/private/Camera.cpp @@ -2,7 +2,7 @@ using namespace tp; -Camera::Camera() { lookAtPoint({0, 0, 0}, {2, 0, 0}, {0, 0, 1}); } +Camera::Camera() { lookAtPoint({ 0, 0, 0 }, { 2, 0, 0 }, { 0, 0, 1 }); } const Vec3F& Camera::getTarget() const { return mTarget; } @@ -31,102 +31,102 @@ halnf Camera::getFOV() const { return mFOV; } Mat4F Camera::calculateTransformationMatrix() { return calculateProjectionMatrix() * calculateViewMatrix(); } Mat4F Camera::calculateViewMatrix() { - const Vec3F& F = (mPos - mTarget).unitV(); - const Vec3F& S = mUp * F; - const Vec3F& U = F * S; - const Vec3F& P = mPos; + const Vec3F& F = (mPos - mTarget).unitV(); + const Vec3F& S = mUp * F; + const Vec3F& U = F * S; + const Vec3F& P = mPos; - Mat4F out; - out[0] = Vec4F(S.x, S.y, S.z, -P.dot(S)); - out[1] = Vec4F(U.x, U.y, U.z, -P.dot(U)); - out[2] = Vec4F(F.x, F.y, F.z, -P.dot(F)); - out[3] = Vec4F(0, 0, 0, 1); - return out; + Mat4F out; + out[0] = Vec4F(S.x, S.y, S.z, -P.dot(S)); + out[1] = Vec4F(U.x, U.y, U.z, -P.dot(U)); + out[2] = Vec4F(F.x, F.y, F.z, -P.dot(F)); + out[3] = Vec4F(0, 0, 0, 1); + return out; } Mat4F Camera::calculateProjectionMatrix() const { - auto r = (halnf) sqrt(mRatio); - halnf c = 1 / r; - auto s = halnf(1.f / tan(mFOV / 2.f)); + auto r = (halnf) sqrt(mRatio); + halnf c = 1 / r; + auto s = halnf(1.f / tan(mFOV / 2.f)); - Mat4F out; - out[0] = Vec4F(s * r, 0, 0, 0); - out[1] = Vec4F(0, s * c, 0, 0); - out[2] = Vec4F(0, 0, -2.f / (mFar - mNear), -(mFar + mNear) / (mFar - mNear)); - out[3] = Vec4F(0, 0, -1, 0); - return out; + Mat4F out; + out[0] = Vec4F(s * r, 0, 0, 0); + out[1] = Vec4F(0, s * c, 0, 0); + out[2] = Vec4F(0, 0, -2.f / (mFar - mNear), -(mFar + mNear) / (mFar - mNear)); + out[3] = Vec4F(0, 0, -1, 0); + return out; } Vec3F Camera::project(Vec2F normalized) { - auto camMat = calculateTransformationMatrix(); - auto inv = camMat.inv(); + auto camMat = calculateTransformationMatrix(); + auto inv = camMat.inv(); - halnf z = halnf((((mTarget - mPos).length() - mNear) / (mFar - mNear) - 1.f / 2) * 2.f); - halnf w = halnf((mTarget - mPos).length()); - Vec4 world_pos4(normalized.x * w, normalized.y * w, z, w); + halnf z = halnf((((mTarget - mPos).length() - mNear) / (mFar - mNear) - 1.f / 2) * 2.f); + halnf w = halnf((mTarget - mPos).length()); + Vec4 world_pos4(normalized.x * w, normalized.y * w, z, w); - return Vec3F(inv * world_pos4); + return Vec3F(inv * world_pos4); } Vec2F Camera::project(const Vec3F& world) { - Vec4F world_pos4(world.x, world.y, world.z, 1); - Vec4F transformed = calculateViewMatrix() * world_pos4; - transformed = calculateProjectionMatrix() * transformed; - return {transformed[0] / transformed[3], transformed[1] / transformed[3]}; + Vec4F world_pos4(world.x, world.y, world.z, 1); + Vec4F transformed = calculateViewMatrix() * world_pos4; + transformed = calculateProjectionMatrix() * transformed; + return { transformed[0] / transformed[3], transformed[1] / transformed[3] }; } Vec2F Camera::project(const tp::Vec3F& world, const tp::Mat4F& viewMat, const tp::Mat4F& projMat) { - Vec4F world_pos4(world.x, world.y, world.z, 1); - Vec4F transformed = viewMat * world_pos4; - transformed = projMat * transformed; - return {transformed[0] / transformed[3], transformed[1] / transformed[3]}; + Vec4F world_pos4(world.x, world.y, world.z, 1); + Vec4F transformed = viewMat * world_pos4; + transformed = projMat * transformed; + return { transformed[0] / transformed[3], transformed[1] / transformed[3] }; } void Camera::lookAtPoint(const Vec3F& aTarget, const Vec3F& aPos, Vec3F aUp) { - if (aTarget == aPos) { - return; - } - mPos = aPos; - mTarget = aTarget; - Vec3F f = (mPos - mTarget).normalize(); - mUp = f * (aUp.normalize() * f); + if (aTarget == aPos) { + return; + } + mPos = aPos; + mTarget = aTarget; + Vec3F f = (mPos - mTarget).normalize(); + mUp = f * (aUp.normalize() * f); } void Camera::zoom(halnf ratio) { - ratio = abs(ratio); - if (ratio < 0.1f) { - return; - } - if (abs((mPos - mTarget).length2()) < 0.05f && ratio < 1.f) { - return; - } - mPos = mTarget + (mPos - mTarget) * ratio; - lookAtPoint(mTarget, mPos, mUp); + ratio = abs(ratio); + if (ratio < 0.1f) { + return; + } + if (abs((mPos - mTarget).length2()) < 0.05f && ratio < 1.f) { + return; + } + mPos = mTarget + (mPos - mTarget) * ratio; + lookAtPoint(mTarget, mPos, mUp); } void Camera::move(Vec2F aPos, Vec2F aPrevPos) { - Vec3F p1 = project(aPrevPos); - Vec3F p2 = project(aPos); - Vec3F move = p1 - p2; - mPos += move; - mTarget += move; - lookAtPoint(mTarget, mPos, mUp); + Vec3F p1 = project(aPrevPos); + Vec3F p2 = project(aPos); + Vec3F move = p1 - p2; + mPos += move; + mTarget += move; + lookAtPoint(mTarget, mPos, mUp); } void Camera::rotate(halnf angleX, halnf angleY) { - Vec3F wup(0, 0, 1); - mPos -= mTarget; + Vec3F wup(0, 0, 1); + mPos -= mTarget; - mat3f rotZ = mat3f::rotatorDir(wup, angleX); - mPos = rotZ * mPos; - mUp = rotZ * mUp; + mat3f rotZ = mat3f::rotatorDir(wup, angleX); + mPos = rotZ * mPos; + mUp = rotZ * mUp; - Vec3F f = mPos.unitV(); - Vec3F s = mUp * f; + Vec3F f = mPos.unitV(); + Vec3F s = mUp * f; - mPos = mat3f::rotatorDir(s, -angleY) * mPos; + mPos = mat3f::rotatorDir(s, -angleY) * mPos; - mPos += mTarget; + mPos += mTarget; - lookAtPoint(mTarget, mPos, mUp); + lookAtPoint(mTarget, mPos, mUp); } diff --git a/Math/private/Color.cpp b/Math/private/Color.cpp index 22741e3..de16799 100644 --- a/Math/private/Color.cpp +++ b/Math/private/Color.cpp @@ -1,169 +1,169 @@ - -#include "Color.hpp" - -using namespace tp; - -RGB::RGB() { r = g = b = 1.f; } -RGB::RGB(flt4 pr, flt4 pg, flt4 pb) { set(pr, pg, pb); } -RGB::RGB(flt4 val) { set(val, val, val); } - -void RGB::set(flt4 pr, flt4 pg, flt4 pb) { - r = pr; - b = pb; - g = pg; -} - -RGB::operator HSV() const { - - HSV out; - alnf min, max, delta; - - min = r < g ? r : g; - min = min < b ? min : b; - max = r > g ? r : g; - max = max > b ? max : b; - - out.v = (halnf) max; - delta = max - min; - - if (delta < 0.00001) { - out.s = 0; - // undefined, maybe nan? - out.h = 0; - return out; - } - if (max > 0.f) { - // NOTE: if Max is == 0, this divide would cause a crash - out.s = (halnf) (delta / max); - - } else { - // if max is 0, then r = g = b = 0 - // s = 0, h is undefined - out.s = 0.f; - out.h = 0.f; - return out; - } - if (r >= max) { - // between yellow & magenta - out.h = (halnf) ((g - b) / delta); - } else { - if (g >= max) { - // between cyan & yellow - out.h = (halnf) (2.0 + (b - r) / delta); - } else { - // between magenta & cyan - out.h = (halnf) (4.0 + (r - g) / delta); - } - } - - out.h *= 60.f; - - if (out.h < 0.0) { - out.h += 360.f; - } - - out.h = (halnf) (out.h / 360.f * (PI2)); - - return out; -} - -HSV::HSV() { h = s = v = 0.f; } - -HSV::HSV(flt4 ph, flt4 ps, flt4 pv) { set(ph, ps, pv); } - -void HSV::set(flt4 ph, flt4 ps, flt4 pv) { - h = ph; - s = ps; - v = pv; -} - -HSV::operator RGB() const { - alnf hh, p, q, t, ff; - alni i; - RGB out; - - if (s <= 0.0) { // < is bogus, just shuts up warnings - out.r = v; - out.g = v; - out.b = v; - return out; - } - - hh = h / (PI2) * 360; - - if (hh >= 360.0) { - hh = 0.0; - } - - hh /= 60.0; - i = (long) hh; - ff = hh - i; - p = v * (1.0 - s); - q = v * (1.0 - (s * ff)); - t = v * (1.0 - (s * (1.0 - ff))); - - switch (i) { - case 0: - out.r = (halnf) v; - out.g = (halnf) t; - out.b = (halnf) p; - break; - case 1: - out.r = (halnf) q; - out.g = (halnf) v; - out.b = (halnf) p; - break; - case 2: - out.r = (halnf) p; - out.g = (halnf) v; - out.b = (halnf) t; - break; - - case 3: - out.r = (halnf) p; - out.g = (halnf) q; - out.b = (halnf) v; - break; - case 4: - out.r = (halnf) t; - out.g = (halnf) p; - out.b = (halnf) v; - break; - case 5: - default: - out.r = (halnf) v; - out.g = (halnf) p; - out.b = (halnf) q; - break; - } - return out; -} - -/* -struct rgbab { - - uint4 RGBA; - - rgbab() { RGBA = 0xFFFFFFFF; } - rgbab(uint4 color) { RGBA = color; } - rgbab(uint1 r, uint1 b, uint1 g, uint1 a) { set(r, b, g, a); } - rgbab(const rgbab& in) { RGBA = in.RGBA; } - - void set(uint4 color) { RGBA = color; } - void set(uint1 r, uint1 b, uint1 g, uint1 a) { - RGBA = (uint1)(a); - RGBA <<= 8; RGBA |= (uint1)(r); - RGBA <<= 8; RGBA |= (uint1)(g); - RGBA <<= 8; RGBA |= (uint1)(b); - } - - operator rgbaf() { - rgbaf out; - out.r = uint1((RGBA & 0x00FF0000) >> 16) / 255.f; - out.g = uint1((RGBA & 0x0000FF00) >> 8) / 255.f; - out.b = uint1(RGBA & 0x000000FF) / 255.f; - out.a = uint1((RGBA & 0xFF000000) >> 24) / 255.f; - return out; - } -}; + +#include "Color.hpp" + +using namespace tp; + +RGB::RGB() { r = g = b = 1.f; } +RGB::RGB(flt4 pr, flt4 pg, flt4 pb) { set(pr, pg, pb); } +RGB::RGB(flt4 val) { set(val, val, val); } + +void RGB::set(flt4 pr, flt4 pg, flt4 pb) { + r = pr; + b = pb; + g = pg; +} + +RGB::operator HSV() const { + + HSV out; + alnf min, max, delta; + + min = r < g ? r : g; + min = min < b ? min : b; + max = r > g ? r : g; + max = max > b ? max : b; + + out.v = (halnf) max; + delta = max - min; + + if (delta < 0.00001) { + out.s = 0; + // undefined, maybe nan? + out.h = 0; + return out; + } + if (max > 0.f) { + // NOTE: if Max is == 0, this divide would cause a crash + out.s = (halnf) (delta / max); + + } else { + // if max is 0, then r = g = b = 0 + // s = 0, h is undefined + out.s = 0.f; + out.h = 0.f; + return out; + } + if (r >= max) { + // between yellow & magenta + out.h = (halnf) ((g - b) / delta); + } else { + if (g >= max) { + // between cyan & yellow + out.h = (halnf) (2.0 + (b - r) / delta); + } else { + // between magenta & cyan + out.h = (halnf) (4.0 + (r - g) / delta); + } + } + + out.h *= 60.f; + + if (out.h < 0.0) { + out.h += 360.f; + } + + out.h = (halnf) (out.h / 360.f * (PI2)); + + return out; +} + +HSV::HSV() { h = s = v = 0.f; } + +HSV::HSV(flt4 ph, flt4 ps, flt4 pv) { set(ph, ps, pv); } + +void HSV::set(flt4 ph, flt4 ps, flt4 pv) { + h = ph; + s = ps; + v = pv; +} + +HSV::operator RGB() const { + alnf hh, p, q, t, ff; + alni i; + RGB out; + + if (s <= 0.0) { // < is bogus, just shuts up warnings + out.r = v; + out.g = v; + out.b = v; + return out; + } + + hh = h / (PI2) *360; + + if (hh >= 360.0) { + hh = 0.0; + } + + hh /= 60.0; + i = (long) hh; + ff = hh - i; + p = v * (1.0 - s); + q = v * (1.0 - (s * ff)); + t = v * (1.0 - (s * (1.0 - ff))); + + switch (i) { + case 0: + out.r = (halnf) v; + out.g = (halnf) t; + out.b = (halnf) p; + break; + case 1: + out.r = (halnf) q; + out.g = (halnf) v; + out.b = (halnf) p; + break; + case 2: + out.r = (halnf) p; + out.g = (halnf) v; + out.b = (halnf) t; + break; + + case 3: + out.r = (halnf) p; + out.g = (halnf) q; + out.b = (halnf) v; + break; + case 4: + out.r = (halnf) t; + out.g = (halnf) p; + out.b = (halnf) v; + break; + case 5: + default: + out.r = (halnf) v; + out.g = (halnf) p; + out.b = (halnf) q; + break; + } + return out; +} + +/* +struct rgbab { + + uint4 RGBA; + + rgbab() { RGBA = 0xFFFFFFFF; } + rgbab(uint4 color) { RGBA = color; } + rgbab(uint1 r, uint1 b, uint1 g, uint1 a) { set(r, b, g, a); } + rgbab(const rgbab& in) { RGBA = in.RGBA; } + + void set(uint4 color) { RGBA = color; } + void set(uint1 r, uint1 b, uint1 g, uint1 a) { + RGBA = (uint1)(a); + RGBA <<= 8; RGBA |= (uint1)(r); + RGBA <<= 8; RGBA |= (uint1)(g); + RGBA <<= 8; RGBA |= (uint1)(b); + } + + operator rgbaf() { + rgbaf out; + out.r = uint1((RGBA & 0x00FF0000) >> 16) / 255.f; + out.g = uint1((RGBA & 0x0000FF00) >> 8) / 255.f; + out.b = uint1(RGBA & 0x000000FF) / 255.f; + out.a = uint1((RGBA & 0xFF000000) >> 24) / 255.f; + return out; + } +}; */ \ No newline at end of file diff --git a/Math/private/MathCommon.cpp b/Math/private/MathCommon.cpp index 4ee0ef7..d2ef70d 100644 --- a/Math/private/MathCommon.cpp +++ b/Math/private/MathCommon.cpp @@ -1,43 +1,40 @@ - -#include "MathCommon.hpp" - -#include "ContainersCommon.hpp" - -static tp::ModuleManifest* sModuleDependencies[] = { - &tp::gModuleContainers, - nullptr -}; - -tp::ModuleManifest tp::gModuleMath = ModuleManifest("Math", nullptr, nullptr, sModuleDependencies); - -tp::alnf std_sin(tp::alnf radians); -tp::alnf std_tan(tp::alnf radians); -tp::alnf std_cos(tp::alnf radians); -tp::alnf std_acos(tp::alnf val); -tp::alnf std_sqrt(tp::alnf val); -tp::alnf std_rad(tp::alnf val); -tp::alnf std_deg(tp::alnf val); -tp::alnf std_atan2(tp::alnf X, tp::alnf Y); -tp::alnf std_atan(tp::alnf val); - -tp::alnf tp::sin(const tp::alnf radians) { return std_sin((halnf) radians); } -tp::alnf tp::tan(const tp::alnf radians) { return std_tan((halnf) radians); } -tp::alnf tp::cos(const tp::alnf radians) { return std_cos((halnf) radians); } -tp::alnf tp::acos(const tp::alnf val) { return std_acos((halnf) val); } -tp::alnf tp::sqrt(const tp::alnf val) { return std_sqrt((halnf) val); } -tp::alnf tp::rad(const tp::alnf val) { return val * (PI / 180.f); } -tp::alnf tp::deg(const tp::alnf val) { return val * (180.f / PI); } -tp::alnf tp::atan2(const tp::alnf X, const tp::alnf Y) { return std_atan2((halnf) X, (halnf) Y); } -tp::alnf tp::atan(const tp::alnf val) { return std_atan((halnf) val); } - -#include - -tp::alnf std_sin(const tp::alnf radians) { return sinf((tp::halnf)radians); } -tp::alnf std_tan(const tp::alnf radians) { return tanf((tp::halnf)radians); } -tp::alnf std_cos(const tp::alnf radians) { return cosf((tp::halnf)radians); } -tp::alnf std_acos(const tp::alnf val) { return acos((tp::halnf)val); } -tp::alnf std_sqrt(const tp::alnf val) { return sqrt((tp::halnf)val); } -tp::alnf std_rad(const tp::alnf val) { return val * (PI / 180.f); } -tp::alnf std_deg(const tp::alnf val) { return val * (180.f / PI); } -tp::alnf std_atan2(const tp::alnf X, const tp::alnf Y) { return atan2((tp::halnf)X, (tp::halnf)Y); } -tp::alnf std_atan(const tp::alnf val) { return atan((tp::halnf)val); } \ No newline at end of file + +#include "MathCommon.hpp" + +#include "ContainersCommon.hpp" + +static tp::ModuleManifest* sModuleDependencies[] = { &tp::gModuleContainers, nullptr }; + +tp::ModuleManifest tp::gModuleMath = ModuleManifest("Math", nullptr, nullptr, sModuleDependencies); + +tp::alnf std_sin(tp::alnf radians); +tp::alnf std_tan(tp::alnf radians); +tp::alnf std_cos(tp::alnf radians); +tp::alnf std_acos(tp::alnf val); +tp::alnf std_sqrt(tp::alnf val); +tp::alnf std_rad(tp::alnf val); +tp::alnf std_deg(tp::alnf val); +tp::alnf std_atan2(tp::alnf X, tp::alnf Y); +tp::alnf std_atan(tp::alnf val); + +tp::alnf tp::sin(const tp::alnf radians) { return std_sin((halnf) radians); } +tp::alnf tp::tan(const tp::alnf radians) { return std_tan((halnf) radians); } +tp::alnf tp::cos(const tp::alnf radians) { return std_cos((halnf) radians); } +tp::alnf tp::acos(const tp::alnf val) { return std_acos((halnf) val); } +tp::alnf tp::sqrt(const tp::alnf val) { return std_sqrt((halnf) val); } +tp::alnf tp::rad(const tp::alnf val) { return val * (PI / 180.f); } +tp::alnf tp::deg(const tp::alnf val) { return val * (180.f / PI); } +tp::alnf tp::atan2(const tp::alnf X, const tp::alnf Y) { return std_atan2((halnf) X, (halnf) Y); } +tp::alnf tp::atan(const tp::alnf val) { return std_atan((halnf) val); } + +#include + +tp::alnf std_sin(const tp::alnf radians) { return sinf((tp::halnf) radians); } +tp::alnf std_tan(const tp::alnf radians) { return tanf((tp::halnf) radians); } +tp::alnf std_cos(const tp::alnf radians) { return cosf((tp::halnf) radians); } +tp::alnf std_acos(const tp::alnf val) { return acos((tp::halnf) val); } +tp::alnf std_sqrt(const tp::alnf val) { return sqrt((tp::halnf) val); } +tp::alnf std_rad(const tp::alnf val) { return val * (PI / 180.f); } +tp::alnf std_deg(const tp::alnf val) { return val * (180.f / PI); } +tp::alnf std_atan2(const tp::alnf X, const tp::alnf Y) { return atan2((tp::halnf) X, (tp::halnf) Y); } +tp::alnf std_atan(const tp::alnf val) { return atan((tp::halnf) val); } \ No newline at end of file diff --git a/Math/private/Ray.cpp b/Math/private/Ray.cpp index d9f2cbd..bce97ce 100644 --- a/Math/private/Ray.cpp +++ b/Math/private/Ray.cpp @@ -1,9 +1,9 @@ - -#include "Ray.hpp" - -using namespace tp; - -Ray::Ray(const Vec3F& aDir, const Vec3F& aPos) { - this->dir = aDir.unitV(); - this->pos = aPos; + +#include "Ray.hpp" + +using namespace tp; + +Ray::Ray(const Vec3F& aDir, const Vec3F& aPos) { + this->dir = aDir.unitV(); + this->pos = aPos; } \ No newline at end of file diff --git a/Math/private/Topology.cpp b/Math/private/Topology.cpp index 4b1d534..592f9c7 100644 --- a/Math/private/Topology.cpp +++ b/Math/private/Topology.cpp @@ -1,104 +1,110 @@ - -#include "Topology.hpp" - -void* operator new(std::size_t, void* in) { return in; } - -using namespace tp; - -Vec3F TrigCache::gHitPos; - -TrigCache::TrigCache() : mP1(0), mP2(0), mP3(0) {} - -TrigCache::TrigCache(ualni v1, ualni v2, ualni v3) : mP1(v1), mP2(v2), mP3(v3) {} - -TrigCache::TrigCache(const TrigCache& in) { - mP1 = in.mP1; - mP2 = in.mP2; - mP3 = in.mP3; - - mEdgeP1P2 = in.mEdgeP1P2; - mEdgeP1P3 = in.mEdgeP1P3; - - mOrigin = in.mOrigin; - mNormal = in.mNormal; -} - -void TrigCache::updateCache(const Buffer& points) { - mOrigin = points[mP1]; - mEdgeP1P2 = points[mP2] - points[mP1]; - mEdgeP1P3 = points[mP3] - points[mP1]; - mNormal = (points[mP2] - points[mP1]).cross(points[mP3] - points[mP1]).unitV(); -} - -bool TrigCache::castRay(const Ray& ray) const { - static Vec3F h, s, q; - static halnf a, f, u, v; - static halnf t; - - if (ray.dir.dot(mNormal) > 0) { - return false; - } - - h = ray.dir.cross(mEdgeP1P3); - a = mEdgeP1P2.dot(h); - - if (a > -EPSILON && a < EPSILON) { - return false; - } - - f = 1.f / a; - s = ray.pos - mOrigin; - u = f * s.dot(h); - - if (u < 0.0 || u > 1.0) { - return false; - } - - q = s.cross(mEdgeP1P2); - v = f * ray.dir.dot(q); - - if (v < 0.f || u + v > 1.f) { - return false; - } - - t = f * mEdgeP1P3.dot(q); - if (t > EPSILON) { - gHitPos = ray.pos + ray.dir * t; - return true; - } else { - return false; - } -} - -const Vec3F& TrigCache::getHitPos() { return gHitPos; } - -const Vec3F& TrigCache::getNormal() const { return mNormal; } - -void TopologyCache::updateCache() { - TransformedNormals.clear(); - TransformedPoints.clear(); - TrigCaches.clear(); - - if (!Source) { - return; - } - - TransformedPoints.reserve(Source->Points.size()); - for (auto idx : Range(TransformedPoints.size())) { - TransformedPoints[idx] = Source->Basis.transform(Source->Points[idx]); - TransformedPoints[idx] += Source->Origin; - } - - TransformedNormals.reserve(Source->Normals.size()); - for (auto idx : Range(TransformedNormals.size())) { - TransformedNormals[idx] = Source->Basis.transform(Source->Normals[idx]); - } - - TrigCaches.reserve(Source->Indexes.size()); - for (auto idx : Range(TrigCaches.size())) { - TrigCaches[idx].mP1 = Source->Indexes[idx].x; - TrigCaches[idx].mP2 = Source->Indexes[idx].y; - TrigCaches[idx].mP3 = Source->Indexes[idx].z; - TrigCaches[idx].updateCache(TransformedPoints); - } -} + +#include "Topology.hpp" + +void* operator new(std::size_t, void* in) { return in; } + +using namespace tp; + +Vec3F TrigCache::gHitPos; + +TrigCache::TrigCache() : + mP1(0), + mP2(0), + mP3(0) {} + +TrigCache::TrigCache(ualni v1, ualni v2, ualni v3) : + mP1(v1), + mP2(v2), + mP3(v3) {} + +TrigCache::TrigCache(const TrigCache& in) { + mP1 = in.mP1; + mP2 = in.mP2; + mP3 = in.mP3; + + mEdgeP1P2 = in.mEdgeP1P2; + mEdgeP1P3 = in.mEdgeP1P3; + + mOrigin = in.mOrigin; + mNormal = in.mNormal; +} + +void TrigCache::updateCache(const Buffer& points) { + mOrigin = points[mP1]; + mEdgeP1P2 = points[mP2] - points[mP1]; + mEdgeP1P3 = points[mP3] - points[mP1]; + mNormal = (points[mP2] - points[mP1]).cross(points[mP3] - points[mP1]).unitV(); +} + +bool TrigCache::castRay(const Ray& ray) const { + static Vec3F h, s, q; + static halnf a, f, u, v; + static halnf t; + + if (ray.dir.dot(mNormal) > 0) { + return false; + } + + h = ray.dir.cross(mEdgeP1P3); + a = mEdgeP1P2.dot(h); + + if (a > -EPSILON && a < EPSILON) { + return false; + } + + f = 1.f / a; + s = ray.pos - mOrigin; + u = f * s.dot(h); + + if (u < 0.0 || u > 1.0) { + return false; + } + + q = s.cross(mEdgeP1P2); + v = f * ray.dir.dot(q); + + if (v < 0.f || u + v > 1.f) { + return false; + } + + t = f * mEdgeP1P3.dot(q); + if (t > EPSILON) { + gHitPos = ray.pos + ray.dir * t; + return true; + } else { + return false; + } +} + +const Vec3F& TrigCache::getHitPos() { return gHitPos; } + +const Vec3F& TrigCache::getNormal() const { return mNormal; } + +void TopologyCache::updateCache() { + TransformedNormals.clear(); + TransformedPoints.clear(); + TrigCaches.clear(); + + if (!Source) { + return; + } + + TransformedPoints.reserve(Source->Points.size()); + for (auto idx : Range(TransformedPoints.size())) { + TransformedPoints[idx] = Source->Basis.transform(Source->Points[idx]); + TransformedPoints[idx] += Source->Origin; + } + + TransformedNormals.reserve(Source->Normals.size()); + for (auto idx : Range(TransformedNormals.size())) { + TransformedNormals[idx] = Source->Basis.transform(Source->Normals[idx]); + } + + TrigCaches.reserve(Source->Indexes.size()); + for (auto idx : Range(TrigCaches.size())) { + TrigCaches[idx].mP1 = Source->Indexes[idx].x; + TrigCaches[idx].mP2 = Source->Indexes[idx].y; + TrigCaches[idx].mP3 = Source->Indexes[idx].z; + TrigCaches[idx].updateCache(TransformedPoints); + } +} diff --git a/Math/private/Trig.cpp b/Math/private/Trig.cpp index b4212da..3bd22db 100644 --- a/Math/private/Trig.cpp +++ b/Math/private/Trig.cpp @@ -1,72 +1,72 @@ - -#include "Trig.hpp" - -#include "Ray.hpp" - -using namespace tp; - -Trig::Trig() { - MODULE_SANITY_CHECK(gModuleMath) - p1.assign(0.f, 0.f, 0.f); - p2.assign(0.f, 0.f, 0.f); - p3.assign(0.f, 0.f, 0.f); -} - -Trig::Trig(const Vec3F& v0, const Vec3F& v1, const Vec3F& v2) { - p1 = v0; - p2 = v1; - p3 = v2; -} - -void Trig::assign(const Vec3F& v0, const Vec3F& v1, const Vec3F& v2) { - p1 = v0; - p2 = v1; - p3 = v2; -} - -Trig::~Trig() = default; - -void Trig::normal(Vec3F& dir) const { - dir = (p2 - p1).cross(p3 - p1); - dir.normalize(); -} - -Vec3F edge1, edge2, h, s, q; -halnf a, f, u, v; -halnf t; - -bool Trig::rayHit(class Ray& ray, Vec3F& HitPos) const { - - edge1 = p2 - p1; - edge2 = p3 - p1; - - h = ray.dir.cross(edge2); - a = edge1.dot(h); - - if (a > -EPSILON && a < EPSILON) { - return false; - } - - f = 1.f / a; - s = ray.pos - p1; - u = f * s.dot(h); - - if (u < 0.0 || u > 1.0) { - return false; - } - - q = s.cross(edge1); - v = f * ray.dir.dot(q); - - if (v < 0.f || u + v > 1.f) { - return false; - } - - t = f * edge2.dot(q); - if (t > EPSILON) { - HitPos = ray.pos + ray.dir * t; - return true; - } else { - return false; - } -} + +#include "Trig.hpp" + +#include "Ray.hpp" + +using namespace tp; + +Trig::Trig() { + MODULE_SANITY_CHECK(gModuleMath) + p1.assign(0.f, 0.f, 0.f); + p2.assign(0.f, 0.f, 0.f); + p3.assign(0.f, 0.f, 0.f); +} + +Trig::Trig(const Vec3F& v0, const Vec3F& v1, const Vec3F& v2) { + p1 = v0; + p2 = v1; + p3 = v2; +} + +void Trig::assign(const Vec3F& v0, const Vec3F& v1, const Vec3F& v2) { + p1 = v0; + p2 = v1; + p3 = v2; +} + +Trig::~Trig() = default; + +void Trig::normal(Vec3F& dir) const { + dir = (p2 - p1).cross(p3 - p1); + dir.normalize(); +} + +Vec3F edge1, edge2, h, s, q; +halnf a, f, u, v; +halnf t; + +bool Trig::rayHit(class Ray& ray, Vec3F& HitPos) const { + + edge1 = p2 - p1; + edge2 = p3 - p1; + + h = ray.dir.cross(edge2); + a = edge1.dot(h); + + if (a > -EPSILON && a < EPSILON) { + return false; + } + + f = 1.f / a; + s = ray.pos - p1; + u = f * s.dot(h); + + if (u < 0.0 || u > 1.0) { + return false; + } + + q = s.cross(edge1); + v = f * ray.dir.dot(q); + + if (v < 0.f || u + v > 1.f) { + return false; + } + + t = f * edge2.dot(q); + if (t > EPSILON) { + HitPos = ray.pos + ray.dir * t; + return true; + } else { + return false; + } +} diff --git a/Math/public/Camera.hpp b/Math/public/Camera.hpp index 0d21c9e..4096f81 100644 --- a/Math/public/Camera.hpp +++ b/Math/public/Camera.hpp @@ -4,43 +4,43 @@ #include "Ray.hpp" namespace tp { - class Camera { - Vec3F mPos, mTarget, mUp; - halnf mFOV = (halnf) (PI) / 4; - halnf mNear = 0.001f; - halnf mFar = 100.f; - halnf mRatio = 1.f; + class Camera { + Vec3F mPos, mTarget, mUp; + halnf mFOV = (halnf) (PI) / 4; + halnf mNear = 0.001f; + halnf mFar = 100.f; + halnf mRatio = 1.f; - public: - Camera(); - ~Camera() = default; + public: + Camera(); + ~Camera() = default; - void setRatio(halnf ratio); - void setFOV(halnf fov); - void setFar(halnf far); + void setRatio(halnf ratio); + void setFOV(halnf fov); + void setFar(halnf far); - [[nodiscard]] const Vec3F& getPos() const; - [[nodiscard]] const Vec3F& getTarget() const; - [[nodiscard]] Vec3F getForward() const; - [[nodiscard]] const Vec3F& getUp() const; - [[nodiscard]] halnf getRatio() const; - [[nodiscard]] halnf getFOV() const; - [[nodiscard]] halnf getFar() const; - [[nodiscard]] halnf getNear() const; + [[nodiscard]] const Vec3F& getPos() const; + [[nodiscard]] const Vec3F& getTarget() const; + [[nodiscard]] Vec3F getForward() const; + [[nodiscard]] const Vec3F& getUp() const; + [[nodiscard]] halnf getRatio() const; + [[nodiscard]] halnf getFOV() const; + [[nodiscard]] halnf getFar() const; + [[nodiscard]] halnf getNear() const; - public: - void lookAtPoint(const Vec3F& aTarget, const Vec3F& aPos, Vec3F aUp); - void rotate(halnf anglex, halnf angleY); - void move(Vec2F aPos, Vec2F aPrevPos); - void zoom(halnf ratio); - void offset_target(halnf val); + public: + void lookAtPoint(const Vec3F& aTarget, const Vec3F& aPos, Vec3F aUp); + void rotate(halnf anglex, halnf angleY); + void move(Vec2F aPos, Vec2F aPrevPos); + void zoom(halnf ratio); + void offset_target(halnf val); - public: - [[nodiscard]] Mat4F calculateTransformationMatrix(); - [[nodiscard]] Mat calculateProjectionMatrix() const; - [[nodiscard]] Mat calculateViewMatrix(); - [[nodiscard]] Vec3F project(Vec2F normalized); - [[nodiscard]] Vec2F project(const Vec3F& world); - [[nodiscard]] static Vec2F project(const tp::Vec3F& world, const tp::Mat4F& viewMat, const tp::Mat4F& projMat); - }; + public: + [[nodiscard]] Mat4F calculateTransformationMatrix(); + [[nodiscard]] Mat calculateProjectionMatrix() const; + [[nodiscard]] Mat calculateViewMatrix(); + [[nodiscard]] Vec3F project(Vec2F normalized); + [[nodiscard]] Vec2F project(const Vec3F& world); + [[nodiscard]] static Vec2F project(const tp::Vec3F& world, const tp::Mat4F& viewMat, const tp::Mat4F& projMat); + }; } diff --git a/Math/public/Color.hpp b/Math/public/Color.hpp index 505bff9..f7d46cc 100644 --- a/Math/public/Color.hpp +++ b/Math/public/Color.hpp @@ -1,90 +1,100 @@ -#pragma once - -#include "Vec.hpp" - -namespace tp { - - class RGB; - class HSV; - - class RGB { - public: - RGB(); - RGB(flt4 pr, flt4 pg, flt4 pb); - RGB(flt4 val); - - public: - void set(flt4 pr, flt4 pg, flt4 pb); - operator HSV() const; - - public: - halnf r, g, b; - }; - - class HSV { - public: - HSV(); - HSV(flt4 ph, flt4 ps, flt4 pv); - - public: - void set(flt4 ph, flt4 ps, flt4 pv); - operator RGB() const; - - public: - halnf h, s, v; - }; - - class RGBA { - public: - RGBA() : r(0), g(0), b(0), a(0) {} - - RGBA(flt4 val) : rgbs(val), a(val) {} - - RGBA(const RGB& RGBs, flt4 val) : rgbs(RGBs), a(val) {} - - RGBA(flt4 pr, flt4 pg, flt4 pb, flt4 pa) : rgbs(pr, pg, pb), a(pa) {} - - public: - RGBA& operator=(const HSV& in) { - rgbs = in; - a = 1; - return *this; - } - - RGBA operator-(const RGBA& in) const { - const auto nr = tp::clamp(r - in.r, 0.f, 1.f); - const auto ng = tp::clamp(g - in.g, 0.f, 1.f); - const auto nb = tp::clamp(b - in.b, 0.f, 1.f); - const auto na = tp::clamp(a - in.a, 0.f, 1.f); - return {nr, ng, nb, na}; - } - - RGBA operator+(const RGBA& in) const { - const auto nr = tp::clamp(r + in.r, 0.f, 1.f); - const auto ng = tp::clamp(g + in.g, 0.f, 1.f); - const auto nb = tp::clamp(b + in.b, 0.f, 1.f); - const auto na = tp::clamp(a + in.a, 0.f, 1.f); - return {nr, ng, nb, na}; - } - - bool operator==(const RGBA& in) const { return r == in.r && g == in.g && b == in.b && a == in.a; } - - public: - flt4 a; - - union { - RGB rgbs; - - struct { - flt4 r; - flt4 g; - flt4 b; - }; - }; - }; - - class HSVA { - HSV rgbs; - flt4 a = 1.f; - }; -} +#pragma once + +#include "Vec.hpp" + +namespace tp { + + class RGB; + class HSV; + + class RGB { + public: + RGB(); + RGB(flt4 pr, flt4 pg, flt4 pb); + RGB(flt4 val); + + public: + void set(flt4 pr, flt4 pg, flt4 pb); + operator HSV() const; + + public: + halnf r, g, b; + }; + + class HSV { + public: + HSV(); + HSV(flt4 ph, flt4 ps, flt4 pv); + + public: + void set(flt4 ph, flt4 ps, flt4 pv); + operator RGB() const; + + public: + halnf h, s, v; + }; + + class RGBA { + public: + RGBA() : + r(0), + g(0), + b(0), + a(0) {} + + RGBA(flt4 val) : + rgbs(val), + a(val) {} + + RGBA(const RGB& RGBs, flt4 val) : + rgbs(RGBs), + a(val) {} + + RGBA(flt4 pr, flt4 pg, flt4 pb, flt4 pa) : + rgbs(pr, pg, pb), + a(pa) {} + + public: + RGBA& operator=(const HSV& in) { + rgbs = in; + a = 1; + return *this; + } + + RGBA operator-(const RGBA& in) const { + const auto nr = tp::clamp(r - in.r, 0.f, 1.f); + const auto ng = tp::clamp(g - in.g, 0.f, 1.f); + const auto nb = tp::clamp(b - in.b, 0.f, 1.f); + const auto na = tp::clamp(a - in.a, 0.f, 1.f); + return { nr, ng, nb, na }; + } + + RGBA operator+(const RGBA& in) const { + const auto nr = tp::clamp(r + in.r, 0.f, 1.f); + const auto ng = tp::clamp(g + in.g, 0.f, 1.f); + const auto nb = tp::clamp(b + in.b, 0.f, 1.f); + const auto na = tp::clamp(a + in.a, 0.f, 1.f); + return { nr, ng, nb, na }; + } + + bool operator==(const RGBA& in) const { return r == in.r && g == in.g && b == in.b && a == in.a; } + + public: + flt4 a; + + union { + RGB rgbs; + + struct { + flt4 r; + flt4 g; + flt4 b; + }; + }; + }; + + class HSVA { + HSV rgbs; + flt4 a = 1.f; + }; +} diff --git a/Math/public/ComplexNumbers.hpp b/Math/public/ComplexNumbers.hpp index 4eeae1d..35a6c57 100644 --- a/Math/public/ComplexNumbers.hpp +++ b/Math/public/ComplexNumbers.hpp @@ -1,57 +1,57 @@ -#pragma once - -#include "MathCommon.hpp" - -namespace tp { - - struct ComplexCart { - typedef alnf Number; - Number r = 0; - Number i = 0; - - public: - [[nodiscard]] ComplexCart operator*(const ComplexCart& in) const { return {in.r * r - in.i * i, in.r * i + in.i * r}; } - - [[nodiscard]] ComplexCart operator*(Number in) const { return {in * r, in * i}; } - - [[nodiscard]] ComplexCart operator+(const ComplexCart& in) const { return {in.r + r, in.i + i}; } - - [[nodiscard]] ComplexCart operator-(const ComplexCart& in) const { return {in.r - r, in.i - i}; } - - [[nodiscard]] Number mod() const { return tp::sqrt(i * i + r * r); } - - [[nodiscard]] Number arg() const { return atan2(r, i); } - - [[nodiscard]] Number norm2() const { return this->operator*(conjugate()).r; } - - [[nodiscard]] ComplexCart reciprocal() const { return {r / norm2(), -i / norm2()}; } - - void set(Number mod, Number arg) { - r = mod * cos(arg); - i = mod * sin(arg); - } - - bool operator==(const ComplexCart& in) const { return in.r == r && in.i == i; } - - [[nodiscard]] ComplexCart conjugate() const { return {r, -i}; } - }; - - struct ComplexRad { - typedef alnf Number; - Number r = 0; - Number a = 0; - - public: - [[nodiscard]] ComplexRad operator*(const ComplexRad& in) const { return {r * in.r, a + in.a}; } - - [[nodiscard]] ComplexRad operator*(Number in) const { return {r * in, a}; } - - [[nodiscard]] ComplexCart cart() const { - ComplexCart out; - out.set(r, a); - return out; - } - - bool operator==(const ComplexRad& in) const { return in.r == r && in.a == a; } - }; -} +#pragma once + +#include "MathCommon.hpp" + +namespace tp { + + struct ComplexCart { + typedef alnf Number; + Number r = 0; + Number i = 0; + + public: + [[nodiscard]] ComplexCart operator*(const ComplexCart& in) const { return { in.r * r - in.i * i, in.r * i + in.i * r }; } + + [[nodiscard]] ComplexCart operator*(Number in) const { return { in * r, in * i }; } + + [[nodiscard]] ComplexCart operator+(const ComplexCart& in) const { return { in.r + r, in.i + i }; } + + [[nodiscard]] ComplexCart operator-(const ComplexCart& in) const { return { in.r - r, in.i - i }; } + + [[nodiscard]] Number mod() const { return tp::sqrt(i * i + r * r); } + + [[nodiscard]] Number arg() const { return atan2(r, i); } + + [[nodiscard]] Number norm2() const { return this->operator*(conjugate()).r; } + + [[nodiscard]] ComplexCart reciprocal() const { return { r / norm2(), -i / norm2() }; } + + void set(Number mod, Number arg) { + r = mod * cos(arg); + i = mod * sin(arg); + } + + bool operator==(const ComplexCart& in) const { return in.r == r && in.i == i; } + + [[nodiscard]] ComplexCart conjugate() const { return { r, -i }; } + }; + + struct ComplexRad { + typedef alnf Number; + Number r = 0; + Number a = 0; + + public: + [[nodiscard]] ComplexRad operator*(const ComplexRad& in) const { return { r * in.r, a + in.a }; } + + [[nodiscard]] ComplexRad operator*(Number in) const { return { r * in, a }; } + + [[nodiscard]] ComplexCart cart() const { + ComplexCart out; + out.set(r, a); + return out; + } + + bool operator==(const ComplexRad& in) const { return in.r == r && in.a == a; } + }; +} diff --git a/Math/public/Intersections.hpp b/Math/public/Intersections.hpp index 80de87f..843093d 100644 --- a/Math/public/Intersections.hpp +++ b/Math/public/Intersections.hpp @@ -1,34 +1,33 @@ -#pragma once - -#include "Vec.hpp" - -namespace tp { - - template - bool intersectLines2D(const Vec2& p1, const Vec2& p2, const Vec2& v1, const Vec2& v2, Vec2* out) { - auto a1 = p2.x - p1.x; - auto a2 = p2.y - p1.y; - - auto b1 = v2.x - v1.x; - auto b2 = v2.y - v1.y; - - auto c1 = v1.x - p1.x; - auto c2 = v1.y - p1.y; - - auto det = a2 * b1 - a1 * b2; - - auto t1 = ( -b2 * c1 + b1 * c2 ) / det; - auto t2 = ( -a2 * c1 + a1 * c2 ) / det; - - if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) { - if (out != nullptr) { - out->x = p1.x + (a1 * t1); - out->y = p1.y + (a2 * t1); - } - return true; - } - return false; - } - -} - +#pragma once + +#include "Vec.hpp" + +namespace tp { + + template + bool intersectLines2D(const Vec2& p1, const Vec2& p2, const Vec2& v1, const Vec2& v2, Vec2* out) { + auto a1 = p2.x - p1.x; + auto a2 = p2.y - p1.y; + + auto b1 = v2.x - v1.x; + auto b2 = v2.y - v1.y; + + auto c1 = v1.x - p1.x; + auto c2 = v1.y - p1.y; + + auto det = a2 * b1 - a1 * b2; + + auto t1 = (-b2 * c1 + b1 * c2) / det; + auto t2 = (-a2 * c1 + a1 * c2) / det; + + if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) { + if (out != nullptr) { + out->x = p1.x + (a1 * t1); + out->y = p1.y + (a2 * t1); + } + return true; + } + return false; + } + +} diff --git a/Math/public/Mat.hpp b/Math/public/Mat.hpp index 59ce954..967a832 100644 --- a/Math/public/Mat.hpp +++ b/Math/public/Mat.hpp @@ -1,724 +1,710 @@ -#pragma once - -#include "Vec.hpp" - -namespace tp { - - template - class Mat { - typedef Vec MVec; - - private: - MVec mCol[tNColoumns]; - - public: - Mat() = default; - - explicit Mat(const Type& val) { operator=(val); } - - Mat(const Mat& in) { operator=(in); } - - MVec& operator[](alni i) { - DEBUG_ASSERT(i < tNColoumns && i >= 0) - return mCol[i]; - } - - const MVec& operator[](alni i) const { - DEBUG_ASSERT(i < tNColoumns && i >= 0) - return mCol[i]; - } - - Mat& operator=(const Mat& in) { - if (&in == this) { - return *this; - } - memCopy(this, &in, sizeof(Mat)); - return *this; - } - - Mat& operator=(const Type& val) { - clear(val); - return *this; - } - - void clear(const Type& val) { - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - (*this)[i][j] = val; - } - } - } - - void setDiagonal(const Type& val) { - halni len = min(tNColoumns, tNRows); - for (halni i = 0; i < len; i++) { - (*this)[i][i] = val; - } - } - - Mat& fillRandom() { - DEBUG_ASSERT(0) - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - (*this)[i][j] = (Type) 0; - } - } - return *this; - } - - Mat operator-() { - Mat out; - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - out[i][j] = -(*this)[i][j]; - } - } - return out; - } - - Mat& operator+=(const Mat& in) { - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - (*this)[i][j] += in[i][j]; - } - } - return *this; - } - - Mat& operator-=(const Mat& in) { - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - (*this)[i][j] -= in[i][j]; - } - } - return *this; - } - - Mat& operator+=(const Type& val) { - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - (*this)[i][j] += val; - } - } - return *this; - } - - Mat& operator-=(const Type& val) { - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - (*this)[i][j] -= val; - } - } - return *this; - } - - Mat& operator/=(const Type& val) { - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - (*this)[i][j] /= val; - } - } - return *this; - } - - Mat& operator*=(const Type& val) { - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - (*this)[i][j] *= val; - } - } - return *this; - } - - Mat operator+(const Mat& in) { - Mat out; - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - out[i][j] = (*this)[i][j] + in[i]; - } - } - return out; - } - - Mat operator-(const Mat& in) { - Mat out; - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - out[i][j] = (*this)[i][j] - in[i]; - } - } - return out; - } - - Mat operator+(const Type& val) { - Mat out; - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - out[i][j] = (*this)[i][j] + val; - } - } - return out; - } - - Mat operator-(const Type& val) { - Mat out; - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - out[i][j] = (*this)[i][j] - val; - } - } - return out; - } - - Mat operator*(const Type& val) { - Mat out; - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - out[i][j] = (*this)[i][j] * val; - } - } - return out; - } - - Mat operator/(const Type& val) { - Mat out; - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = 0; j < tNRows; j++) { - out[i][j] = (*this)[i][j] / val; - } - } - return out; - } - - // Matrix Properties - MVec transform(const MVec& in) const { - static_assert(tNRows == tNColoumns); - MVec out; - for (halni i = 0; i < tNRows; i++) { - Type tmp = 0; - for (halni j = 0; j < tNColoumns; j++) { - tmp += (*this)[i][j] * in[j]; - } - out[i] = tmp; - } - return out; - } - - Mat transform(const Mat& in) const { - Mat out; - out.clear(0); - for (halni i = 0; i < tNRows; i++) { - for (halni j = 0; j < tNRows; j++) { - for (halni u = 0; u < tNRows; u++) { - out[i][j] += (*this)[i][u] * in[u][j]; - } - } - } - return out; - } - - Mat& transpose() { - static_assert(tNRows == tNColoumns); - for (halni i = 0; i < tNColoumns; i++) { - for (halni j = i + 1; j < tNColoumns; j++) { - swap((*this)[i][j], (*this)[j][i]); - } - } - return *this; - } - - Mat operator*(const Mat& in) const { return transform(in); } - - MVec operator*(const MVec& in) const { return transform(in); } - - Mat minor(halni p, halni q) { - Mat out; - halni i = 0, j = 0; - for (halni row = 0; row < tNRows; row++) { - for (halni col = 0; col < tNRows; col++) { - if (row != p && col != q) { - out[i][j++] = (*this)[row][col]; - if (j == tNRows - 1) { - j = 0; - i++; - } - } - } - } - return out; - } - - Type det() { - static_assert(tNRows == tNColoumns); - - Type out = 0; - - if (tNRows == 1) { - return (*this)[0][0]; - } - if (tNRows == 2) { - return ((*this)[0][0] * (*this)[1][1]) - ((*this)[1][0] * (*this)[0][1]); - } - - halni sign = 1; - for (int i = 0; i < tNRows; i++) { - out += sign * (*this)[0][i] * minor(0, i).det(); - sign = -sign; - } - return out; - } - - Mat cofactors() { - static_assert(tNRows == tNColoumns); - Mat out; - for (int i = 0; i < tNRows; i++) { - for (int j = 0; j < tNRows; j++) { - Type sign = (Type) ((i + j + 2) & 1 ? -1 : 1); - out[i][j] = minor(j, i).det() * sign; - } - } - return out; - } - - Mat inv() { - Type detV = det(); - DEBUG_ASSERT(detV) - return cofactors() /= detV; - } - }; - - template - using Mat2 = Mat; - using Mat2F = Mat2; - - template - class Mat { - typedef Vec MVec; - - MVec i; - MVec j; - - public: - Mat() = default; - - explicit Mat(const Type& val) { operator=(val); } - - Mat(const MVec& pi, const MVec& pj) { - i.x = pi.x; - i.y = pi.y; - j.x = pj.x; - j.y = pj.y; - } - - Mat(Type ix, Type iy, Type jx, Type jy) { - i.x = ix; - i.y = iy; - j.x = jx; - j.y = jy; - } - - Mat(const Mat& in) { operator=(in); } - - MVec& operator[](alni idx) { - DEBUG_ASSERT(idx < 2 && idx >= 0) - return (&i)[idx]; - } - - const MVec& operator[](alni idx) const { - DEBUG_ASSERT(idx < 2 && idx >= 0) - return (&i)[idx]; - } - - Mat& operator=(const Mat& in) { - memCopy(this, &in, sizeof(Mat2)); - return *this; - } - - Mat& operator=(const Type& val) { - clear(val); - return *this; - } - - void clear(const Type& val) { - i.x = val; - i.y = val; - j.x = val; - j.y = val; - } - - void setDiagonal(const Type& val) { - i.x = val; - j.y = val; - } - - Mat& fillRandom() { - DEBUG_ASSERT(0) - i.x = (Type) 0; - i.y = (Type) 0; - j.x = (Type) 0; - j.y = (Type) 0; - return *this; - } - - Mat operator-() { return Mat(-i.x, -i.y, -j.x, -j.y); } - - Mat& operator+=(const Mat& in) { - i.x += in.i.x; - i.y += in.i.y; - j.x += in.j.x; - j.y += in.j.y; - return *this; - } - - Mat& operator-=(const Mat& in) { - i.x -= in.i.x; - i.y -= in.i.y; - j.x -= in.j.x; - j.y -= in.j.y; - return *this; - } - - Mat& operator+=(Type val) { - i.x += val; - i.y += val; - j.x += val; - j.y += val; - return *this; - } - - Mat& operator-=(Type val) { - i.x -= val; - i.y -= val; - j.x -= val; - j.y -= val; - return *this; - } - - Mat& operator/=(Type val) { - i.x /= val; - i.y /= val; - j.x /= val; - j.y /= val; - return *this; - } - - Mat& operator*=(Type val) { - i.x *= val; - i.y *= val; - j.x *= val; - j.y *= val; - return *this; - } - - Mat operator+(const Mat& in) { - Mat out; - out.i.x = i.x + in.i.x; - out.i.y = i.y + in.i.y; - out.j.x = j.x + in.j.x; - out.j.y = j.y + in.j.y; - return out; - } - - Mat operator-(const Mat& in) { - Mat out; - out.i.x = i.x - in.i.x; - out.i.y = i.y - in.i.y; - out.j.x = j.x - in.j.x; - out.j.y = j.y - in.j.y; - return out; - } - - Mat operator+(const Type& val) { - Mat out; - out.i.x = i.x + val; - out.i.y = i.y + val; - out.j.x = j.x + val; - out.j.y = j.y + val; - return out; - } - - Mat operator-(const Type& val) { - Mat out; - out.i.x = i.x - val; - out.i.y = i.y - val; - out.j.x = j.x - val; - out.j.y = j.y - val; - return out; - } - - Mat operator*(const Type& val) { - Mat out; - out.i.x = i.x * val; - out.i.y = i.y * val; - out.j.x = j.x * val; - out.j.y = j.y * val; - return out; - } - - Mat operator/(const Type& val) { - Mat out; - out.i.x = i.x / val; - out.i.y = i.y / val; - out.j.x = j.x / val; - out.j.y = j.y / val; - return out; - } - - // Matrix Properties - MVec transform(const MVec& in) const { return MVec(i.x * in.x + i.y * in.y, j.x * in.y + j.y * in.x); } - - Mat transform(const Mat& in) const { - Mat out; - out.i.x = i.x * in.i.x + j.x * in.i.y; - out.i.y = i.y * in.i.x + j.y * in.i.y; - out.j.x = i.x * in.j.x + j.x * in.j.y; - out.j.y = i.y * in.j.x + j.y * in.j.y; - return out; - } - - Mat operator*(const Mat& in) { return transform(in); } - - Mat& transpose() { - swap(j.x, i.y); - return *this; - } - - Type det() { return i.x * j.y - i.y * j.x; } - - Mat cofactors() { return Mat(j.y, -i.y, -j.x, i.x); } - - Mat inv() { - Type detV = det(); - DEBUG_ASSERT(detV != 0) - return (cofactors() /= detV); - } - }; - - template - using mat3 = Mat; - using mat3f = mat3; - - template - class Mat { - typedef Vec3 vec; - - public: - vec I; - vec J; - vec K; - - public: - Mat() = default; - - explicit Mat(Type val) { - I.assign(val, 0.f, 0.f); - J.assign(0.f, val, 0.f); - K.assign(0.f, 0.f, val); - } - - Mat(const vec& i, const vec& j, const vec& k) { - I = i; - J = j; - K = k; - } - - Mat(const Mat& in) { - this->I = in.I; - this->J = in.J; - this->K = in.K; - } - - void assign(const vec& i, const vec& j, const vec& k) { - I = i; - J = j; - K = k; - } - - Mat& fillRandom() { - I.randf(); - J.randf(); - K.randf(); - return *this; - } - - vec& operator[](alni i) { - DEBUG_ASSERT(i < 3 && i >= 0) - return (&I)[i]; - } - - const vec& operator[](alni i) const { - DEBUG_ASSERT(i < 3 && i >= 0) - return (&I)[i]; - } - - // create on stack - Mat operator+(const Mat& in) { return Mat(I + in.I, J + in.J, K + in.K); } - - Mat operator-(const Mat& in) { return Mat(I - in.I, J - in.J, K - in.K); } - - Mat operator+(Type val) { return Mat(I + val, J + val, K + val); } - - Mat operator-(Type val) { return Mat(I - val, J - val, K - val); } - - Mat operator*(Type val) { return Mat(I * val, J * val, K * val); } - - Mat operator/(Type val) { return Mat(I / val, J / val, K / val); } - - // write - Mat& operator=(const Mat& in) { - I = in.I; - J = in.J; - K = in.K; - return *this; - } - - Mat& operator+=(const Mat& in) { - I += in.I; - J += in.J; - K += in.K; - return *this; - } - - Mat& operator-=(const Mat& in) { - I -= in.I; - J -= in.J; - K -= in.K; - return *this; - } - - Mat& operator+=(Type val) { - I += val; - J += val; - K += val; - return *this; - } - - Mat& operator-=(Type val) { - I -= val; - J -= val; - K -= val; - return *this; - } - - Mat& operator*=(Type val) { - I *= val; - J *= val; - K *= val; - return *this; - } - - Mat& operator/=(Type val) { - I /= val; - J /= val; - K /= val; - return *this; - } - - // Matrix transformation - vec transform(const vec& in) const { return vec(I.x * in.x + I.y * in.y + I.z * in.z, J.x * in.x + J.y * in.y + J.z * in.z, K.x * in.x + K.y * in.y + K.z * in.z); } - - Mat transform(const Mat& in) { - return Mat({(in.I.x * I.x + in.I.y * J.x + in.I.z * K.x), (in.I.x * I.y + in.I.y * J.y + in.I.z * K.y), (in.I.x * I.z + in.I.y * J.z + in.I.z * K.z)}, - {(in.J.x * I.x + in.J.y * J.x + in.J.z * K.x), (in.J.x * I.y + in.J.y * J.y + in.J.z * K.y), (in.J.x * I.z + in.J.y * J.z + in.J.z * K.z)}, - {(in.K.x * I.x + in.K.y * J.x + in.K.z * K.x), (in.K.x * I.y + in.K.y * J.y + in.K.z * K.y), (in.K.x * I.z + in.K.y * J.z + in.K.z * K.z)}); - } - - vec operator*(const vec& in) { return transform(in); } - - Mat operator*(const Mat& in) { return transform(in); } - - Mat minor(halni, halni) { - Mat out; - return out; - } - - Mat& transpose() { - swap(I.y, J.x); - swap(I.z, K.x); - swap(J.z, K.y); - return *this; - } - - Type det() { return (+I.x * (J.y * K.z - J.z * K.y) - I.y * (J.x * K.z - J.z * K.x) + I.z * (J.x * K.y - J.y * K.x)); } - - Mat cofactors() { - return Mat(vec(+(J.y * K.z - J.z * K.y), -(I.y * K.z - I.z * K.y), +(I.y * J.z - I.z * J.y)), - vec(-(J.x * K.z - J.z * K.x), +(I.x * K.z - I.z * K.x), -(I.x * J.z - I.z * J.x)), - vec(+(J.x * K.y - J.y * K.x), -(I.x * K.y - I.y * K.x), +(I.x * J.y - I.y * J.x))); - } - - Mat inv() { return cofactors() /= det(); } - - Mat rotatorX(alnf angle) { - alnf cosA = (alnf) cos(angle); - alnf sinA = (alnf) sin(angle); - return { - {1, 0, 0 }, - {0, cosA, -sinA}, - {0, sinA, cosA } - }; - } - - Mat rotatorY(alnf angle) { - alnf cosA = (alnf) cos(angle); - alnf sinA = (alnf) sin(angle); - return { - {cosA, 0, sinA}, - {0, 1, 0 }, - {-sinA, 0, cosA} - }; - } - - Mat rotatorZ(alnf angle) { - alnf cosA = (alnf) cos(angle); - alnf sinA = (alnf) sin(angle); - return { - {cosA, -sinA, 0}, - {sinA, cosA, 0}, - {0, 0, 1} - }; - } - - static Mat rotatorDir(vec dir, alnf angle) { - dir.normalize(); - - Mat out; - alnf cosA = (alnf) cos(angle); - alnf sinA = (alnf) sin(angle); - alnf tmp = 1 - cosA; - - out.I.x = (Type) (cosA + dir.x * dir.x * tmp); - out.I.y = (Type) (dir.x * dir.y * tmp - dir.z * sinA); - out.I.z = (Type) (dir.x * dir.z * tmp + dir.y * sinA); - - out.J.x = (Type) (dir.y * dir.x * tmp + dir.z * sinA); - out.J.y = (Type) (cosA + dir.y * dir.y * tmp); - out.J.z = (Type) (dir.y * dir.z * tmp - dir.x * sinA); - - out.K.x = (Type) (dir.z * dir.x * tmp - dir.y * sinA); - out.K.y = (Type) (dir.z * dir.y * tmp + dir.x * sinA); - out.K.z = (Type) (cosA + dir.z * dir.z * tmp); - - return out; - } - }; - - template - using Mat4 = Mat; - - using Mat4F = Mat4; - using Mat4I = Mat4; - - template - class Mat { - typedef Vec MVec; - MVec dummy; - - public: - MVec& operator[](alni) { return dummy; } - - const MVec& operator[](alni) const { return dummy; } - - Type det() { return Type(); } - }; -} +#pragma once + +#include "Vec.hpp" + +namespace tp { + + template + class Mat { + typedef Vec MVec; + + private: + MVec mCol[tNColoumns]; + + public: + Mat() = default; + + explicit Mat(const Type& val) { operator=(val); } + + Mat(const Mat& in) { operator=(in); } + + MVec& operator[](alni i) { + DEBUG_ASSERT(i < tNColoumns && i >= 0) + return mCol[i]; + } + + const MVec& operator[](alni i) const { + DEBUG_ASSERT(i < tNColoumns && i >= 0) + return mCol[i]; + } + + Mat& operator=(const Mat& in) { + if (&in == this) { + return *this; + } + memCopy(this, &in, sizeof(Mat)); + return *this; + } + + Mat& operator=(const Type& val) { + clear(val); + return *this; + } + + void clear(const Type& val) { + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + (*this)[i][j] = val; + } + } + } + + void setDiagonal(const Type& val) { + halni len = min(tNColoumns, tNRows); + for (halni i = 0; i < len; i++) { + (*this)[i][i] = val; + } + } + + Mat& fillRandom() { + DEBUG_ASSERT(0) + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + (*this)[i][j] = (Type) 0; + } + } + return *this; + } + + Mat operator-() { + Mat out; + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + out[i][j] = -(*this)[i][j]; + } + } + return out; + } + + Mat& operator+=(const Mat& in) { + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + (*this)[i][j] += in[i][j]; + } + } + return *this; + } + + Mat& operator-=(const Mat& in) { + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + (*this)[i][j] -= in[i][j]; + } + } + return *this; + } + + Mat& operator+=(const Type& val) { + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + (*this)[i][j] += val; + } + } + return *this; + } + + Mat& operator-=(const Type& val) { + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + (*this)[i][j] -= val; + } + } + return *this; + } + + Mat& operator/=(const Type& val) { + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + (*this)[i][j] /= val; + } + } + return *this; + } + + Mat& operator*=(const Type& val) { + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + (*this)[i][j] *= val; + } + } + return *this; + } + + Mat operator+(const Mat& in) { + Mat out; + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + out[i][j] = (*this)[i][j] + in[i]; + } + } + return out; + } + + Mat operator-(const Mat& in) { + Mat out; + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + out[i][j] = (*this)[i][j] - in[i]; + } + } + return out; + } + + Mat operator+(const Type& val) { + Mat out; + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + out[i][j] = (*this)[i][j] + val; + } + } + return out; + } + + Mat operator-(const Type& val) { + Mat out; + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + out[i][j] = (*this)[i][j] - val; + } + } + return out; + } + + Mat operator*(const Type& val) { + Mat out; + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + out[i][j] = (*this)[i][j] * val; + } + } + return out; + } + + Mat operator/(const Type& val) { + Mat out; + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = 0; j < tNRows; j++) { + out[i][j] = (*this)[i][j] / val; + } + } + return out; + } + + // Matrix Properties + MVec transform(const MVec& in) const { + static_assert(tNRows == tNColoumns); + MVec out; + for (halni i = 0; i < tNRows; i++) { + Type tmp = 0; + for (halni j = 0; j < tNColoumns; j++) { + tmp += (*this)[i][j] * in[j]; + } + out[i] = tmp; + } + return out; + } + + Mat transform(const Mat& in) const { + Mat out; + out.clear(0); + for (halni i = 0; i < tNRows; i++) { + for (halni j = 0; j < tNRows; j++) { + for (halni u = 0; u < tNRows; u++) { + out[i][j] += (*this)[i][u] * in[u][j]; + } + } + } + return out; + } + + Mat& transpose() { + static_assert(tNRows == tNColoumns); + for (halni i = 0; i < tNColoumns; i++) { + for (halni j = i + 1; j < tNColoumns; j++) { + swap((*this)[i][j], (*this)[j][i]); + } + } + return *this; + } + + Mat operator*(const Mat& in) const { return transform(in); } + + MVec operator*(const MVec& in) const { return transform(in); } + + Mat minor(halni p, halni q) { + Mat out; + halni i = 0, j = 0; + for (halni row = 0; row < tNRows; row++) { + for (halni col = 0; col < tNRows; col++) { + if (row != p && col != q) { + out[i][j++] = (*this)[row][col]; + if (j == tNRows - 1) { + j = 0; + i++; + } + } + } + } + return out; + } + + Type det() { + static_assert(tNRows == tNColoumns); + + Type out = 0; + + if (tNRows == 1) { + return (*this)[0][0]; + } + if (tNRows == 2) { + return ((*this)[0][0] * (*this)[1][1]) - ((*this)[1][0] * (*this)[0][1]); + } + + halni sign = 1; + for (int i = 0; i < tNRows; i++) { + out += sign * (*this)[0][i] * minor(0, i).det(); + sign = -sign; + } + return out; + } + + Mat cofactors() { + static_assert(tNRows == tNColoumns); + Mat out; + for (int i = 0; i < tNRows; i++) { + for (int j = 0; j < tNRows; j++) { + Type sign = (Type) ((i + j + 2) & 1 ? -1 : 1); + out[i][j] = minor(j, i).det() * sign; + } + } + return out; + } + + Mat inv() { + Type detV = det(); + DEBUG_ASSERT(detV) + return cofactors() /= detV; + } + }; + + template + using Mat2 = Mat; + using Mat2F = Mat2; + + template + class Mat { + typedef Vec MVec; + + MVec i; + MVec j; + + public: + Mat() = default; + + explicit Mat(const Type& val) { operator=(val); } + + Mat(const MVec& pi, const MVec& pj) { + i.x = pi.x; + i.y = pi.y; + j.x = pj.x; + j.y = pj.y; + } + + Mat(Type ix, Type iy, Type jx, Type jy) { + i.x = ix; + i.y = iy; + j.x = jx; + j.y = jy; + } + + Mat(const Mat& in) { operator=(in); } + + MVec& operator[](alni idx) { + DEBUG_ASSERT(idx < 2 && idx >= 0) + return (&i)[idx]; + } + + const MVec& operator[](alni idx) const { + DEBUG_ASSERT(idx < 2 && idx >= 0) + return (&i)[idx]; + } + + Mat& operator=(const Mat& in) { + memCopy(this, &in, sizeof(Mat2)); + return *this; + } + + Mat& operator=(const Type& val) { + clear(val); + return *this; + } + + void clear(const Type& val) { + i.x = val; + i.y = val; + j.x = val; + j.y = val; + } + + void setDiagonal(const Type& val) { + i.x = val; + j.y = val; + } + + Mat& fillRandom() { + DEBUG_ASSERT(0) + i.x = (Type) 0; + i.y = (Type) 0; + j.x = (Type) 0; + j.y = (Type) 0; + return *this; + } + + Mat operator-() { return Mat(-i.x, -i.y, -j.x, -j.y); } + + Mat& operator+=(const Mat& in) { + i.x += in.i.x; + i.y += in.i.y; + j.x += in.j.x; + j.y += in.j.y; + return *this; + } + + Mat& operator-=(const Mat& in) { + i.x -= in.i.x; + i.y -= in.i.y; + j.x -= in.j.x; + j.y -= in.j.y; + return *this; + } + + Mat& operator+=(Type val) { + i.x += val; + i.y += val; + j.x += val; + j.y += val; + return *this; + } + + Mat& operator-=(Type val) { + i.x -= val; + i.y -= val; + j.x -= val; + j.y -= val; + return *this; + } + + Mat& operator/=(Type val) { + i.x /= val; + i.y /= val; + j.x /= val; + j.y /= val; + return *this; + } + + Mat& operator*=(Type val) { + i.x *= val; + i.y *= val; + j.x *= val; + j.y *= val; + return *this; + } + + Mat operator+(const Mat& in) { + Mat out; + out.i.x = i.x + in.i.x; + out.i.y = i.y + in.i.y; + out.j.x = j.x + in.j.x; + out.j.y = j.y + in.j.y; + return out; + } + + Mat operator-(const Mat& in) { + Mat out; + out.i.x = i.x - in.i.x; + out.i.y = i.y - in.i.y; + out.j.x = j.x - in.j.x; + out.j.y = j.y - in.j.y; + return out; + } + + Mat operator+(const Type& val) { + Mat out; + out.i.x = i.x + val; + out.i.y = i.y + val; + out.j.x = j.x + val; + out.j.y = j.y + val; + return out; + } + + Mat operator-(const Type& val) { + Mat out; + out.i.x = i.x - val; + out.i.y = i.y - val; + out.j.x = j.x - val; + out.j.y = j.y - val; + return out; + } + + Mat operator*(const Type& val) { + Mat out; + out.i.x = i.x * val; + out.i.y = i.y * val; + out.j.x = j.x * val; + out.j.y = j.y * val; + return out; + } + + Mat operator/(const Type& val) { + Mat out; + out.i.x = i.x / val; + out.i.y = i.y / val; + out.j.x = j.x / val; + out.j.y = j.y / val; + return out; + } + + // Matrix Properties + MVec transform(const MVec& in) const { return MVec(i.x * in.x + i.y * in.y, j.x * in.y + j.y * in.x); } + + Mat transform(const Mat& in) const { + Mat out; + out.i.x = i.x * in.i.x + j.x * in.i.y; + out.i.y = i.y * in.i.x + j.y * in.i.y; + out.j.x = i.x * in.j.x + j.x * in.j.y; + out.j.y = i.y * in.j.x + j.y * in.j.y; + return out; + } + + Mat operator*(const Mat& in) { return transform(in); } + + Mat& transpose() { + swap(j.x, i.y); + return *this; + } + + Type det() { return i.x * j.y - i.y * j.x; } + + Mat cofactors() { return Mat(j.y, -i.y, -j.x, i.x); } + + Mat inv() { + Type detV = det(); + DEBUG_ASSERT(detV != 0) + return (cofactors() /= detV); + } + }; + + template + using mat3 = Mat; + using mat3f = mat3; + + template + class Mat { + typedef Vec3 vec; + + public: + vec I; + vec J; + vec K; + + public: + Mat() = default; + + explicit Mat(Type val) { + I.assign(val, 0.f, 0.f); + J.assign(0.f, val, 0.f); + K.assign(0.f, 0.f, val); + } + + Mat(const vec& i, const vec& j, const vec& k) { + I = i; + J = j; + K = k; + } + + Mat(const Mat& in) { + this->I = in.I; + this->J = in.J; + this->K = in.K; + } + + void assign(const vec& i, const vec& j, const vec& k) { + I = i; + J = j; + K = k; + } + + Mat& fillRandom() { + I.randf(); + J.randf(); + K.randf(); + return *this; + } + + vec& operator[](alni i) { + DEBUG_ASSERT(i < 3 && i >= 0) + return (&I)[i]; + } + + const vec& operator[](alni i) const { + DEBUG_ASSERT(i < 3 && i >= 0) + return (&I)[i]; + } + + // create on stack + Mat operator+(const Mat& in) { return Mat(I + in.I, J + in.J, K + in.K); } + + Mat operator-(const Mat& in) { return Mat(I - in.I, J - in.J, K - in.K); } + + Mat operator+(Type val) { return Mat(I + val, J + val, K + val); } + + Mat operator-(Type val) { return Mat(I - val, J - val, K - val); } + + Mat operator*(Type val) { return Mat(I * val, J * val, K * val); } + + Mat operator/(Type val) { return Mat(I / val, J / val, K / val); } + + // write + Mat& operator=(const Mat& in) { + I = in.I; + J = in.J; + K = in.K; + return *this; + } + + Mat& operator+=(const Mat& in) { + I += in.I; + J += in.J; + K += in.K; + return *this; + } + + Mat& operator-=(const Mat& in) { + I -= in.I; + J -= in.J; + K -= in.K; + return *this; + } + + Mat& operator+=(Type val) { + I += val; + J += val; + K += val; + return *this; + } + + Mat& operator-=(Type val) { + I -= val; + J -= val; + K -= val; + return *this; + } + + Mat& operator*=(Type val) { + I *= val; + J *= val; + K *= val; + return *this; + } + + Mat& operator/=(Type val) { + I /= val; + J /= val; + K /= val; + return *this; + } + + // Matrix transformation + vec transform(const vec& in) const { return vec(I.x * in.x + I.y * in.y + I.z * in.z, J.x * in.x + J.y * in.y + J.z * in.z, K.x * in.x + K.y * in.y + K.z * in.z); } + + Mat transform(const Mat& in) { + return Mat( + { (in.I.x * I.x + in.I.y * J.x + in.I.z * K.x), (in.I.x * I.y + in.I.y * J.y + in.I.z * K.y), (in.I.x * I.z + in.I.y * J.z + in.I.z * K.z) }, + { (in.J.x * I.x + in.J.y * J.x + in.J.z * K.x), (in.J.x * I.y + in.J.y * J.y + in.J.z * K.y), (in.J.x * I.z + in.J.y * J.z + in.J.z * K.z) }, + { (in.K.x * I.x + in.K.y * J.x + in.K.z * K.x), (in.K.x * I.y + in.K.y * J.y + in.K.z * K.y), (in.K.x * I.z + in.K.y * J.z + in.K.z * K.z) } + ); + } + + vec operator*(const vec& in) { return transform(in); } + + Mat operator*(const Mat& in) { return transform(in); } + + Mat minor(halni, halni) { + Mat out; + return out; + } + + Mat& transpose() { + swap(I.y, J.x); + swap(I.z, K.x); + swap(J.z, K.y); + return *this; + } + + Type det() { return (+I.x * (J.y * K.z - J.z * K.y) - I.y * (J.x * K.z - J.z * K.x) + I.z * (J.x * K.y - J.y * K.x)); } + + Mat cofactors() { return Mat(vec(+(J.y * K.z - J.z * K.y), -(I.y * K.z - I.z * K.y), +(I.y * J.z - I.z * J.y)), vec(-(J.x * K.z - J.z * K.x), +(I.x * K.z - I.z * K.x), -(I.x * J.z - I.z * J.x)), vec(+(J.x * K.y - J.y * K.x), -(I.x * K.y - I.y * K.x), +(I.x * J.y - I.y * J.x))); } + + Mat inv() { return cofactors() /= det(); } + + Mat rotatorX(alnf angle) { + alnf cosA = (alnf) cos(angle); + alnf sinA = (alnf) sin(angle); + return { { 1, 0, 0 }, { 0, cosA, -sinA }, { 0, sinA, cosA } }; + } + + Mat rotatorY(alnf angle) { + alnf cosA = (alnf) cos(angle); + alnf sinA = (alnf) sin(angle); + return { { cosA, 0, sinA }, { 0, 1, 0 }, { -sinA, 0, cosA } }; + } + + Mat rotatorZ(alnf angle) { + alnf cosA = (alnf) cos(angle); + alnf sinA = (alnf) sin(angle); + return { { cosA, -sinA, 0 }, { sinA, cosA, 0 }, { 0, 0, 1 } }; + } + + static Mat rotatorDir(vec dir, alnf angle) { + dir.normalize(); + + Mat out; + alnf cosA = (alnf) cos(angle); + alnf sinA = (alnf) sin(angle); + alnf tmp = 1 - cosA; + + out.I.x = (Type) (cosA + dir.x * dir.x * tmp); + out.I.y = (Type) (dir.x * dir.y * tmp - dir.z * sinA); + out.I.z = (Type) (dir.x * dir.z * tmp + dir.y * sinA); + + out.J.x = (Type) (dir.y * dir.x * tmp + dir.z * sinA); + out.J.y = (Type) (cosA + dir.y * dir.y * tmp); + out.J.z = (Type) (dir.y * dir.z * tmp - dir.x * sinA); + + out.K.x = (Type) (dir.z * dir.x * tmp - dir.y * sinA); + out.K.y = (Type) (dir.z * dir.y * tmp + dir.x * sinA); + out.K.z = (Type) (cosA + dir.z * dir.z * tmp); + + return out; + } + }; + + template + using Mat4 = Mat; + + using Mat4F = Mat4; + using Mat4I = Mat4; + + template + class Mat { + typedef Vec MVec; + MVec dummy; + + public: + MVec& operator[](alni) { return dummy; } + + const MVec& operator[](alni) const { return dummy; } + + Type det() { return Type(); } + }; +} diff --git a/Math/public/Ray.hpp b/Math/public/Ray.hpp index ae90e61..2d6927a 100644 --- a/Math/public/Ray.hpp +++ b/Math/public/Ray.hpp @@ -1,20 +1,20 @@ -#pragma once - -#include "Vec.hpp" - -namespace tp { - - class Ray { - public: - Ray(const Vec3F& Dir, const Vec3F& Pos); - Ray() = default; - - public: - Vec3F dir; - Vec3F pos; - - public: - ~Ray() = default; - }; - +#pragma once + +#include "Vec.hpp" + +namespace tp { + + class Ray { + public: + Ray(const Vec3F& Dir, const Vec3F& Pos); + Ray() = default; + + public: + Vec3F dir; + Vec3F pos; + + public: + ~Ray() = default; + }; + } \ No newline at end of file diff --git a/Math/public/Rect.hpp b/Math/public/Rect.hpp index f6aba2a..1ad93fc 100644 --- a/Math/public/Rect.hpp +++ b/Math/public/Rect.hpp @@ -1,274 +1,240 @@ - -#pragma once - -#include "Vec.hpp" - -#include "Intersections.hpp" - -namespace tp { - - template class Rect; - using RectF = Rect; - using RectI = Rect; - - template - class Rect { - public: - Rect() {} - - explicit Rect(Type val) { - this->pos = val; - this->size = val; - } - - template - explicit Rect(const Rect& rec) { - this->pos = rec.pos; - this->size = rec.size; - } - - Rect(const Vec2& pos, const Vec2& size) { - this->pos = pos; - this->size = size; - } - - Rect(Type aPosX, Type posy, Type aSizeX, Type aSizeY) { - pos.assign(aPosX, posy); - size.assign(aSizeX, aSizeY); - } - - // assign - template - Rect& assign(InType p1x, InType p1y, InType p2x, InType p2y) { - pos.assign(p1x, p1y); - size.assign(p2x, p2y); - return *this; - } - - // assign - template - Rect& assign(const Vec2& pos, const Vec2& size) { - this->pos.assign(pos.x, pos.y); - this->size.assign(size.x, size.y); - return *this; - } - - // conversion - template - Rect& operator=(const Rect& rect) { - pos = rect.pos; - size = rect.size; - return *this; - } - - bool operator==(Rect& rect) const { - return (pos == rect.pos && size == rect.size); - } - - bool isEnclosedIn(const Rect& rect, bool aParent = false) const { - if (aParent) { - return (pos.x + size.x <= rect.size.x && pos.y + size.y <= rect.size.y && - pos.x >= 0 && pos.y >= 0); - } - *(Vec2*)(&pos) -= rect.pos; - bool ret = this->isEnclosedIn(rect, true); - *(Vec2*)(&pos) += rect.pos; - return ret; - } - - void calcIntersection(Rect& in, Rect& out) const { - if (isOverlap(in)) { - out = *this; - for (char i = 0; i < 2; i++) { - clamp(out.pos[i], in.pos[i], in.pos[i] + in.size[i]); - Type p2 = pos[i] + size[i]; - clamp(p2, in.pos[i], in.pos[i] + in.size[i]); - out.size[i] = p2 - out.pos[i]; - } - } - else { - out.size.assign(0, 0); - out.pos.assign(0, 0); - } - } - - // argument isInside - bool isInside(const Vec2& p) const { - return isInside(p.x, p.y); - } - - bool isInside(Type x, Type y) const { - return (pos.x < x&& pos.y < y&& pos.x + size.x > x&& pos.y + size.y > y); - } - - inline Vec2 sizeVec() const { - return Vec2(size.x, size.y); - } - - inline Vec2 sizeVecW() const { - return Vec2(size.x + pos.x, size.y + pos.y); - } - - void invertY(Type scr_y) { - pos.y = scr_y - pos.y - size.y; - } - - void move(Type dx, Type dy) { - pos.x += dx; - pos.y += dy; - } - - Rect& scaleFromCenter(tp::halnf fac, bool add = false) { - if (add) { - pos += fac; - size -= fac * 2; - } - else { - auto new_size = size * fac; - pos = pos - (new_size - size) / 2; - size = new_size; - } - return *this; - } - - Vec2 p1() { - return pos; - } - - Vec2 p3() { - return pos + size; - } - - Vec2 p2() { - return { pos.x, pos.y + size.y }; - } - - Vec2 p4() { - return { pos.x + size.x, pos.y }; - } - - inline bool isAbove(const Rect& rect) const { - return (pos.y + size.y < rect.pos.y); - } - - inline bool isBellow(const Rect& rect) const { - return (rect.pos.y + rect.size.y < pos.y); - } - - inline bool isRight(const Rect& rect) const { - return (pos.x + size.x < rect.pos.x); - } - - inline bool isLeft(const Rect& rect) const { - return (rect.pos.x + rect.size.x < pos.x); - } - - inline bool isIntersectsY(const Rect& in) const { - if (INRANGE(in.pos.x, pos.x, pos.x + size.x)) return true; - if (INRANGE(pos.x, in.pos.x, in.pos.x + in.size.x)) return true; - return false; - } - - inline bool isIntersectX(const Rect& rect) const { - if (INRANGE(rect.pos.y, pos.y, pos.y + size.y)) return true; - if (INRANGE(pos.y, rect.pos.y, rect.pos.y + rect.size.y)) return true; - return false; - } - - bool isOverlap(const Rect& rect) const { - return (isIntersectX(rect) && isIntersectsY(rect)); - } - - void clamp(const Rect& bounds) { - Vec2 p3(pos + size); - Vec2 max = bounds.pos + bounds.size; - - pos.clamp(bounds.pos, max); - p3.clamp(bounds.pos, max); - - size = p3 - pos; - } - - // if only one point isInside - bool clampOutside(Vec2& v1, Vec2& v2) { - bool const in1 = isInside(v1); - bool const in2 = isInside(v2); - if (!in1 && !in2) return false; - - if (in1) { - if (!intersectLines2D(p2(), p3(), v1, v2, &v1)) { - if (!intersectLines2D(p1(), p4(), v1, v2, &v1)) { - if (!intersectLines2D(p1(), p2(), v1, v2, &v1)) { - intersectLines2D(p3(), p4(), v1, v2, &v1); - } - } - } - return true; - } - - if (!intersectLines2D(p2(), p3(), v1, v2, &v2)) { - if (!intersectLines2D(p1(), p4(), v1, v2, &v2)) { - if (!intersectLines2D(p1(), p2(), v1, v2, &v2)) { - intersectLines2D(p3(), p4(), v1, v2, &v2); - } - } - } - return true; - } - - uhalni clampInside(Vec2& v1, Vec2& v2) { - bool const in1 = isInside(v1); - bool const in2 = isInside(v2); - - if (in1 && in2) return 2; - - Vec2 v1copy = v1; - Vec2 v2copy = v2; - - if (in1 || in2) { - if (!intersectLines2D(p2(), p3(), v1copy, v2copy, &v2)) { - if (!intersectLines2D(p1(), p4(), v1copy, v2copy, &v2)) { - if (!intersectLines2D(p1(), p2(), v1copy, v2copy, &v2)) { - intersectLines2D(p3(), p4(), v1copy, v2copy, &v2); - } - } - } - return 1; - } - - DEBUG_ASSERT(0) - return 0; - } - - template - Rect operator*(ConversionType val) { - Rect out; - out.pos = pos * val; - out.size = size * val; - return out; - } - - Vec2 center() { - return pos + size / 2.f; - } - - public: - union { - Vec2 v1; - Vec2 pos; - struct { - Type x; - Type y; - }; - }; - - union { - Vec2 v2; - Vec2 size; - struct { - Type z; - Type w; - }; - }; - }; + +#pragma once + +#include "Vec.hpp" + +#include "Intersections.hpp" + +namespace tp { + + template + class Rect; + using RectF = Rect; + using RectI = Rect; + + template + class Rect { + public: + Rect() {} + + explicit Rect(Type val) { + this->pos = val; + this->size = val; + } + + template + explicit Rect(const Rect& rec) { + this->pos = rec.pos; + this->size = rec.size; + } + + Rect(const Vec2& pos, const Vec2& size) { + this->pos = pos; + this->size = size; + } + + Rect(Type aPosX, Type posy, Type aSizeX, Type aSizeY) { + pos.assign(aPosX, posy); + size.assign(aSizeX, aSizeY); + } + + // assign + template + Rect& assign(InType p1x, InType p1y, InType p2x, InType p2y) { + pos.assign(p1x, p1y); + size.assign(p2x, p2y); + return *this; + } + + // assign + template + Rect& assign(const Vec2& pos, const Vec2& size) { + this->pos.assign(pos.x, pos.y); + this->size.assign(size.x, size.y); + return *this; + } + + // conversion + template + Rect& operator=(const Rect& rect) { + pos = rect.pos; + size = rect.size; + return *this; + } + + bool operator==(Rect& rect) const { return (pos == rect.pos && size == rect.size); } + + bool isEnclosedIn(const Rect& rect, bool aParent = false) const { + if (aParent) { + return (pos.x + size.x <= rect.size.x && pos.y + size.y <= rect.size.y && pos.x >= 0 && pos.y >= 0); + } + *(Vec2*) (&pos) -= rect.pos; + bool ret = this->isEnclosedIn(rect, true); + *(Vec2*) (&pos) += rect.pos; + return ret; + } + + void calcIntersection(Rect& in, Rect& out) const { + if (isOverlap(in)) { + out = *this; + for (char i = 0; i < 2; i++) { + clamp(out.pos[i], in.pos[i], in.pos[i] + in.size[i]); + Type p2 = pos[i] + size[i]; + clamp(p2, in.pos[i], in.pos[i] + in.size[i]); + out.size[i] = p2 - out.pos[i]; + } + } else { + out.size.assign(0, 0); + out.pos.assign(0, 0); + } + } + + // argument isInside + bool isInside(const Vec2& p) const { return isInside(p.x, p.y); } + + bool isInside(Type x, Type y) const { return (pos.x < x && pos.y < y && pos.x + size.x > x && pos.y + size.y > y); } + + inline Vec2 sizeVec() const { return Vec2(size.x, size.y); } + + inline Vec2 sizeVecW() const { return Vec2(size.x + pos.x, size.y + pos.y); } + + void invertY(Type scr_y) { pos.y = scr_y - pos.y - size.y; } + + void move(Type dx, Type dy) { + pos.x += dx; + pos.y += dy; + } + + Rect& scaleFromCenter(tp::halnf fac, bool add = false) { + if (add) { + pos += fac; + size -= fac * 2; + } else { + auto new_size = size * fac; + pos = pos - (new_size - size) / 2; + size = new_size; + } + return *this; + } + + Vec2 p1() { return pos; } + + Vec2 p3() { return pos + size; } + + Vec2 p2() { return { pos.x, pos.y + size.y }; } + + Vec2 p4() { return { pos.x + size.x, pos.y }; } + + inline bool isAbove(const Rect& rect) const { return (pos.y + size.y < rect.pos.y); } + + inline bool isBellow(const Rect& rect) const { return (rect.pos.y + rect.size.y < pos.y); } + + inline bool isRight(const Rect& rect) const { return (pos.x + size.x < rect.pos.x); } + + inline bool isLeft(const Rect& rect) const { return (rect.pos.x + rect.size.x < pos.x); } + + inline bool isIntersectsY(const Rect& in) const { + if (INRANGE(in.pos.x, pos.x, pos.x + size.x)) return true; + if (INRANGE(pos.x, in.pos.x, in.pos.x + in.size.x)) return true; + return false; + } + + inline bool isIntersectX(const Rect& rect) const { + if (INRANGE(rect.pos.y, pos.y, pos.y + size.y)) return true; + if (INRANGE(pos.y, rect.pos.y, rect.pos.y + rect.size.y)) return true; + return false; + } + + bool isOverlap(const Rect& rect) const { return (isIntersectX(rect) && isIntersectsY(rect)); } + + void clamp(const Rect& bounds) { + Vec2 p3(pos + size); + Vec2 max = bounds.pos + bounds.size; + + pos.clamp(bounds.pos, max); + p3.clamp(bounds.pos, max); + + size = p3 - pos; + } + + // if only one point isInside + bool clampOutside(Vec2& v1, Vec2& v2) { + bool const in1 = isInside(v1); + bool const in2 = isInside(v2); + if (!in1 && !in2) return false; + + if (in1) { + if (!intersectLines2D(p2(), p3(), v1, v2, &v1)) { + if (!intersectLines2D(p1(), p4(), v1, v2, &v1)) { + if (!intersectLines2D(p1(), p2(), v1, v2, &v1)) { + intersectLines2D(p3(), p4(), v1, v2, &v1); + } + } + } + return true; + } + + if (!intersectLines2D(p2(), p3(), v1, v2, &v2)) { + if (!intersectLines2D(p1(), p4(), v1, v2, &v2)) { + if (!intersectLines2D(p1(), p2(), v1, v2, &v2)) { + intersectLines2D(p3(), p4(), v1, v2, &v2); + } + } + } + return true; + } + + uhalni clampInside(Vec2& v1, Vec2& v2) { + bool const in1 = isInside(v1); + bool const in2 = isInside(v2); + + if (in1 && in2) return 2; + + Vec2 v1copy = v1; + Vec2 v2copy = v2; + + if (in1 || in2) { + if (!intersectLines2D(p2(), p3(), v1copy, v2copy, &v2)) { + if (!intersectLines2D(p1(), p4(), v1copy, v2copy, &v2)) { + if (!intersectLines2D(p1(), p2(), v1copy, v2copy, &v2)) { + intersectLines2D(p3(), p4(), v1copy, v2copy, &v2); + } + } + } + return 1; + } + + DEBUG_ASSERT(0) + return 0; + } + + template + Rect operator*(ConversionType val) { + Rect out; + out.pos = pos * val; + out.size = size * val; + return out; + } + + Vec2 center() { return pos + size / 2.f; } + + public: + union { + Vec2 v1; + Vec2 pos; + struct { + Type x; + Type y; + }; + }; + + union { + Vec2 v2; + Vec2 size; + struct { + Type z; + Type w; + }; + }; + }; } \ No newline at end of file diff --git a/Math/public/Topology.hpp b/Math/public/Topology.hpp index 2bc2ce2..f29fb36 100644 --- a/Math/public/Topology.hpp +++ b/Math/public/Topology.hpp @@ -1,53 +1,49 @@ -#pragma once - -#include "Buffer.hpp" -#include "Camera.hpp" - -namespace tp { - - class TrigCache { - static Vec3F gHitPos; - - public: - ualni mP1, mP2, mP3; - Vec3F mEdgeP1P2, mEdgeP1P3; - Vec3F mNormal; - Vec3F mOrigin; - - public: - TrigCache(); - TrigCache(const TrigCache& in); - TrigCache(ualni v1, ualni v2, ualni v3); - - public: - static const Vec3F& getHitPos(); - [[nodiscard]] const Vec3F& getNormal() const; - - public: - void updateCache(const Buffer& points); - [[nodiscard]] bool castRay(const Ray& ray) const; - }; - - struct Topology { - Vec3F Origin = {0, 0, 0}; - mat3f Basis = { - {1, 0, 0}, - {0, 1, 0}, - {0, 0, 1} - }; - - Buffer Points; - Buffer Normals; - Buffer Indexes; - }; - - struct TopologyCache { - const Topology* Source = nullptr; - - Buffer TransformedPoints; - Buffer TransformedNormals; - Buffer TrigCaches; - - void updateCache(); - }; -} +#pragma once + +#include "Buffer.hpp" +#include "Camera.hpp" + +namespace tp { + + class TrigCache { + static Vec3F gHitPos; + + public: + ualni mP1, mP2, mP3; + Vec3F mEdgeP1P2, mEdgeP1P3; + Vec3F mNormal; + Vec3F mOrigin; + + public: + TrigCache(); + TrigCache(const TrigCache& in); + TrigCache(ualni v1, ualni v2, ualni v3); + + public: + static const Vec3F& getHitPos(); + [[nodiscard]] const Vec3F& getNormal() const; + + public: + void updateCache(const Buffer& points); + [[nodiscard]] bool castRay(const Ray& ray) const; + }; + + struct Topology { + Vec3F Origin = { 0, 0, 0 }; + mat3f Basis = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; + + Buffer Points; + Buffer Normals; + Buffer Indexes; + }; + + struct TopologyCache { + const Topology* Source = nullptr; + + Buffer TransformedPoints; + Buffer TransformedNormals; + Buffer TrigCaches; + + void updateCache(); + }; +} diff --git a/Math/public/Trig.hpp b/Math/public/Trig.hpp index 956e234..5ab78d5 100644 --- a/Math/public/Trig.hpp +++ b/Math/public/Trig.hpp @@ -1,25 +1,25 @@ -#pragma once - -#include "Vec.hpp" - -namespace tp { - - class Trig { - public: - Trig(); - Trig(const Vec3F& v0, const Vec3F& v1, const Vec3F& v2); - - public: - Vec3F p1; - Vec3F p2; - Vec3F p3; - - public: - void assign(const Vec3F& v0, const Vec3F& v1, const Vec3F& v2); - void normal(Vec3F& dir) const; - bool rayHit(class Ray& ray, Vec3F& HitPos) const; - - public: - ~Trig(); - }; +#pragma once + +#include "Vec.hpp" + +namespace tp { + + class Trig { + public: + Trig(); + Trig(const Vec3F& v0, const Vec3F& v1, const Vec3F& v2); + + public: + Vec3F p1; + Vec3F p2; + Vec3F p3; + + public: + void assign(const Vec3F& v0, const Vec3F& v1, const Vec3F& v2); + void normal(Vec3F& dir) const; + bool rayHit(class Ray& ray, Vec3F& HitPos) const; + + public: + ~Trig(); + }; } \ No newline at end of file diff --git a/Math/public/Vec.hpp b/Math/public/Vec.hpp index 3f5b1d4..a904869 100644 --- a/Math/public/Vec.hpp +++ b/Math/public/Vec.hpp @@ -1,649 +1,576 @@ -#pragma once - -#include "MathCommon.hpp" - -namespace tp { - - template - class Vec { - typedef SelectValueOrReference TypeArg; - - private: - Type mBuff[tSize]; - - inline const Type& get(ualni i) const { return mBuff[i]; } - inline Type& get(ualni i) { return mBuff[i]; } - inline Type& set(ualni i, TypeArg arg) { return mBuff[i] = arg; } - - public: - - Vec() { - MODULE_SANITY_CHECK(gModuleMath) - } - - explicit Vec(TypeArg val) { - assign(val); - } - - Vec(TypeArg val1, TypeArg val2, TypeArg val3, TypeArg val4) { - static_assert(tSize == 4); - mBuff[0] = val1; - mBuff[1] = val2; - mBuff[2] = val3; - mBuff[3] = val4; - } - - Vec(TypeArg val1, TypeArg val2, TypeArg val3, TypeArg val4, TypeArg val5) { - static_assert(tSize == 5); - mBuff[0] = val1; - mBuff[1] = val2; - mBuff[2] = val3; - mBuff[3] = val4; - mBuff[4] = val5; - } - - Vec(TypeArg val1, TypeArg val2, TypeArg val3, TypeArg val4, TypeArg val5, TypeArg val6) { - static_assert(tSize == 6); - mBuff[0] = val1; - mBuff[1] = val2; - mBuff[2] = val3; - mBuff[3] = val4; - mBuff[4] = val5; - mBuff[5] = val6; - } - - Vec(const Vec& in) { - memCopy(mBuff, in.mBuff, sizeof(Type) * tSize); - } - - Type& operator[](ualni i) { - DEBUG_ASSERT(i < tSize && i >= 0) - return mBuff[i]; - } - - const Type& operator[](ualni i) const { - DEBUG_ASSERT(i < tSize && i >= 0) - return mBuff[i]; - } - - Vec operator-() { - Vec out; - for (halni i = 0; i < tSize; i++) { - out.get(i) = -get(i); - } - return out; - } - - // write - Vec& operator+=(const Vec& val) { - for (ualni i = 0; i < tSize; i++) { - get(i) += val[i]; - } - return *this; - } - - Vec& operator-=(const Vec& val) { - for (ualni i = 0; i < tSize; i++) { - get(i) -= val[i]; - } - return *this; - } - - Vec& operator+=(Type val) { - for (ualni i = 0; i < tSize; i++) { - get(i) += val; - } - return *this; - } - - Vec& operator-=(Type val) { - for (ualni i = 0; i < tSize; i++) { - get(i) -= val; - } - return *this; - } - - Vec& operator*=(Type val) { - for (ualni i = 0; i < tSize; i++) { - get(i) *= val; - } - return *this; - } - - Vec& operator/=(Type val) { - for (ualni i = 0; i < tSize; i++) { - get(i) /= val; - } - return *this; - } - - void assign(Type val) { - for (ualni i = 0; i < tSize; i++) { - get(i) = val; - } - } - - // create on stack - Vec operator+(const Vec& in) const { - Vec out; - for (ualni i = 0; i < tSize; i++) { - out[i] = in[i] + get(i); - } - return out; - } - - Vec operator-(const Vec& in) const { - Vec out; - for (ualni i = 0; i < tSize; i++) { - out[i] = in[i] - get(i); - } - return out; - } - - Vec operator+(Type val) const { - Vec out; - for (ualni i = 0; i < tSize; i++) { - out[i] = get(i) + val; - } - return out; - } - - Vec operator-(Type val) const { - Vec out; - for (ualni i = 0; i < tSize; i++) { - out[i] = get(i) - val; - } - return out; - } - - Vec operator*(Type val) const { - Vec out; - for (ualni i = 0; i < tSize; i++) { - out[i] = get(i) * val; - } - return out; - } - - Vec operator/(Type val) const { - Vec out; - for (ualni i = 0; i < tSize; i++) { - out[i] = get(i) / val; - } - return out; - } - - // Vector Properties - Type dot(const Vec& in) const { - Type out = 0; - for (ualni i = 0; i < tSize; i++) { - out += get(i) * in.get(i); - } - return out; - } - - Type operator*(const Vec& in) const { - return dot(in); - } - - [[nodiscard]] alnf length2() const { - alnf sum = 0; - for (ualni i = 0; i < tSize; i++) { - Type val = get(i); - sum += val * val; - } - return sum; - } - - [[nodiscard]] alnf length() const { - return sqrt(length2()); - } - - Vec& normalize() { - operator/=((Type) length()); - return *this; - } - - Vec unitV() { - return Vec(*this).normalize(); - } - - // Comparisons - bool operator>(const Vec& in) const { return this->length2() > in.length2(); } - bool operator<(const Vec& in) const { return this->length2() < in.length2(); } - bool operator>=(const Vec& in) const { return this->length2() >= in.length2(); } - bool operator<=(const Vec& in) const { return this->length2() <= in.length2(); } - - bool operator==(const Vec& in) const { - for (ualni i = 0; i < tSize; i++) { - if (get(i) != in.get(i)) { - return false; - } - } - return true; - } - - bool operator!=(const Vec& in) const { - return !operator==(in); - } - }; - - template - using Vec2 = Vec; - - using Vec2F = Vec; - using Vec2I = Vec; - - template - class Vec { - - public: - Type x; - Type y; - - Vec() : x(0), y(0) {} - - // Initialization - template - Vec(TypeIn aX, TypeIn aY) { - x = (Type) aX; - y = (Type) aY; - } - - template - explicit Vec(TypeIn Vec[2]) { - x = (Type) Vec[0]; - y = (Type) Vec[1]; - } - - template - explicit Vec(TypeIn val) { - x = y = (Type) val; - } - - template - explicit Vec(Vec& Vec) { - x = (Type) Vec.x; - y = (Type) Vec.y; - } - - template - void assign(TypeIn aX, TypeIn aY) { - x = (Type) aX; - y = (Type) aY; - } - - template - void assign(const Vec& in) { - x = (Type) in.x; - y = (Type) in.y; - } - - template - void assign(TypeIn in[2]) { - x = (Type) in[0]; - y = (Type) in[1]; - } - - template - Vec& operator=(TypeIn val) { - x = y = (Type) val; - return *this; - } - - // Conversion - template - Vec& operator=(const Vec& in) { - x = (Type) in.x; - y = (Type) in.y; - return *this; - } - - // create on stack - Vec2 operator+(const Vec2& in) const { return Vec2(x + in.x, y + in.y); } - Vec2 operator-(const Vec2& in) const { return Vec2(x - in.x, y - in.y); } - Vec2 operator+(Type val) const { return Vec2(x + val, y + val); } - Vec2 operator-(Type val) const { return Vec2(x - val, y - val); } - Vec2 operator*(Type val) const { return Vec2(x * val, y * val); } - Vec2 operator/(Type val) const { return Vec2(x / val, y / val); } - - // write - void operator-=(Type val) { - x -= val; - y -= val; - } - - void operator+=(Type val) { - x += val; - y += val; - } - - void operator-=(const Vec2& Vec) { - x -= Vec.x; - y -= Vec.y; - } - - void operator+=(const Vec2& Vec) { - x += Vec.x; - y += Vec.y; - } - - void operator*=(Type val) { - x *= val; - y *= val; - } - - void operator/=(Type val) { - x /= val; - y /= val; - } - - void operator/=(const Vec2& in) { - x /= in.x; - y /= in.y; - } - - void operator*=(const Vec2& in) { - x *= in.x; - y *= in.y; - } - - bool compareEach(const Vec& in) const { return (x > in.x && y > in.y); } - - bool operator>(const Vec& in) const { return length2() > in.length2(); } - bool operator<(const Vec& in) const { return length2() < in.length2(); } - bool operator>=(const Vec& in) const { return length2() >= in.length2(); } - bool operator<=(const Vec& in) const { return length2() <= in.length2(); } - bool operator==(const Vec& in) const { return (x == in.x && y == in.y); } - bool operator!=(const Vec& in) const { return (x != in.x || y != in.y); } - - Type& operator[](bool axes) { return (&x)[axes]; } - - const Type& operator[](bool axes) const { return (&x)[axes]; } - - // Vector Properties - alnf operator*(const Vec& in) const { - return dot(in); - } - - alnf dot(const Vec& in) const { - return (x * in.x + y * in.y); - } - - Vec unitV() const { - return Vec(*this / (Type) this->length()); - } - - void normalize() { - *this /= (Type) length(); - } - - Vec normal() { - return { -y, x }; - } - - [[nodiscard]] alnf length2() const { - return (x * x + y * y); - } - - [[nodiscard]] alnf length() const { - Type const tmp = (Type) (x * x + y * y); - return sqrt(tmp); - } - - // Vector Transformation - void Rot(float cosA, float sinA) { - Type tmp = x; - x = x * cosA - y * sinA; - y = tmp * sinA + y * cosA; - } - - void clamp(const Vec& min, const Vec& max) { - tp::clamp(x, min.x, max.x); - tp::clamp(y, min.y, max.y); - } - }; - - template - using Vec3 = Vec; - - using Vec3F = Vec3; - using Vec3I = Vec3; - - template - class Vec { - - public: - - Type x; - Type y; - Type z; - - // Initialization - Vec() = default; - - explicit Vec(const Vec& in) { - x = in[0]; - y = in[1]; - z = in[2]; - } - - Vec(Type aX, Type aY, Type aZ) { - x = aX; - y = aY; - z = aZ; - } - - explicit Vec(Type Vec[3]) { - x = Vec[0]; - y = Vec[1]; - z = Vec[2]; - } - - explicit Vec(Type x) { - assign(x); - } - - Vec(const Vec& Vec) { - x = Vec.x; - y = Vec.y; - z = Vec.z; - } - - void assign(Type aX, Type aY, Type aZ) { - x = aX; - y = aY; - z = aZ; - } - - void assign(const Vec& in) { - x = in.x; - y = in.y; - z = in.z; - } - - void assign(Type val) { - x = val; - y = val; - z = val; - } - - Vec& operator=(const Vec& in) { - x = in.x; - y = in.y; - z = in.z; - return *this; - } - - Vec& operator=(const Type* in) { - x = in[0]; - y = in[1]; - z = in[2]; - return *this; - } - - Type& operator[](alni i) { - DEBUG_ASSERT(i < 3 && i >= 0) - return (&x)[i]; - } - - const Type& operator[](alni i) const { - DEBUG_ASSERT(i < 3 && i >= 0) - return (&x)[i]; - } - - // create on stack - Vec operator+(const Vec& in) const { - return Vec(x + in.x, y + in.y, z + in.z); - } - - Vec operator-(const Vec& in) const { - return Vec(x - in.x, y - in.y, z - in.z); - } - - Vec operator+(Type val) const { - return Vec(x + val, y + val, z + val); - } - - Vec operator-(Type val) const { - return Vec(x - val, y - val, z - val); - } - - Vec operator*(Type val) const { - return Vec(x * val, y * val, z * val); - } - - Vec operator/(Type val) const { - return Vec(x / val, y / val, z / val); - } - - - // compare - bool operator>(const Vec& Vec) const { - return length2() > Vec.length2(); - } - - bool operator<(const Vec& Vec) const { - return length2() < Vec.length2(); - } - - bool operator>=(const Vec& Vec) const { - return length2() >= Vec.length2(); - } - - bool operator<=(const Vec& Vec) const { - return length2() <= Vec.length2(); - } - - bool operator==(const Vec& Vec) const { - return (x == Vec.x && y == Vec.y && z == Vec.z); - } - - // write - Vec operator-() { - return Vec(-x, -y, -z); - } - - void operator -= (Type val) { - x -= val; - y -= val; - z -= val; - } - - void operator += (Type val) { - x += val; - y += val; - z += val; - } - - void operator -= (const Vec& in) { - x -= in.x; - y -= in.y; - z -= in.z; - } - - void operator += (const Vec& in) { - x += in.x; - y += in.y; - z += in.z; - } - - void operator *= (Type val) { - x *= val; - y *= val; - z *= val; - } - - void operator /= (Type val) { - x /= val; - y /= val; - z /= val; - } - - // Vector Properties - Type dot(const Vec& in) const { - return (x * in.x + y * in.y + z * in.z); - } - - [[nodiscard]] alnf length() const { - return sqrt((halnf) (x * x + y * y + z * z)); - } - - Type length2() const { - return (x * x + y * y + z * z); - } - - Vec unitV() const { - return *this / (Type) this->length(); - } - - Vec& normalize() { - *this /= (Type) this->length(); - return *this; - } - - Vec cross(const Vec& in) const { - return Vec( - y * in.z - z * in.y, - z * in.x - x * in.z, - x * in.y - y * in.x - ); - } - - Vec operator*(const Vec& in) const { - return cross(in); - } - - // Vector Transformation - void rotZ(alnf cosA, alnf sinA) { - Type tmp = x; - x = (Type) (x * cosA - y * sinA); - y = (Type) (tmp * sinA + y * cosA); - } - - void rotY(float cosA, float sinA) { - Type tmp = x; - x = (Type) (x * cosA - z * sinA); - z = (Type) (tmp * sinA + z * cosA); - } - - void rotX(float cosA, float sinA) { - Type tmp = y; - y = (Type) (y * cosA - z * sinA); - z = (Type) (tmp * sinA + z * cosA); - } - - [[nodiscard]] halnf angelX() const { - return (halnf) atan2(y, z); - } - - [[nodiscard]] halnf angelY() const { - return (halnf) atan2(x, z); - } - }; - - template - using Vec4 = Vec; - - using Vec4F = Vec4; - using Vec4I = Vec4; +#pragma once + +#include "MathCommon.hpp" + +namespace tp { + + template + class Vec { + typedef SelectValueOrReference TypeArg; + + private: + Type mBuff[tSize]; + + inline const Type& get(ualni i) const { return mBuff[i]; } + inline Type& get(ualni i) { return mBuff[i]; } + inline Type& set(ualni i, TypeArg arg) { return mBuff[i] = arg; } + + public: + Vec() { MODULE_SANITY_CHECK(gModuleMath) } + + explicit Vec(TypeArg val) { assign(val); } + + Vec(TypeArg val1, TypeArg val2, TypeArg val3, TypeArg val4) { + static_assert(tSize == 4); + mBuff[0] = val1; + mBuff[1] = val2; + mBuff[2] = val3; + mBuff[3] = val4; + } + + Vec(TypeArg val1, TypeArg val2, TypeArg val3, TypeArg val4, TypeArg val5) { + static_assert(tSize == 5); + mBuff[0] = val1; + mBuff[1] = val2; + mBuff[2] = val3; + mBuff[3] = val4; + mBuff[4] = val5; + } + + Vec(TypeArg val1, TypeArg val2, TypeArg val3, TypeArg val4, TypeArg val5, TypeArg val6) { + static_assert(tSize == 6); + mBuff[0] = val1; + mBuff[1] = val2; + mBuff[2] = val3; + mBuff[3] = val4; + mBuff[4] = val5; + mBuff[5] = val6; + } + + Vec(const Vec& in) { memCopy(mBuff, in.mBuff, sizeof(Type) * tSize); } + + Type& operator[](ualni i) { + DEBUG_ASSERT(i < tSize && i >= 0) + return mBuff[i]; + } + + const Type& operator[](ualni i) const { + DEBUG_ASSERT(i < tSize && i >= 0) + return mBuff[i]; + } + + Vec operator-() { + Vec out; + for (halni i = 0; i < tSize; i++) { + out.get(i) = -get(i); + } + return out; + } + + // write + Vec& operator+=(const Vec& val) { + for (ualni i = 0; i < tSize; i++) { + get(i) += val[i]; + } + return *this; + } + + Vec& operator-=(const Vec& val) { + for (ualni i = 0; i < tSize; i++) { + get(i) -= val[i]; + } + return *this; + } + + Vec& operator+=(Type val) { + for (ualni i = 0; i < tSize; i++) { + get(i) += val; + } + return *this; + } + + Vec& operator-=(Type val) { + for (ualni i = 0; i < tSize; i++) { + get(i) -= val; + } + return *this; + } + + Vec& operator*=(Type val) { + for (ualni i = 0; i < tSize; i++) { + get(i) *= val; + } + return *this; + } + + Vec& operator/=(Type val) { + for (ualni i = 0; i < tSize; i++) { + get(i) /= val; + } + return *this; + } + + void assign(Type val) { + for (ualni i = 0; i < tSize; i++) { + get(i) = val; + } + } + + // create on stack + Vec operator+(const Vec& in) const { + Vec out; + for (ualni i = 0; i < tSize; i++) { + out[i] = in[i] + get(i); + } + return out; + } + + Vec operator-(const Vec& in) const { + Vec out; + for (ualni i = 0; i < tSize; i++) { + out[i] = in[i] - get(i); + } + return out; + } + + Vec operator+(Type val) const { + Vec out; + for (ualni i = 0; i < tSize; i++) { + out[i] = get(i) + val; + } + return out; + } + + Vec operator-(Type val) const { + Vec out; + for (ualni i = 0; i < tSize; i++) { + out[i] = get(i) - val; + } + return out; + } + + Vec operator*(Type val) const { + Vec out; + for (ualni i = 0; i < tSize; i++) { + out[i] = get(i) * val; + } + return out; + } + + Vec operator/(Type val) const { + Vec out; + for (ualni i = 0; i < tSize; i++) { + out[i] = get(i) / val; + } + return out; + } + + // Vector Properties + Type dot(const Vec& in) const { + Type out = 0; + for (ualni i = 0; i < tSize; i++) { + out += get(i) * in.get(i); + } + return out; + } + + Type operator*(const Vec& in) const { return dot(in); } + + [[nodiscard]] alnf length2() const { + alnf sum = 0; + for (ualni i = 0; i < tSize; i++) { + Type val = get(i); + sum += val * val; + } + return sum; + } + + [[nodiscard]] alnf length() const { return sqrt(length2()); } + + Vec& normalize() { + operator/=((Type) length()); + return *this; + } + + Vec unitV() { return Vec(*this).normalize(); } + + // Comparisons + bool operator>(const Vec& in) const { return this->length2() > in.length2(); } + bool operator<(const Vec& in) const { return this->length2() < in.length2(); } + bool operator>=(const Vec& in) const { return this->length2() >= in.length2(); } + bool operator<=(const Vec& in) const { return this->length2() <= in.length2(); } + + bool operator==(const Vec& in) const { + for (ualni i = 0; i < tSize; i++) { + if (get(i) != in.get(i)) { + return false; + } + } + return true; + } + + bool operator!=(const Vec& in) const { return !operator==(in); } + }; + + template + using Vec2 = Vec; + + using Vec2F = Vec; + using Vec2I = Vec; + + template + class Vec { + + public: + Type x; + Type y; + + Vec() : + x(0), + y(0) {} + + // Initialization + template + Vec(TypeIn aX, TypeIn aY) { + x = (Type) aX; + y = (Type) aY; + } + + template + explicit Vec(TypeIn Vec[2]) { + x = (Type) Vec[0]; + y = (Type) Vec[1]; + } + + template + explicit Vec(TypeIn val) { + x = y = (Type) val; + } + + template + explicit Vec(Vec& Vec) { + x = (Type) Vec.x; + y = (Type) Vec.y; + } + + template + void assign(TypeIn aX, TypeIn aY) { + x = (Type) aX; + y = (Type) aY; + } + + template + void assign(const Vec& in) { + x = (Type) in.x; + y = (Type) in.y; + } + + template + void assign(TypeIn in[2]) { + x = (Type) in[0]; + y = (Type) in[1]; + } + + template + Vec& operator=(TypeIn val) { + x = y = (Type) val; + return *this; + } + + // Conversion + template + Vec& operator=(const Vec& in) { + x = (Type) in.x; + y = (Type) in.y; + return *this; + } + + // create on stack + Vec2 operator+(const Vec2& in) const { return Vec2(x + in.x, y + in.y); } + Vec2 operator-(const Vec2& in) const { return Vec2(x - in.x, y - in.y); } + Vec2 operator+(Type val) const { return Vec2(x + val, y + val); } + Vec2 operator-(Type val) const { return Vec2(x - val, y - val); } + Vec2 operator*(Type val) const { return Vec2(x * val, y * val); } + Vec2 operator/(Type val) const { return Vec2(x / val, y / val); } + + // write + void operator-=(Type val) { + x -= val; + y -= val; + } + + void operator+=(Type val) { + x += val; + y += val; + } + + void operator-=(const Vec2& Vec) { + x -= Vec.x; + y -= Vec.y; + } + + void operator+=(const Vec2& Vec) { + x += Vec.x; + y += Vec.y; + } + + void operator*=(Type val) { + x *= val; + y *= val; + } + + void operator/=(Type val) { + x /= val; + y /= val; + } + + void operator/=(const Vec2& in) { + x /= in.x; + y /= in.y; + } + + void operator*=(const Vec2& in) { + x *= in.x; + y *= in.y; + } + + bool compareEach(const Vec& in) const { return (x > in.x && y > in.y); } + + bool operator>(const Vec& in) const { return length2() > in.length2(); } + bool operator<(const Vec& in) const { return length2() < in.length2(); } + bool operator>=(const Vec& in) const { return length2() >= in.length2(); } + bool operator<=(const Vec& in) const { return length2() <= in.length2(); } + bool operator==(const Vec& in) const { return (x == in.x && y == in.y); } + bool operator!=(const Vec& in) const { return (x != in.x || y != in.y); } + + Type& operator[](bool axes) { return (&x)[axes]; } + + const Type& operator[](bool axes) const { return (&x)[axes]; } + + // Vector Properties + alnf operator*(const Vec& in) const { return dot(in); } + + alnf dot(const Vec& in) const { return (x * in.x + y * in.y); } + + Vec unitV() const { return Vec(*this / (Type) this->length()); } + + void normalize() { *this /= (Type) length(); } + + Vec normal() { return { -y, x }; } + + [[nodiscard]] alnf length2() const { return (x * x + y * y); } + + [[nodiscard]] alnf length() const { + Type const tmp = (Type) (x * x + y * y); + return sqrt(tmp); + } + + // Vector Transformation + void Rot(float cosA, float sinA) { + Type tmp = x; + x = x * cosA - y * sinA; + y = tmp * sinA + y * cosA; + } + + void clamp(const Vec& min, const Vec& max) { + tp::clamp(x, min.x, max.x); + tp::clamp(y, min.y, max.y); + } + }; + + template + using Vec3 = Vec; + + using Vec3F = Vec3; + using Vec3I = Vec3; + + template + class Vec { + + public: + Type x; + Type y; + Type z; + + // Initialization + Vec() = default; + + explicit Vec(const Vec& in) { + x = in[0]; + y = in[1]; + z = in[2]; + } + + Vec(Type aX, Type aY, Type aZ) { + x = aX; + y = aY; + z = aZ; + } + + explicit Vec(Type Vec[3]) { + x = Vec[0]; + y = Vec[1]; + z = Vec[2]; + } + + explicit Vec(Type x) { assign(x); } + + Vec(const Vec& Vec) { + x = Vec.x; + y = Vec.y; + z = Vec.z; + } + + void assign(Type aX, Type aY, Type aZ) { + x = aX; + y = aY; + z = aZ; + } + + void assign(const Vec& in) { + x = in.x; + y = in.y; + z = in.z; + } + + void assign(Type val) { + x = val; + y = val; + z = val; + } + + Vec& operator=(const Vec& in) { + x = in.x; + y = in.y; + z = in.z; + return *this; + } + + Vec& operator=(const Type* in) { + x = in[0]; + y = in[1]; + z = in[2]; + return *this; + } + + Type& operator[](alni i) { + DEBUG_ASSERT(i < 3 && i >= 0) + return (&x)[i]; + } + + const Type& operator[](alni i) const { + DEBUG_ASSERT(i < 3 && i >= 0) + return (&x)[i]; + } + + // create on stack + Vec operator+(const Vec& in) const { return Vec(x + in.x, y + in.y, z + in.z); } + + Vec operator-(const Vec& in) const { return Vec(x - in.x, y - in.y, z - in.z); } + + Vec operator+(Type val) const { return Vec(x + val, y + val, z + val); } + + Vec operator-(Type val) const { return Vec(x - val, y - val, z - val); } + + Vec operator*(Type val) const { return Vec(x * val, y * val, z * val); } + + Vec operator/(Type val) const { return Vec(x / val, y / val, z / val); } + + // compare + bool operator>(const Vec& Vec) const { return length2() > Vec.length2(); } + + bool operator<(const Vec& Vec) const { return length2() < Vec.length2(); } + + bool operator>=(const Vec& Vec) const { return length2() >= Vec.length2(); } + + bool operator<=(const Vec& Vec) const { return length2() <= Vec.length2(); } + + bool operator==(const Vec& Vec) const { return (x == Vec.x && y == Vec.y && z == Vec.z); } + + // write + Vec operator-() { return Vec(-x, -y, -z); } + + void operator-=(Type val) { + x -= val; + y -= val; + z -= val; + } + + void operator+=(Type val) { + x += val; + y += val; + z += val; + } + + void operator-=(const Vec& in) { + x -= in.x; + y -= in.y; + z -= in.z; + } + + void operator+=(const Vec& in) { + x += in.x; + y += in.y; + z += in.z; + } + + void operator*=(Type val) { + x *= val; + y *= val; + z *= val; + } + + void operator/=(Type val) { + x /= val; + y /= val; + z /= val; + } + + // Vector Properties + Type dot(const Vec& in) const { return (x * in.x + y * in.y + z * in.z); } + + [[nodiscard]] alnf length() const { return sqrt((halnf) (x * x + y * y + z * z)); } + + Type length2() const { return (x * x + y * y + z * z); } + + Vec unitV() const { return *this / (Type) this->length(); } + + Vec& normalize() { + *this /= (Type) this->length(); + return *this; + } + + Vec cross(const Vec& in) const { return Vec(y * in.z - z * in.y, z * in.x - x * in.z, x * in.y - y * in.x); } + + Vec operator*(const Vec& in) const { return cross(in); } + + // Vector Transformation + void rotZ(alnf cosA, alnf sinA) { + Type tmp = x; + x = (Type) (x * cosA - y * sinA); + y = (Type) (tmp * sinA + y * cosA); + } + + void rotY(float cosA, float sinA) { + Type tmp = x; + x = (Type) (x * cosA - z * sinA); + z = (Type) (tmp * sinA + z * cosA); + } + + void rotX(float cosA, float sinA) { + Type tmp = y; + y = (Type) (y * cosA - z * sinA); + z = (Type) (tmp * sinA + z * cosA); + } + + [[nodiscard]] halnf angelX() const { return (halnf) atan2(y, z); } + + [[nodiscard]] halnf angelY() const { return (halnf) atan2(x, z); } + }; + + template + using Vec4 = Vec; + + using Vec4F = Vec4; + using Vec4I = Vec4; } \ No newline at end of file diff --git a/Math/tests/TestCommon.cpp b/Math/tests/TestCommon.cpp index 2b33b4f..ba0946d 100644 --- a/Math/tests/TestCommon.cpp +++ b/Math/tests/TestCommon.cpp @@ -5,37 +5,37 @@ using namespace tp; TEST_DEF(ComplexNumber) { - TEST((ComplexCart {3, 4}.mod() == 5)); - TEST((ComplexCart {1, 1}.arg() == 0.7853981633974483)); - TEST((ComplexCart {3, 4}.norm2() == 25)); + TEST((ComplexCart{ 3, 4 }.mod() == 5)); + TEST((ComplexCart{ 1, 1 }.arg() == 0.7853981633974483)); + TEST((ComplexCart{ 3, 4 }.norm2() == 25)); - { - ComplexCart cn {3, 4}; - ComplexCart expected {0.12, -0.16}; - auto val = cn.reciprocal(); - TEST((val == expected)); - } + { + ComplexCart cn{ 3, 4 }; + ComplexCart expected{ 0.12, -0.16 }; + auto val = cn.reciprocal(); + TEST((val == expected)); + } - { - ComplexCart cn {3, 4}; - ComplexCart expected {3, -4}; - TEST((cn.conjugate() == expected)); - } + { + ComplexCart cn{ 3, 4 }; + ComplexCart expected{ 3, -4 }; + TEST((cn.conjugate() == expected)); + } - { - ComplexCart cn1 {3, 4}; - ComplexCart cn2 {1, 2}; - ComplexCart expected {-5, 10}; - TEST((cn1 * cn2 == expected)); - } + { + ComplexCart cn1{ 3, 4 }; + ComplexCart cn2{ 1, 2 }; + ComplexCart expected{ -5, 10 }; + TEST((cn1 * cn2 == expected)); + } - { - ComplexRad c1 {5, 7}; - ComplexRad c2 {10, 3}; - ComplexCart tmp1 = (c1 * c2).cart(); - ComplexCart tmp2 = (c1.cart() * c2.cart()); - TEST((tmp1 - tmp2).mod() < 0.001); - } + { + ComplexRad c1{ 5, 7 }; + ComplexRad c2{ 10, 3 }; + ComplexCart tmp1 = (c1 * c2).cart(); + ComplexCart tmp2 = (c1.cart() * c2.cart()); + TEST((tmp1 - tmp2).mod() < 0.001); + } } TEST_DEF(Math) { testComplexNumber(); } diff --git a/Math/tests/Tests.cpp b/Math/tests/Tests.cpp index cee0396..3853ece 100644 --- a/Math/tests/Tests.cpp +++ b/Math/tests/Tests.cpp @@ -1,23 +1,23 @@ - -#include "MathCommon.hpp" -#include "Testing.hpp" - -static bool init(const tp::ModuleManifest* self) { - tp::gTesting.setRootName(self->getName()); - return true; -} - -void testMath(); - -int main() { - tp::ModuleManifest* deps[] = {&tp::gModuleMath, &tp::gModuleUtils, nullptr}; - tp::ModuleManifest testModule("MathTest", init, nullptr, deps); - - if (!testModule.initialize()) { - return 1; - } - - testMath(); - - testModule.deinitialize(); -} + +#include "MathCommon.hpp" +#include "Testing.hpp" + +static bool init(const tp::ModuleManifest* self) { + tp::gTesting.setRootName(self->getName()); + return true; +} + +void testMath(); + +int main() { + tp::ModuleManifest* deps[] = { &tp::gModuleMath, &tp::gModuleUtils, nullptr }; + tp::ModuleManifest testModule("MathTest", init, nullptr, deps); + + if (!testModule.initialize()) { + return 1; + } + + testMath(); + + testModule.deinitialize(); +} diff --git a/Modules/private/Assert.cpp b/Modules/private/Assert.cpp index 6539d66..1d2fa9b 100644 --- a/Modules/private/Assert.cpp +++ b/Modules/private/Assert.cpp @@ -1,26 +1,22 @@ - -#include "Assert.hpp" - -#include -#include - -using namespace tp; - -void tp::_assert_(const char* exp, const char* file, int line) { - if (!exp) { - exp = "no info"; - } - printf("\nERROR: Assertion Failure - %s -- %s:%i\n", exp, file, line); - -#ifdef ENV_BUILD_DEBUG - DEBUG_BREAK(true); -#else - exit(1); -#endif - - -} - -void tp::terminate(tp::alni code) { - exit((int)code); -} \ No newline at end of file + +#include "Assert.hpp" + +#include +#include + +using namespace tp; + +void tp::_assert_(const char* exp, const char* file, int line) { + if (!exp) { + exp = "no info"; + } + printf("\nERROR: Assertion Failure - %s -- %s:%i\n", exp, file, line); + +#ifdef ENV_BUILD_DEBUG + DEBUG_BREAK(true); +#else + exit(1); +#endif +} + +void tp::terminate(tp::alni code) { exit((int) code); } \ No newline at end of file diff --git a/Modules/private/Common.cpp b/Modules/private/Common.cpp index b92b59a..6b0b5c7 100644 --- a/Modules/private/Common.cpp +++ b/Modules/private/Common.cpp @@ -39,7 +39,7 @@ namespace tp { } ualni hash(alni bytes) { return abs(bytes); } - ualni hash(alnf bytes) { return (alni)(abs(bytes)); } + ualni hash(alnf bytes) { return (alni) (abs(bytes)); } ualni hash(halni bytes) { return hash(alni(bytes)); } ualni hash(uhalni bytes) { return hash(alni(bytes)); } ualni hash(ualni bytes) { return hash(alni(bytes)); } diff --git a/Modules/private/Environment.cpp b/Modules/private/Environment.cpp index fd78f1e..d3b4ab3 100644 --- a/Modules/private/Environment.cpp +++ b/Modules/private/Environment.cpp @@ -9,13 +9,12 @@ const char* ToolchainString[] = { "UNDEF", "GNU", "LLVM", "MSVC" }; const char* OSString[] = { "UNDEF", "LINUX", "WINDOWS", "ANDROID", "IOS" }; const char* ArchWidthString[] = { "UNDEF", "X64", "X32" }; - const tp::Environment tp::gEnvironment; void tp::Environment::log() const { - std::cout << "ARCH : " << ArchString[(int)mArch] << "\n"; - std::cout << "WIDTH : " << ArchWidthString[(int)mWidth] << "\n"; - std::cout << "CURRENT OS : " << OSString[(int)mOS] << "\n"; - std::cout << "TOOLCHAIN : " << ToolchainString[(int)mToolchain] << "\n"; - std::cout << "BUILD TYPE : " << BuildTypeString[(int)mBuildType] << "\n"; + std::cout << "ARCH : " << ArchString[(int) mArch] << "\n"; + std::cout << "WIDTH : " << ArchWidthString[(int) mWidth] << "\n"; + std::cout << "CURRENT OS : " << OSString[(int) mOS] << "\n"; + std::cout << "TOOLCHAIN : " << ToolchainString[(int) mToolchain] << "\n"; + std::cout << "BUILD TYPE : " << BuildTypeString[(int) mBuildType] << "\n"; } \ No newline at end of file diff --git a/Modules/private/Module.cpp b/Modules/private/Module.cpp index 2089a07..54bf334 100644 --- a/Modules/private/Module.cpp +++ b/Modules/private/Module.cpp @@ -1,85 +1,81 @@ - -#include "Module.hpp" - -#include - -using namespace tp; - -static bool init(const ModuleManifest* self) { - gEnvironment.log(); - return true; -} - -static ModuleManifest* deps[] = { nullptr }; -ModuleManifest tp::gModuleBase = ModuleManifest("Common", init, nullptr, deps); - -ModuleManifest::ModuleManifest(const char* aModuleName, ModuleInit aInit, ModuleDeinit aDeinit, ModuleManifest** aDependencies) { - mInit = aInit; - mDeinit = aDeinit; - mDependencies = aDependencies; - mModuleName = aModuleName; -} - -bool ModuleManifest::isInitialized() const { - return mInitialized; -} - -bool ModuleManifest::initialize(const ModuleManifest* parent) { - - if (!parent) std::cout << "===== Initialization Start =====\n"; - - mInitCount++; - - if (isInitialized()) { - return true; - } - - mInitialized = true; - - for (auto module = mDependencies; module && *module; module++) { - mInitialized &= (*module)->initialize(this); - } - - std::cout << " * Initializing \"" << mModuleName << "\" from \"" << (parent ? parent->mModuleName : mModuleName ) << "\"\n"; - - if (mInit) mInitialized &= mInit(this); - - if (!mInitialized) { - std::cout << "Failed to Initialize.\n"; - } - - if (!parent) std::cout << "===== Initialization End =====\n\n"; - - return mInitialized; -} - -void ModuleManifest::deinitialize() { - mInitCount--; - - if (mInitCount > 0) { - return; - } - - if (!isInitialized()) { - return; - } - - if (mDeinit) mDeinit(this); - mInitialized = false; - - auto len = 0; - for (auto module = mDependencies; module && *module; module++) { - len++; - } - - for (auto i = 0; i < len; i++) { - auto module = mDependencies + (len - i - 1); - if ((*module)->isInitialized()) { - (*module)->deinitialize(); - } - } -} - -const char *ModuleManifest::getName() const { - return mModuleName; -} + +#include "Module.hpp" + +#include + +using namespace tp; + +static bool init(const ModuleManifest* self) { + gEnvironment.log(); + return true; +} + +static ModuleManifest* deps[] = { nullptr }; +ModuleManifest tp::gModuleBase = ModuleManifest("Common", init, nullptr, deps); + +ModuleManifest::ModuleManifest(const char* aModuleName, ModuleInit aInit, ModuleDeinit aDeinit, ModuleManifest** aDependencies) { + mInit = aInit; + mDeinit = aDeinit; + mDependencies = aDependencies; + mModuleName = aModuleName; +} + +bool ModuleManifest::isInitialized() const { return mInitialized; } + +bool ModuleManifest::initialize(const ModuleManifest* parent) { + + if (!parent) std::cout << "===== Initialization Start =====\n"; + + mInitCount++; + + if (isInitialized()) { + return true; + } + + mInitialized = true; + + for (auto module = mDependencies; module && *module; module++) { + mInitialized &= (*module)->initialize(this); + } + + std::cout << " * Initializing \"" << mModuleName << "\" from \"" << (parent ? parent->mModuleName : mModuleName) << "\"\n"; + + if (mInit) mInitialized &= mInit(this); + + if (!mInitialized) { + std::cout << "Failed to Initialize.\n"; + } + + if (!parent) std::cout << "===== Initialization End =====\n\n"; + + return mInitialized; +} + +void ModuleManifest::deinitialize() { + mInitCount--; + + if (mInitCount > 0) { + return; + } + + if (!isInitialized()) { + return; + } + + if (mDeinit) mDeinit(this); + mInitialized = false; + + auto len = 0; + for (auto module = mDependencies; module && *module; module++) { + len++; + } + + for (auto i = 0; i < len; i++) { + auto module = mDependencies + (len - i - 1); + if ((*module)->isInitialized()) { + (*module)->deinitialize(); + } + } +} + +const char* ModuleManifest::getName() const { return mModuleName; } diff --git a/Modules/public/Archiver.hpp b/Modules/public/Archiver.hpp index 6bc7ee9..806230f 100644 --- a/Modules/public/Archiver.hpp +++ b/Modules/public/Archiver.hpp @@ -12,14 +12,20 @@ namespace tp { public: struct HasFunc { typedef ArchiverTemplate& ArchRef; - template struct Write : FalseType {}; - template struct Write()().archiveWrite(DeclareValue()()))>> : TrueType {}; + template + struct Write : FalseType {}; + template + struct Write()().archiveWrite(DeclareValue()()))>> : TrueType {}; - template struct Read : FalseType {}; - template struct Read()().archiveRead(DeclareValue()()))>> : TrueType {}; + template + struct Read : FalseType {}; + template + struct Read()().archiveRead(DeclareValue()()))>> : TrueType {}; - template struct Archive : FalseType {}; - template struct Archive()().archive(DeclareValue()()))>> : TrueType {}; + template + struct Archive : FalseType {}; + template + struct Archive()().archive(DeclareValue()()))>> : TrueType {}; template struct AssertCombinations { @@ -35,14 +41,14 @@ namespace tp { public: virtual void writeBytes(const int1* val, ualni size) = 0; - virtual void readBytes(int1* val, ualni size) = 0; + virtual void readBytes(int1* val, ualni size) = 0; public: ArchiverTemplate() = default; // check if type has explicit write method. if not write as bytes - template - void operator <<(const Type& val) { + template + void operator<<(const Type& val) { static_assert(!tRead); static_assert(HasFunc::template AssertCombinations::assert()); if constexpr (HasFunc::template Write::value) { @@ -53,8 +59,8 @@ namespace tp { } // check if type has explicit read method. if not read as bytes - template - void operator >>(Type& val) { + template + void operator>>(Type& val) { static_assert(tRead); static_assert(HasFunc::template AssertCombinations::assert()); if constexpr (HasFunc::template Read::value) { @@ -65,8 +71,8 @@ namespace tp { } // check if type has explicit archive method. if not read/write as bytes - template - void operator %(Type& val) { + template + void operator%(Type& val) { static_assert(HasFunc::template AssertCombinations::assert()); if constexpr (HasFunc::template Archive::value) { val.archive(*this); @@ -79,11 +85,11 @@ namespace tp { } } - template - void operator %(const Type& val) { + template + void operator%(const Type& val) { static_assert(HasFunc::template AssertCombinations::assert()); if constexpr (HasFunc::template Archive::value) { - ((Type&)val).archive(*this); + ((Type&) val).archive(*this); } else { if constexpr (tRead) { operator>>(val); @@ -94,7 +100,7 @@ namespace tp { } }; - template + template class ArchiverExample : public ArchiverTemplate { public: ArchiverExample() = default; @@ -106,12 +112,14 @@ namespace tp { } void writeBytes(const int1* val, ualni size) override { - for (auto i = 0; i < size; i++) mBuff[mAddress + i] = val[i]; + for (auto i = 0; i < size; i++) + mBuff[mAddress + i] = val[i]; incrementAddresses(size); } void readBytes(int1* val, ualni size) override { - for (auto i = 0; i < size; i++) val[i] = mBuff[mAddress + i]; + for (auto i = 0; i < size; i++) + val[i] = mBuff[mAddress + i]; incrementAddresses(size); } diff --git a/Modules/public/Assert.hpp b/Modules/public/Assert.hpp index f80ad71..0704ed2 100644 --- a/Modules/public/Assert.hpp +++ b/Modules/public/Assert.hpp @@ -1,32 +1,48 @@ - -#pragma once - -#include "Environment.hpp" - -namespace tp { - void _assert_(const char* exp, const char* file, int line); - void terminate(tp::alni code = 0); -}; - -#define FAIL(exp) tp::_assert_(#exp, __FILE__, __LINE__); -#define ASSERT(exp) if (!(exp)) { FAIL(exp) } - -#undef assert -#ifdef ENV_BUILD_DEBUG -#define DEBUG_ASSERT(exp) ASSERT(exp) -#else -#define DEBUG_ASSERT(exp) {} -#endif - -#if defined(ENV_OS_WINDOWS) - #define DEBUG_BREAK(expr) if (expr) { __debugbreak(); } -#elif defined(ENV_OS_ANDROID) - #define DEBUG_BREAK(expr) if (expr) { __builtin_debugtrap(); } -#elif defined(ENV_OS_LINUX) - #define DEBUG_BREAK(expr) if (expr) { __builtin_trap(); } -#else - #define DEBUG_BREAK(expr) () -#endif - - -#define SWITCH_NO_DEF default : { FAIL("No Default Case Possible"); } \ No newline at end of file + +#pragma once + +#include "Environment.hpp" + +namespace tp { + void _assert_(const char* exp, const char* file, int line); + void terminate(tp::alni code = 0); +}; + +#define FAIL(exp) tp::_assert_(#exp, __FILE__, __LINE__); +#define ASSERT(exp) \ + if (!(exp)) { \ + FAIL(exp) \ + } + +#undef assert +#ifdef ENV_BUILD_DEBUG +#define DEBUG_ASSERT(exp) ASSERT(exp) +#else +#define DEBUG_ASSERT(exp) \ + {} +#endif + +#if defined(ENV_OS_WINDOWS) +#define DEBUG_BREAK(expr) \ + if (expr) { \ + __debugbreak(); \ + } +#elif defined(ENV_OS_ANDROID) +#define DEBUG_BREAK(expr) \ + if (expr) { \ + __builtin_debugtrap(); \ + } +#elif defined(ENV_OS_LINUX) +#define DEBUG_BREAK(expr) \ + if (expr) { \ + __builtin_trap(); \ + } +#else +#define DEBUG_BREAK(expr) () +#endif + +#define SWITCH_NO_DEF \ + default: \ + { \ + FAIL("No Default Case Possible"); \ + } \ No newline at end of file diff --git a/Modules/public/Common.hpp b/Modules/public/Common.hpp index 06c94ca..44741d0 100644 --- a/Modules/public/Common.hpp +++ b/Modules/public/Common.hpp @@ -8,7 +8,7 @@ #include namespace tp { - template + template using InitialierList = std::initializer_list; // Selects whether to pass by constant reference or by value @@ -25,15 +25,15 @@ namespace tp { template struct DeclareValue { - tType operator()() {} + tType operator()() {} }; struct TrueType { - static constexpr auto value = true; + static constexpr auto value = true; }; struct FalseType { - static constexpr auto value = false; + static constexpr auto value = false; }; } @@ -50,35 +50,64 @@ namespace tp { ualni hash(alnf bytes); template - [[nodiscard]] T clamp(T v, T l, T u) { if (v < l) { v = l; } else if (v > u) { v = u; } return v; } + [[nodiscard]] T clamp(T v, T l, T u) { + if (v < l) { + v = l; + } else if (v > u) { + v = u; + } + return v; + } template - [[nodiscard]] T max(T a, T b) { return (a > b) ? a : b; } + [[nodiscard]] T max(T a, T b) { + return (a > b) ? a : b; + } template - [[nodiscard]] T min(T a, T b) { return (a < b) ? a : b; } + [[nodiscard]] T min(T a, T b) { + return (a < b) ? a : b; + } template - [[nodiscard]] T abs(T v) { if (v < 0) { return -v; } return v; } + [[nodiscard]] T abs(T v) { + if (v < 0) { + return -v; + } + return v; + } template - inline void swap(T& t1, T& t2) { const T tmp = t1; t1 = t2; t2 = tmp; } + inline void swap(T& t1, T& t2) { + const T tmp = t1; + t1 = t2; + t2 = tmp; + } // only for x > 0 and y > 0 template - [[nodiscard]] T ceil_positive(T x, T y) { return T( 1 + ((x - 1) / (tp::alnf)y) ); } + [[nodiscard]] T ceil_positive(T x, T y) { + return T(1 + ((x - 1) / (tp::alnf) y)); + } // power template [[nodiscard]] T pow(T x, uhalni n) { - T out = x; for (uhalni i = 0; i < n - 1; i++) { out = out * x; } + T out = x; + for (uhalni i = 0; i < n - 1; i++) { + out = out * x; + } return out; } - template + template halni nDig10(Type val) { - val = abs(val); halni out = 0; - while (val != 0) { val = halni(val / 10); out++; } + val = abs(val); + halni out = 0; + while (val != 0) { + val = halni(val / 10); + out++; + } return out; } } \ No newline at end of file diff --git a/Modules/public/Environment.hpp b/Modules/public/Environment.hpp index 80ad849..43bc75a 100644 --- a/Modules/public/Environment.hpp +++ b/Modules/public/Environment.hpp @@ -1,198 +1,197 @@ - -#pragma once - -#include -#include - -namespace tp { - - class Environment { - public: - - enum class Arch { UNDEF, INTEL, ARM } mArch = Arch::UNDEF; - - // Build Type - #if defined(__DEBUG__) || defined(_DEBUG) || defined(DEBUG) || !defined(NDEBUG) - #define ENV_BUILD_DEBUG - enum class BuildType { UNDEF, DEBUG, RELEASE } mBuildType = BuildType::DEBUG; - #else - #define ENV_BUILD_RELEASE - enum class BuildType { UNDEF, DEBUG, RELEASE } mBuildType = BuildType::RELEASE; - #endif - - // MCVS - #ifdef _MSC_VER - #define ENV_COMPILER_MSVC - enum class Toolchain { UNDEF, GNU, LLVM, MSVC } mToolchain = Toolchain::MSVC; - - // VERSION - // TODO - - // TARGET OS - #if defined(_WIN32) || defined(_WIN64) - #define ENV_OS_WINDOWS - enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::WINDOWS; - #else - enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::UNDEF; - #error "unexplored compilation to os target" - #endif - - // TARGET ALIGNED SIZE - #ifdef _WIN64 - enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X64; - #define ENV_BITS_64 - #else - enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X32; - #define ENV_BITS_32 - #endif - - #endif - - // GCC - #if defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER) - #define ENV_COMPILER_GCC - enum class Toolchain { UNDEF, GNU, LLVM, MSVC } mToolchain = Toolchain::GNU; - - // VERSION - #if (__GNUC___ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ >= 1)) - // TODO - #endif - - // TARGET OS - #if defined(__linux__) && !defined(__ANDROID__) - #define ENV_OS_LINUX - enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::LINUX; - #else - #error "unexplored compilation to os target" - #endif - - // TARGET ALIGNED SIZE - #if defined(__aarch64__) || defined(__x86_64__) || defined(__ARM_64BIT_STATE) - #define ENV_BITS_64 - enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X64; - #elif defined(__x86_64__) || defined(i386) - #define ENV_BITS_32 - enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X32; - #endif - - #endif - - // CLANG - #if defined(__clang__) && !defined(ENV_COMPILER_GCC) - #define ENV_COMPILER_CLANG - enum class Toolchain { UNDEF, GNU, LLVM, MSVC } mToolchain = Toolchain::LLVM; - - // VERSION - #if (__clang_major__ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ >= 1)) - // TODO - #endif - - // TARGET OS - #if defined(__linux__) && !defined(__ANDROID__) - #define ENV_OS_LINUX - enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::LINUX; - #elif defined(__ANDROID__) - enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::ANDOID; - #define ENV_OS_ANDROID - #else - #error "unexplored compilation to target os" - #endif - - // TARGET ALIGNED SIZE - #if defined(__aarch64__) || defined(__x86_64__) || defined(__ARM_64BIT_STATE) - #define ENV_BITS_64 - enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X64; - #elif defined(__x86_64__) || defined(i386) - #define ENV_BITS_32 - enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X32; - #endif - - #endif - - #if defined(__EMSCRIPTEN__) || defined(__MINGW32__) || defined(__MINGW32__) || defined(__MINGW64__) - #error "compiler is not supported" - #else - #if !(defined(ENV_COMPILER_MSVC) || defined(ENV_COMPILER_CLANG) || defined(ENV_COMPILER_GCC)) - // Linux and Linux - derived __linux__ - // Darwin(Mac OS X and iOS) __APPLE__ - // Akaros __ros__ - // NaCL __native_client__ - // AsmJS __asmjs__ - // Fuschia __Fuchsia__ - #error "unknown compiler" - #endif - #endif - - void log() const; - }; - - #ifndef ENV_BITS_64 - #error "ERROR - not 64 bit archytectures are out of support" - #endif - - const extern Environment gEnvironment; - - typedef char int1; - typedef unsigned char uint1; - typedef short int2; - typedef unsigned short uint2; - typedef unsigned int uint4; - typedef uint2 ufalni; - typedef uint4 uhalni; - typedef int int4; - typedef int4 halni; - typedef unsigned long long uint8; - typedef uint8 ualni; - typedef long long int8; - typedef int8 alni; - typedef double flt8; - typedef flt8 alnf; - typedef float flt4; - typedef flt4 halnf; - - #define ENV_INT1_MAX tp::int1( 0x7f) - #define ENV_INT1_MIN (-tp::int1(0x80)) - #define ENV_UINT1_MAX tp::uint1(0xff) - #define ENV_UINT1_MIN tp::uint1(0x00) - #define ENV_INT2_MAX tp::int2( 0x7fff) - #define ENV_INT2_MIN (-tp::int2(0x8000)) - #define ENV_UINT2_MAX tp::uint2(0xffff) - #define ENV_UINT2_MIN tp::uint2(0x0000) - #define ENV_UHALNI_MAX tp::uhalni(0xffffffff) - #define ENV_UHALNI_MIN tp::uhalni(0x00000000) - #define ENV_HALNI_MAX tp::halni( 0x7fffffff) - #define ENV_HALNI_MIN (-tp::halni(0x80000000)) - #define ENV_UALNI_MAX tp::ualni(0xffffffffffffffff) - #define ENV_UALNI_MIN tp::ualni(0x0000000000000000) - #define ENV_ALNI_MAX tp::alni( 0x7fffffffffffffff) - #define ENV_ALNI_MIN (-tp::alni(0x8000000000000000)) - #define ENV_ALNI_SIZE_B (8) - #define ENV_ALNF_DECIMAL_DIG DBL_DECIMAL_DIG - #define ENV_ALNF_DIG DBL_DIG - #define ENV_ALNF_EPSILON DBL_EPSILON - #define ENV_ALNF_HAS_SUBNORM DBL_HAS_SUBNORM - #define ENV_ALNF_MANT_DIG DBL_MANT_DIG - #define ENV_ALNF_MAX DBL_MAX - #define ENV_ALNF_MAX_10_EXP DBL_MAX_10_EXP - #define ENV_ALNF_MAX_EXP DBL_MAX_EXP - #define ENV_ALNF_MIN DBL_MIN - #define ENV_ALNF_MIN_10_EXP DBL_MIN_10_EXP - #define ENV_ALNF_MIN_EXP DBL_MIN_EXP - #define ENV_ALNF_RADIX _DBL_RADIX - #define ENV_ALNF_TRUE_MIN DBL_TRUE_MIN - #define ENV_HALNF_DECIMAL_DIG FLT_DECIMAL_DIG - #define ENV_HALNF_DIG FLT_DIG - #define ENV_HALNF_EPSILON FLT_EPSILON - #define ENV_HALNF_HAS_SUBNORM FLT_HAS_SUBNORM - #define ENV_HALNF_GUARD FLT_GUARD - #define ENV_HALNF_MANT_DIG FLT_MANT_DIG - #define ENV_HALNF_MAX FLT_MAX - #define ENV_HALNF_MAX_10_EXP FLT_MAX_10_EXP - #define ENV_HALNF_MAX_EXP FLT_MAX_EXP - #define ENV_HALNF_MIN FLT_MIN - #define ENV_HALNF_MIN_10_EXP FLT_MIN_10_EXP - #define ENV_HALNF_MIN_EXP FLT_MIN_EXP - #define ENV_HALNF_NORMALIZE FLT_NORMALIZE - #define ENV_HALNF_RADIX FLT_RADIX - #define ENV_HALNF_TRUE_MIN FLT_TRUE_MIN + +#pragma once + +#include +#include + +namespace tp { + + class Environment { + public: + enum class Arch { UNDEF, INTEL, ARM } mArch = Arch::UNDEF; + +// Build Type +#if defined(__DEBUG__) || defined(_DEBUG) || defined(DEBUG) || !defined(NDEBUG) +#define ENV_BUILD_DEBUG + enum class BuildType { UNDEF, DEBUG, RELEASE } mBuildType = BuildType::DEBUG; +#else +#define ENV_BUILD_RELEASE + enum class BuildType { UNDEF, DEBUG, RELEASE } mBuildType = BuildType::RELEASE; +#endif + +// MCVS +#ifdef _MSC_VER +#define ENV_COMPILER_MSVC + enum class Toolchain { UNDEF, GNU, LLVM, MSVC } mToolchain = Toolchain::MSVC; + +// VERSION +// TODO + +// TARGET OS +#if defined(_WIN32) || defined(_WIN64) +#define ENV_OS_WINDOWS + enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::WINDOWS; +#else + enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::UNDEF; +#error "unexplored compilation to os target" +#endif + +// TARGET ALIGNED SIZE +#ifdef _WIN64 + enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X64; +#define ENV_BITS_64 +#else + enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X32; +#define ENV_BITS_32 +#endif + +#endif + +// GCC +#if defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER) +#define ENV_COMPILER_GCC + enum class Toolchain { UNDEF, GNU, LLVM, MSVC } mToolchain = Toolchain::GNU; + +// VERSION +#if (__GNUC___ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ >= 1)) + // TODO +#endif + +// TARGET OS +#if defined(__linux__) && !defined(__ANDROID__) +#define ENV_OS_LINUX + enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::LINUX; +#else +#error "unexplored compilation to os target" +#endif + +// TARGET ALIGNED SIZE +#if defined(__aarch64__) || defined(__x86_64__) || defined(__ARM_64BIT_STATE) +#define ENV_BITS_64 + enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X64; +#elif defined(__x86_64__) || defined(i386) +#define ENV_BITS_32 + enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X32; +#endif + +#endif + +// CLANG +#if defined(__clang__) && !defined(ENV_COMPILER_GCC) +#define ENV_COMPILER_CLANG + enum class Toolchain { UNDEF, GNU, LLVM, MSVC } mToolchain = Toolchain::LLVM; + +// VERSION +#if (__clang_major__ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ >= 1)) + // TODO +#endif + +// TARGET OS +#if defined(__linux__) && !defined(__ANDROID__) +#define ENV_OS_LINUX + enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::LINUX; +#elif defined(__ANDROID__) + enum class OS { UNDEF, LINUX, WINDOWS, ANDROID, IOS } mOS = OS::ANDOID; +#define ENV_OS_ANDROID +#else +#error "unexplored compilation to target os" +#endif + +// TARGET ALIGNED SIZE +#if defined(__aarch64__) || defined(__x86_64__) || defined(__ARM_64BIT_STATE) +#define ENV_BITS_64 + enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X64; +#elif defined(__x86_64__) || defined(i386) +#define ENV_BITS_32 + enum class ArchWidth { UNDEF, X64, X32 } mWidth = ArchWidth::X32; +#endif + +#endif + +#if defined(__EMSCRIPTEN__) || defined(__MINGW32__) || defined(__MINGW32__) || defined(__MINGW64__) +#error "compiler is not supported" +#else +#if !(defined(ENV_COMPILER_MSVC) || defined(ENV_COMPILER_CLANG) || defined(ENV_COMPILER_GCC)) + // Linux and Linux - derived __linux__ +// Darwin(Mac OS X and iOS) __APPLE__ +// Akaros __ros__ +// NaCL __native_client__ +// AsmJS __asmjs__ +// Fuschia __Fuchsia__ +#error "unknown compiler" +#endif +#endif + + void log() const; + }; + +#ifndef ENV_BITS_64 +#error "ERROR - not 64 bit archytectures are out of support" +#endif + + const extern Environment gEnvironment; + + typedef char int1; + typedef unsigned char uint1; + typedef short int2; + typedef unsigned short uint2; + typedef unsigned int uint4; + typedef uint2 ufalni; + typedef uint4 uhalni; + typedef int int4; + typedef int4 halni; + typedef unsigned long long uint8; + typedef uint8 ualni; + typedef long long int8; + typedef int8 alni; + typedef double flt8; + typedef flt8 alnf; + typedef float flt4; + typedef flt4 halnf; + +#define ENV_INT1_MAX tp::int1(0x7f) +#define ENV_INT1_MIN (-tp::int1(0x80)) +#define ENV_UINT1_MAX tp::uint1(0xff) +#define ENV_UINT1_MIN tp::uint1(0x00) +#define ENV_INT2_MAX tp::int2(0x7fff) +#define ENV_INT2_MIN (-tp::int2(0x8000)) +#define ENV_UINT2_MAX tp::uint2(0xffff) +#define ENV_UINT2_MIN tp::uint2(0x0000) +#define ENV_UHALNI_MAX tp::uhalni(0xffffffff) +#define ENV_UHALNI_MIN tp::uhalni(0x00000000) +#define ENV_HALNI_MAX tp::halni(0x7fffffff) +#define ENV_HALNI_MIN (-tp::halni(0x80000000)) +#define ENV_UALNI_MAX tp::ualni(0xffffffffffffffff) +#define ENV_UALNI_MIN tp::ualni(0x0000000000000000) +#define ENV_ALNI_MAX tp::alni(0x7fffffffffffffff) +#define ENV_ALNI_MIN (-tp::alni(0x8000000000000000)) +#define ENV_ALNI_SIZE_B (8) +#define ENV_ALNF_DECIMAL_DIG DBL_DECIMAL_DIG +#define ENV_ALNF_DIG DBL_DIG +#define ENV_ALNF_EPSILON DBL_EPSILON +#define ENV_ALNF_HAS_SUBNORM DBL_HAS_SUBNORM +#define ENV_ALNF_MANT_DIG DBL_MANT_DIG +#define ENV_ALNF_MAX DBL_MAX +#define ENV_ALNF_MAX_10_EXP DBL_MAX_10_EXP +#define ENV_ALNF_MAX_EXP DBL_MAX_EXP +#define ENV_ALNF_MIN DBL_MIN +#define ENV_ALNF_MIN_10_EXP DBL_MIN_10_EXP +#define ENV_ALNF_MIN_EXP DBL_MIN_EXP +#define ENV_ALNF_RADIX _DBL_RADIX +#define ENV_ALNF_TRUE_MIN DBL_TRUE_MIN +#define ENV_HALNF_DECIMAL_DIG FLT_DECIMAL_DIG +#define ENV_HALNF_DIG FLT_DIG +#define ENV_HALNF_EPSILON FLT_EPSILON +#define ENV_HALNF_HAS_SUBNORM FLT_HAS_SUBNORM +#define ENV_HALNF_GUARD FLT_GUARD +#define ENV_HALNF_MANT_DIG FLT_MANT_DIG +#define ENV_HALNF_MAX FLT_MAX +#define ENV_HALNF_MAX_10_EXP FLT_MAX_10_EXP +#define ENV_HALNF_MAX_EXP FLT_MAX_EXP +#define ENV_HALNF_MIN FLT_MIN +#define ENV_HALNF_MIN_10_EXP FLT_MIN_10_EXP +#define ENV_HALNF_MIN_EXP FLT_MIN_EXP +#define ENV_HALNF_NORMALIZE FLT_NORMALIZE +#define ENV_HALNF_RADIX FLT_RADIX +#define ENV_HALNF_TRUE_MIN FLT_TRUE_MIN }; \ No newline at end of file diff --git a/Modules/public/Module.hpp b/Modules/public/Module.hpp index 7d01e42..ef11973 100644 --- a/Modules/public/Module.hpp +++ b/Modules/public/Module.hpp @@ -1,35 +1,35 @@ - -#pragma once - -#include "Common.hpp" -#include "Assert.hpp" - -#define MODULE_SANITY_CHECK(name) DEBUG_ASSERT(name.isInitialized() && "Modules Is Not Initialized" && #name) - -namespace tp { - - class ModuleManifest { - public: - typedef bool (*ModuleInit)(const ModuleManifest*); - typedef void (*ModuleDeinit)(const ModuleManifest*); - - ModuleManifest(const char* aModuleName, ModuleInit aInit, ModuleDeinit aDeinit, ModuleManifest** aDependencies); - [[nodiscard]] bool isInitialized() const; - bool initialize(const ModuleManifest* parent = nullptr); - void deinitialize(); - [[nodiscard]] const char* getName() const; - void setCustomData(void* data) { mCustomData = data; } - void* getCustomData(void* data) const { return mCustomData; } - - private: - const char* mModuleName = nullptr; - ModuleManifest** mDependencies; // NULL terminated - bool mInitialized = false; - ModuleInit mInit = nullptr; - ModuleDeinit mDeinit = nullptr; - uhalni mInitCount = 0; - void* mCustomData = nullptr; - }; - - extern ModuleManifest gModuleBase; -}; + +#pragma once + +#include "Assert.hpp" +#include "Common.hpp" + +#define MODULE_SANITY_CHECK(name) DEBUG_ASSERT(name.isInitialized() && "Modules Is Not Initialized" && #name) + +namespace tp { + + class ModuleManifest { + public: + typedef bool (*ModuleInit)(const ModuleManifest*); + typedef void (*ModuleDeinit)(const ModuleManifest*); + + ModuleManifest(const char* aModuleName, ModuleInit aInit, ModuleDeinit aDeinit, ModuleManifest** aDependencies); + [[nodiscard]] bool isInitialized() const; + bool initialize(const ModuleManifest* parent = nullptr); + void deinitialize(); + [[nodiscard]] const char* getName() const; + void setCustomData(void* data) { mCustomData = data; } + void* getCustomData(void* data) const { return mCustomData; } + + private: + const char* mModuleName = nullptr; + ModuleManifest** mDependencies; // NULL terminated + bool mInitialized = false; + ModuleInit mInit = nullptr; + ModuleDeinit mDeinit = nullptr; + uhalni mInitCount = 0; + void* mCustomData = nullptr; + }; + + extern ModuleManifest gModuleBase; +}; diff --git a/Modules/public/SizeCounter.hpp b/Modules/public/SizeCounter.hpp index e861738..3622d49 100644 --- a/Modules/public/SizeCounter.hpp +++ b/Modules/public/SizeCounter.hpp @@ -8,7 +8,7 @@ namespace tp { public: SaveSizeCounter() = default; - template < typename tType> + template static ualni calc(const tType& val) { SaveSizeCounter cnt; cnt << val; @@ -25,19 +25,19 @@ namespace tp { ualni mSize = 0; }; - - // TODO template class SizeCounter { typedef SizeCounter& ArchRef; - template struct HasSizeCounter : FalseType {}; - template struct HasSizeCounter()().count(DeclareValue()()))>> : TrueType {}; + template + struct HasSizeCounter : FalseType {}; + template + struct HasSizeCounter()().count(DeclareValue()()))>> : TrueType {}; public: SizeCounter() = default; - template + template void count(const Type& val) { if constexpr (HasSizeCounter::value) { val.count(*this); @@ -50,21 +50,13 @@ namespace tp { } } - void countSizeUnused(ualni size) { - mSizeUnused += size; - } + void countSizeUnused(ualni size) { mSizeUnused += size; } - void countSize(ualni size) { - mSize += size; - } + void countSize(ualni size) { mSize += size; } - [[nodiscard]] ualni getSizeUnused() const { - return mSizeUnused; - } + [[nodiscard]] ualni getSizeUnused() const { return mSizeUnused; } - [[nodiscard]] ualni getSize() const { - return mSize; - } + [[nodiscard]] ualni getSize() const { return mSize; } private: ualni mSize = 0; diff --git a/Modules/public/TypeInfo.hpp b/Modules/public/TypeInfo.hpp index dbbb893..29404c8 100644 --- a/Modules/public/TypeInfo.hpp +++ b/Modules/public/TypeInfo.hpp @@ -28,7 +28,6 @@ // SOFTWARE. //////////////////////////////////////////////////////////////////////////////// - namespace tp { template struct TypeSelect { @@ -41,14 +40,14 @@ namespace tp { } namespace tp { -//////////////////////////////////////////////////////////////////////////////// -// class template IsSameType -// Return true iff two given types are the same -// Invocation: SameType::value -// where: -// T and U are types -// Result evaluates to true iff U == T (types equal) -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template IsSameType + // Return true iff two given types are the same + // Invocation: SameType::value + // where: + // T and U are types + // Result evaluates to true iff U == T (types equal) + //////////////////////////////////////////////////////////////////////////////// template struct IsSameType { @@ -60,36 +59,38 @@ namespace tp { enum { value = true }; }; -//////////////////////////////////////////////////////////////////////////////// -// Helper types Small and Big - guarantee that sizeof(Small) < sizeof(Big) -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // Helper types Small and Big - guarantee that sizeof(Small) < sizeof(Big) + //////////////////////////////////////////////////////////////////////////////// namespace Private { template struct ConversionHelper { typedef char Small; - struct Big { char dummy[2]; }; - static Big Test(...); + struct Big { + char dummy[2]; + }; + static Big Test(...); static Small Test(U); static T MakeT(); }; } -//////////////////////////////////////////////////////////////////////////////// -// class template Conversion -// Figures out the conversion relationships between two types -// Invocations (T and U are types): -// a) Conversion::exists -// returns (at compile time) true if there is an implicit conversion from T -// to U (example: Derived to Base) -// b) Conversion::exists2Way -// returns (at compile time) true if there are both conversions from T -// to U and from U to T (example: int to char and back) -// c) Conversion::sameType -// returns (at compile time) true if T and U represent the same type -// -// Caveat: might not work if T and U are in a private inheritance hierarchy. -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template Conversion + // Figures out the conversion relationships between two types + // Invocations (T and U are types): + // a) Conversion::exists + // returns (at compile time) true if there is an implicit conversion from T + // to U (example: Derived to Base) + // b) Conversion::exists2Way + // returns (at compile time) true if there are both conversions from T + // to U and from U to T (example: int to char and back) + // c) Conversion::sameType + // returns (at compile time) true if T and U represent the same type + // + // Caveat: might not work if T and U are in a private inheritance hierarchy. + //////////////////////////////////////////////////////////////////////////////// template struct Conversion { @@ -124,22 +125,20 @@ namespace tp { enum { exists = 1, exists2Way = 1, sameType = 1 }; }; -//////////////////////////////////////////////////////////////////////////////// -// class template SuperSubclass -// Invocation: SuperSubclass::value where B and D are types. -// Returns true if B is a public base of D, or if B and D are aliases of the -// same type. -// -// Caveat: might not work if T and U are in a private inheritance hierarchy. -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template SuperSubclass + // Invocation: SuperSubclass::value where B and D are types. + // Returns true if B is a public base of D, or if B and D are aliases of the + // same type. + // + // Caveat: might not work if T and U are in a private inheritance hierarchy. + //////////////////////////////////////////////////////////////////////////////// template struct SuperSubclass { - enum { - value = (::tp::Conversion::exists && !::tp::Conversion::sameType) - }; + enum { value = (::tp::Conversion::exists && !::tp::Conversion::sameType) }; -// Dummy enum to make sure that both classes are fully defined. + // Dummy enum to make sure that both classes are fully defined. enum { dontUseWithIncompleteTypes = (sizeof(T) == sizeof(U)) }; }; @@ -150,21 +149,17 @@ namespace tp { template struct SuperSubclass { - enum { - value = (::tp::Conversion::exists && !::tp::Conversion::sameType) - }; + enum { value = (::tp::Conversion::exists && !::tp::Conversion::sameType) }; -// Dummy enum to make sure that both classes are fully defined. + // Dummy enum to make sure that both classes are fully defined. enum { dontUseWithIncompleteTypes = (0 == sizeof(U)) }; }; template struct SuperSubclass { - enum { - value = (::tp::Conversion::exists && !::tp::Conversion::sameType) - }; + enum { value = (::tp::Conversion::exists && !::tp::Conversion::sameType) }; -// Dummy enum to make sure that both classes are fully defined. + // Dummy enum to make sure that both classes are fully defined. enum { dontUseWithIncompleteTypes = (sizeof(T) == 0) }; }; @@ -176,49 +171,36 @@ namespace tp { // Caveat: might not work if T and U are in a private inheritance hierarchy. //////////////////////////////////////////////////////////////////////////////// - template + template struct SuperSubclassStrict { - enum { - value = (::tp::Conversion::exists && - !::tp::Conversion::sameType && - !::tp::Conversion::sameType) - }; + enum { value = (::tp::Conversion::exists && !::tp::Conversion::sameType && !::tp::Conversion::sameType) }; -// Dummy enum to make sure that both classes are fully defined. + // Dummy enum to make sure that both classes are fully defined. enum { dontUseWithIncompleteTypes = (sizeof(T) == sizeof(U)) }; }; - template<> + template <> struct SuperSubclassStrict { enum { value = false }; }; - template + template struct SuperSubclassStrict { - enum { - value = (::tp::Conversion::exists && - !::tp::Conversion::sameType && - !::tp::Conversion::sameType) - }; + enum { value = (::tp::Conversion::exists && !::tp::Conversion::sameType && !::tp::Conversion::sameType) }; -// Dummy enum to make sure that both classes are fully defined. + // Dummy enum to make sure that both classes are fully defined. enum { dontUseWithIncompleteTypes = (0 == sizeof(U)) }; }; - template + template struct SuperSubclassStrict { - enum { - value = (::tp::Conversion::exists && - !::tp::Conversion::sameType && - !::tp::Conversion::sameType) - }; + enum { value = (::tp::Conversion::exists && !::tp::Conversion::sameType && !::tp::Conversion::sameType) }; -// Dummy enum to make sure that both classes are fully defined. + // Dummy enum to make sure that both classes are fully defined. enum { dontUseWithIncompleteTypes = (sizeof(T) == 0) }; }; - -} // namespace tp +} // namespace tp //////////////////////////////////////////////////////////////////////////////// // macro SUPERSUBCLASS @@ -230,7 +212,7 @@ namespace tp { // Deprecated: Use SuperSubclass class template instead. //////////////////////////////////////////////////////////////////////////////// -#define SUPERSUBCLASS(T, U) ::tp::SuperSubclass::value +#define SUPERSUBCLASS(T, U) ::tp::SuperSubclass::value //////////////////////////////////////////////////////////////////////////////// // macro SUPERSUBCLASS_STRICT @@ -241,22 +223,20 @@ namespace tp { // Deprecated: Use SuperSubclassStrict class template instead. //////////////////////////////////////////////////////////////////////////////// -#define SUPERSUBCLASS_STRICT(T, U) ::tp::SuperSubclassStrict::value - - +#define SUPERSUBCLASS_STRICT(T, U) ::tp::SuperSubclassStrict::value namespace tp { struct NullType {}; -//////////////////////////////////////////////////////////////////////////////// -// class template Typelist -// The building block of typelists of any length -// Use it through the LOKI_TYPELIST_NN macros -// Defines nested types: -// Head (first element, a non-typelist type by convention) -// Tail (second element, can be another typelist) -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template Typelist + // The building block of typelists of any length + // Use it through the LOKI_TYPELIST_NN macros + // Defines nested types: + // Head (first element, a non-typelist type by convention) + // Tail (second element, can be another typelist) + //////////////////////////////////////////////////////////////////////////////// template struct Typelist { @@ -264,79 +244,83 @@ namespace tp { typedef U Tail; }; -// Typelist utility algorithms + // Typelist utility algorithms namespace TL { -//////////////////////////////////////////////////////////////////////////////// -// class template MakeTypelist -// Takes a number of arguments equal to its numeric suffix -// The arguments are type names. -// MakeTypelist::Result -// returns a typelist that is of T1, T2, ... -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template MakeTypelist + // Takes a number of arguments equal to its numeric suffix + // The arguments are type names. + // MakeTypelist::Result + // returns a typelist that is of T1, T2, ... + //////////////////////////////////////////////////////////////////////////////// - template - < - typename T1 = NullType, typename T2 = NullType, typename T3 = NullType, - typename T4 = NullType, typename T5 = NullType, typename T6 = NullType, - typename T7 = NullType, typename T8 = NullType, typename T9 = NullType, - typename T10 = NullType, typename T11 = NullType, typename T12 = NullType, - typename T13 = NullType, typename T14 = NullType, typename T15 = NullType, - typename T16 = NullType, typename T17 = NullType, typename T18 = NullType - > + template < + typename T1 = NullType, + typename T2 = NullType, + typename T3 = NullType, + typename T4 = NullType, + typename T5 = NullType, + typename T6 = NullType, + typename T7 = NullType, + typename T8 = NullType, + typename T9 = NullType, + typename T10 = NullType, + typename T11 = NullType, + typename T12 = NullType, + typename T13 = NullType, + typename T14 = NullType, + typename T15 = NullType, + typename T16 = NullType, + typename T17 = NullType, + typename T18 = NullType> struct MakeTypelist { private: - typedef typename MakeTypelist - < - T2, T3, T4, - T5, T6, T7, - T8, T9, T10, - T11, T12, T13, - T14, T15, T16, - T17, T18 - > - ::Result TailResult; + typedef typename MakeTypelist::Result TailResult; public: typedef Typelist Result; }; - template<> + template <> struct MakeTypelist<> { typedef NullType Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template Length -// Computes the length of a typelist -// Invocation (TList is a typelist): -// Length::value -// returns a compile-time constant containing the length of TList, not counting -// the end terminator (which by convention is NullType) -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template Length + // Computes the length of a typelist + // Invocation (TList is a typelist): + // Length::value + // returns a compile-time constant containing the length of TList, not counting + // the end terminator (which by convention is NullType) + //////////////////////////////////////////////////////////////////////////////// - template struct Length; - template <> struct Length { + template + struct Length; + template <> + struct Length { enum { value = 0 }; }; template - struct Length< Typelist > { + struct Length> { enum { value = 1 + Length::value }; }; -//////////////////////////////////////////////////////////////////////////////// -// class template TypeAt -// Finds the type at a given index in a typelist -// Invocation (TList is a typelist and index is a compile-time integral -// constant): -// TypeAt::Result -// returns the type in position 'index' in TList -// If you pass an out-of-bounds index, the result is a compile-time error -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template TypeAt + // Finds the type at a given index in a typelist + // Invocation (TList is a typelist and index is a compile-time integral + // constant): + // TypeAt::Result + // returns the type in position 'index' in TList + // If you pass an out-of-bounds index, the result is a compile-time error + //////////////////////////////////////////////////////////////////////////////// - template struct TypeAt; + template + struct TypeAt; template struct TypeAt, 0> { @@ -348,20 +332,19 @@ namespace tp { typedef typename TypeAt::Result Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template TypeAtNonStrict -// Finds the type at a given index in a typelist -// Invocations (TList is a typelist and index is a compile-time integral -// constant): -// a) TypeAt::Result -// returns the type in position 'index' in TList, or NullType if index is -// out-of-bounds -// b) TypeAt::Result -// returns the type in position 'index' in TList, or D if index is out-of-bounds -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template TypeAtNonStrict + // Finds the type at a given index in a typelist + // Invocations (TList is a typelist and index is a compile-time integral + // constant): + // a) TypeAt::Result + // returns the type in position 'index' in TList, or NullType if index is + // out-of-bounds + // b) TypeAt::Result + // returns the type in position 'index' in TList, or D if index is out-of-bounds + //////////////////////////////////////////////////////////////////////////////// - template + template struct TypeAtNonStrict { typedef DefaultType Result; }; @@ -373,19 +356,19 @@ namespace tp { template struct TypeAtNonStrict, i, DefaultType> { - typedef typename - TypeAtNonStrict::Result Result; + typedef typename TypeAtNonStrict::Result Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template IndexOf -// Finds the index of a type in a typelist -// Invocation (TList is a typelist and T is a type): -// IndexOf::value -// returns the position of T in TList, or NullType if T is not found in TList -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template IndexOf + // Finds the index of a type in a typelist + // Invocation (TList is a typelist and T is a type): + // IndexOf::value + // returns the position of T in TList, or NullType if T is not found in TList + //////////////////////////////////////////////////////////////////////////////// - template struct IndexOf; + template + struct IndexOf; template struct IndexOf { @@ -401,30 +384,34 @@ namespace tp { struct IndexOf, T> { private: enum { temp = IndexOf::value }; + public: enum { value = (temp == -1 ? -1 : 1 + temp) }; }; -//////////////////////////////////////////////////////////////////////////////// -// class template Append -// Appends a type or a typelist to another -// Invocation (TList is a typelist and T is either a type or a typelist): -// Append::Result -// returns a typelist that is TList followed by T and NullType-terminated -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template Append + // Appends a type or a typelist to another + // Invocation (TList is a typelist and T is either a type or a typelist): + // Append::Result + // returns a typelist that is TList followed by T and NullType-terminated + //////////////////////////////////////////////////////////////////////////////// - template struct Append; + template + struct Append; - template <> struct Append { + template <> + struct Append { typedef NullType Result; }; - template struct Append { + template + struct Append { typedef Typelist Result; }; template - struct Append > { + struct Append> { typedef Typelist Result; }; @@ -433,22 +420,23 @@ namespace tp { typedef Typelist::Result> Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template Erase -// Erases the first occurence, if any, of a type in a typelist -// Invocation (TList is a typelist and T is a type): -// Erase::Result -// returns a typelist that is TList without the first occurence of T -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template Erase + // Erases the first occurence, if any, of a type in a typelist + // Invocation (TList is a typelist and T is a type): + // Erase::Result + // returns a typelist that is TList without the first occurence of T + //////////////////////////////////////////////////////////////////////////////// - template struct Erase; + template + struct Erase; - template // Specialization 1 + template // Specialization 1 struct Erase { typedef NullType Result; }; - template // Specialization 2 + template // Specialization 2 struct Erase, T> { typedef Tail Result; }; @@ -458,15 +446,16 @@ namespace tp { typedef Typelist::Result> Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template EraseAll -// Erases all first occurences, if any, of a type in a typelist -// Invocation (TList is a typelist and T is a type): -// EraseAll::Result -// returns a typelist that is TList without any occurence of T -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template EraseAll + // Erases all first occurences, if any, of a type in a typelist + // Invocation (TList is a typelist and T is a type): + // EraseAll::Result + // returns a typelist that is TList without any occurence of T + //////////////////////////////////////////////////////////////////////////////// - template struct EraseAll; + template + struct EraseAll; template struct EraseAll { typedef NullType Result; @@ -482,37 +471,41 @@ namespace tp { typedef Typelist::Result> Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template NoDuplicates -// Removes all duplicate types in a typelist -// Invocation (TList is a typelist): -// NoDuplicates::Result -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template NoDuplicates + // Removes all duplicate types in a typelist + // Invocation (TList is a typelist): + // NoDuplicates::Result + //////////////////////////////////////////////////////////////////////////////// - template struct NoDuplicates; + template + struct NoDuplicates; - template <> struct NoDuplicates { + template <> + struct NoDuplicates { typedef NullType Result; }; template - struct NoDuplicates< Typelist > { + struct NoDuplicates> { private: typedef typename NoDuplicates::Result L1; typedef typename Erase::Result L2; + public: typedef Typelist Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template Replace -// Replaces the first occurence of a type in a typelist, with another type -// Invocation (TList is a typelist, T, U are types): -// Replace::Result -// returns a typelist in which the first occurence of T is replaced with U -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template Replace + // Replaces the first occurence of a type in a typelist, with another type + // Invocation (TList is a typelist, T, U are types): + // Replace::Result + // returns a typelist in which the first occurence of T is replaced with U + //////////////////////////////////////////////////////////////////////////////// - template struct Replace; + template + struct Replace; template struct Replace { @@ -529,15 +522,16 @@ namespace tp { typedef Typelist::Result> Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template ReplaceAll -// Replaces all occurences of a type in a typelist, with another type -// Invocation (TList is a typelist, T, U are types): -// Replace::Result -// returns a typelist in which all occurences of T is replaced with U -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template ReplaceAll + // Replaces all occurences of a type in a typelist, with another type + // Invocation (TList is a typelist, T, U are types): + // Replace::Result + // returns a typelist in which all occurences of T is replaced with U + //////////////////////////////////////////////////////////////////////////////// - template struct ReplaceAll; + template + struct ReplaceAll; template struct ReplaceAll { @@ -554,15 +548,16 @@ namespace tp { typedef Typelist::Result> Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template Reverse -// Reverses a typelist -// Invocation (TList is a typelist): -// Reverse::Result -// returns a typelist that is TList reversed -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template Reverse + // Reverses a typelist + // Invocation (TList is a typelist): + // Reverse::Result + // returns a typelist that is TList reversed + //////////////////////////////////////////////////////////////////////////////// - template struct Reverse; + template + struct Reverse; template <> struct Reverse { @@ -570,19 +565,20 @@ namespace tp { }; template - struct Reverse< Typelist > { - typedef typename Append::Result, Head>::Result Result; + struct Reverse> { + typedef typename Append::Result, Head>::Result Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template MostDerived -// Finds the type in a typelist that is the most derived from a given type -// Invocation (TList is a typelist, T is a type): -// MostDerived::Result -// returns the type in TList that's the most derived from T -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template MostDerived + // Finds the type in a typelist that is the most derived from a given type + // Invocation (TList is a typelist, T is a type): + // MostDerived::Result + // returns the type in TList that's the most derived from T + //////////////////////////////////////////////////////////////////////////////// - template struct MostDerived; + template + struct MostDerived; template struct MostDerived { @@ -593,19 +589,21 @@ namespace tp { struct MostDerived, T> { private: typedef typename MostDerived::Result Candidate; + public: typedef typename TypeSelect::value, Head, Candidate>::Result Result; }; -//////////////////////////////////////////////////////////////////////////////// -// class template DerivedToFront -// Arranges the types in a typelist so that the most derived types appear first -// Invocation (TList is a typelist): -// DerivedToFront::Result -// returns the reordered TList -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template DerivedToFront + // Arranges the types in a typelist so that the most derived types appear first + // Invocation (TList is a typelist): + // DerivedToFront::Result + // returns the reordered TList + //////////////////////////////////////////////////////////////////////////////// - template struct DerivedToFront; + template + struct DerivedToFront; template <> struct DerivedToFront { @@ -613,111 +611,127 @@ namespace tp { }; template - struct DerivedToFront< Typelist > { + struct DerivedToFront> { private: typedef typename MostDerived::Result TheMostDerived; typedef typename Replace::Result Temp; typedef typename DerivedToFront::Result L; + public: typedef Typelist Result; }; - } // namespace TL - + } // namespace TL template < - class T01 = NullType, class T02 = NullType, class T03 = NullType, class T04 = NullType, class T05 = NullType, - class T06 = NullType, class T07 = NullType, class T08 = NullType, class T09 = NullType, class T10 = NullType, - class T11 = NullType, class T12 = NullType, class T13 = NullType, class T14 = NullType, class T15 = NullType, - class T16 = NullType, class T17 = NullType, class T18 = NullType, class T19 = NullType, class T20 = NullType - > + class T01 = NullType, + class T02 = NullType, + class T03 = NullType, + class T04 = NullType, + class T05 = NullType, + class T06 = NullType, + class T07 = NullType, + class T08 = NullType, + class T09 = NullType, + class T10 = NullType, + class T11 = NullType, + class T12 = NullType, + class T13 = NullType, + class T14 = NullType, + class T15 = NullType, + class T16 = NullType, + class T17 = NullType, + class T18 = NullType, + class T19 = NullType, + class T20 = NullType> class Seq { typedef typename Seq::list TailResult; + public: typedef Typelist list; }; - template<> + template <> struct Seq<> { typedef NullType list; }; -} // namespace tp +} // namespace tp #if 0 -#define TYPELIST1(T1) ::compiler::Typelist -#define TYPELIST2(T1, T2) ::compiler::Typelist -#define TYPELIST3(T1, T2, T3) ::compiler::Typelist -#define TYPELIST4(T1, T2, T3, T4) ::compiler::Typelist -#define TYPELIST5(T1, T2, T3, T4, T5) ::compiler::Typelist -#define TYPELIST6(T1, T2, T3, T4, T5, T6) ::compiler::Typelist -#define TYPELIST7(T1, T2, T3, T4, T5, T6, T7) ::compiler::Typelist -#define TYPELIST8(T1, T2, T3, T4, T5, T6, T7, T8) ::compiler::Typelist -#define TYPELIST9(T1, T2, T3, T4, T5, T6, T7, T8, T9) ::compiler::Typelist -#define TYPELIST10(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) ::compiler::Typelist +#define TYPELIST1(T1) ::compiler::Typelist +#define TYPELIST2(T1, T2) ::compiler::Typelist +#define TYPELIST3(T1, T2, T3) ::compiler::Typelist +#define TYPELIST4(T1, T2, T3, T4) ::compiler::Typelist +#define TYPELIST5(T1, T2, T3, T4, T5) ::compiler::Typelist +#define TYPELIST6(T1, T2, T3, T4, T5, T6) ::compiler::Typelist +#define TYPELIST7(T1, T2, T3, T4, T5, T6, T7) ::compiler::Typelist +#define TYPELIST8(T1, T2, T3, T4, T5, T6, T7, T8) ::compiler::Typelist +#define TYPELIST9(T1, T2, T3, T4, T5, T6, T7, T8, T9) ::compiler::Typelist +#define TYPELIST10(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) ::compiler::Typelist #endif #include #ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable : 4180 ) //qualifier applied to function type has no meaning; ignored +#pragma warning(push) +#pragma warning(disable : 4180) // qualifier applied to function type has no meaning; ignored #endif namespace tp { -//////////////////////////////////////////////////////////////////////////////// -// class template IsCustomUnsignedInt -// Offers a means to integrate nonstandard built-in unsigned integral types -// (such as unsigned __int64 or unsigned long long int) with the TypeTraits -// class template defined below. -// Invocation: IsCustomUnsignedInt where T is any type -// Defines 'value', an enum that is 1 iff T is a custom built-in unsigned -// integral type -// Specialize this class template for nonstandard unsigned integral types -// and define value = 1 in those specializations -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template IsCustomUnsignedInt + // Offers a means to integrate nonstandard built-in unsigned integral types + // (such as unsigned __int64 or unsigned long long int) with the TypeTraits + // class template defined below. + // Invocation: IsCustomUnsignedInt where T is any type + // Defines 'value', an enum that is 1 iff T is a custom built-in unsigned + // integral type + // Specialize this class template for nonstandard unsigned integral types + // and define value = 1 in those specializations + //////////////////////////////////////////////////////////////////////////////// template struct IsCustomUnsignedInt { enum { value = 0 }; }; -//////////////////////////////////////////////////////////////////////////////// -// class template IsCustomSignedInt -// Offers a means to integrate nonstandard built-in unsigned integral types -// (such as unsigned __int64 or unsigned long long int) with the TypeTraits -// class template defined below. -// Invocation: IsCustomSignedInt where T is any type -// Defines 'value', an enum that is 1 iff T is a custom built-in signed -// integral type -// Specialize this class template for nonstandard unsigned integral types -// and define value = 1 in those specializations -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template IsCustomSignedInt + // Offers a means to integrate nonstandard built-in unsigned integral types + // (such as unsigned __int64 or unsigned long long int) with the TypeTraits + // class template defined below. + // Invocation: IsCustomSignedInt where T is any type + // Defines 'value', an enum that is 1 iff T is a custom built-in signed + // integral type + // Specialize this class template for nonstandard unsigned integral types + // and define value = 1 in those specializations + //////////////////////////////////////////////////////////////////////////////// template struct IsCustomSignedInt { enum { value = 0 }; }; -//////////////////////////////////////////////////////////////////////////////// -// class template IsCustomFloat -// Offers a means to integrate nonstandard floating point types with the -// TypeTraits class template defined below. -// Invocation: IsCustomFloat where T is any type -// Defines 'value', an enum that is 1 iff T is a custom built-in -// floating point type -// Specialize this class template for nonstandard unsigned integral types -// and define value = 1 in those specializations -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template IsCustomFloat + // Offers a means to integrate nonstandard floating point types with the + // TypeTraits class template defined below. + // Invocation: IsCustomFloat where T is any type + // Defines 'value', an enum that is 1 iff T is a custom built-in + // floating point type + // Specialize this class template for nonstandard unsigned integral types + // and define value = 1 in those specializations + //////////////////////////////////////////////////////////////////////////////// template struct IsCustomFloat { enum { value = 0 }; }; -//////////////////////////////////////////////////////////////////////////////// -// Helper types for class template TypeTraits defined below -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // Helper types for class template TypeTraits defined below + //////////////////////////////////////////////////////////////////////////////// namespace Private { @@ -726,124 +740,161 @@ namespace tp { typedef Seq::list StdOtherInts; typedef Seq::list StdFloats; - template struct AddPointer { typedef U* Result; }; - template struct AddPointer { typedef U* Result; }; + template + struct AddPointer { + typedef U* Result; + }; + template + struct AddPointer { + typedef U* Result; + }; - template struct AddReference { typedef U& Result; }; - template struct AddReference { typedef U& Result; }; - template <> struct AddReference { typedef NullType Result; }; + template + struct AddReference { + typedef U& Result; + }; + template + struct AddReference { + typedef U& Result; + }; + template <> + struct AddReference { + typedef NullType Result; + }; - template struct AddParameterType { typedef const U& Result; }; - template struct AddParameterType { typedef U& Result; }; - template <> struct AddParameterType { typedef NullType Result; }; + template + struct AddParameterType { + typedef const U& Result; + }; + template + struct AddParameterType { + typedef U& Result; + }; + template <> + struct AddParameterType { + typedef NullType Result; + }; - }// namespace Private + } // namespace Private -//////////////////////////////////////////////////////////////////////////////// -// class template TypeTraits -// -// Figures out at compile time various properties of any given type -// Invocations (T is a type, TypeTraits::Property): -// -// - isPointer : returns true if T is a pointer type -// - PointeeType : returns the type to which T points if T is a pointer -// type, NullType otherwise -// - isReference : returns true if T is a reference type -// - ReferredType : returns the type to which T refers if T is a reference -// type, NullType otherwise -// - isMemberPointer : returns true if T is a pointer to member type -// - isStdUnsignedInt: returns true if T is a standard unsigned integral type -// - isStdSignedInt : returns true if T is a standard signed integral type -// - isStdIntegral : returns true if T is a standard integral type -// - isStdFloat : returns true if T is a standard floating-point type -// - isStdArith : returns true if T is a standard arithmetic type -// - isStdFundamental: returns true if T is a standard fundamental type -// - isUnsignedInt : returns true if T is a unsigned integral type -// - isSignedInt : returns true if T is a signed integral type -// - isIntegral : returns true if T is a integral type -// - isFloat : returns true if T is a floating-point type -// - isArith : returns true if T is a arithmetic type -// - isFundamental : returns true if T is a fundamental type -// - ParameterType : returns the optimal type to be used as a parameter for -// functions that take Ts -// - isConst : returns true if T is a const-qualified type -// - NonConstType : Type with removed 'const' qualifier from T, if any -// - isVolatile : returns true if T is a volatile-qualified type -// - NonVolatileType : Type with removed 'volatile' qualifier from T, if any -// - UnqualifiedType : Type with removed 'const' and 'volatile' qualifiers from -// T, if any -// - ParameterType : returns the optimal type to be used as a parameter -// for functions that take 'const T's -// -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // class template TypeTraits + // + // Figures out at compile time various properties of any given type + // Invocations (T is a type, TypeTraits::Property): + // + // - isPointer : returns true if T is a pointer type + // - PointeeType : returns the type to which T points if T is a pointer + // type, NullType otherwise + // - isReference : returns true if T is a reference type + // - ReferredType : returns the type to which T refers if T is a reference + // type, NullType otherwise + // - isMemberPointer : returns true if T is a pointer to member type + // - isStdUnsignedInt: returns true if T is a standard unsigned integral type + // - isStdSignedInt : returns true if T is a standard signed integral type + // - isStdIntegral : returns true if T is a standard integral type + // - isStdFloat : returns true if T is a standard floating-point type + // - isStdArith : returns true if T is a standard arithmetic type + // - isStdFundamental: returns true if T is a standard fundamental type + // - isUnsignedInt : returns true if T is a unsigned integral type + // - isSignedInt : returns true if T is a signed integral type + // - isIntegral : returns true if T is a integral type + // - isFloat : returns true if T is a floating-point type + // - isArith : returns true if T is a arithmetic type + // - isFundamental : returns true if T is a fundamental type + // - ParameterType : returns the optimal type to be used as a parameter for + // functions that take Ts + // - isConst : returns true if T is a const-qualified type + // - NonConstType : Type with removed 'const' qualifier from T, if any + // - isVolatile : returns true if T is a volatile-qualified type + // - NonVolatileType : Type with removed 'volatile' qualifier from T, if any + // - UnqualifiedType : Type with removed 'const' and 'volatile' qualifiers from + // T, if any + // - ParameterType : returns the optimal type to be used as a parameter + // for functions that take 'const T's + // + //////////////////////////////////////////////////////////////////////////////// template class TypeTraits { private: - - template struct ReferenceTraits { + template + struct ReferenceTraits { enum { result = false }; typedef U ReferredType; }; - template struct ReferenceTraits { + template + struct ReferenceTraits { enum { result = true }; typedef U ReferredType; }; - template struct PointerTraits { + template + struct PointerTraits { enum { result = false }; typedef NullType PointeeType; }; - template struct PointerTraits { + template + struct PointerTraits { enum { result = true }; typedef U PointeeType; }; - template struct PointerTraits { + template + struct PointerTraits { enum { result = true }; typedef U PointeeType; }; - template struct PToMTraits { + template + struct PToMTraits { enum { result = false }; }; - template struct PToMTraits { + template + struct PToMTraits { enum { result = true }; }; - template struct PToMTraits { + template + struct PToMTraits { enum { result = true }; }; - template struct UnConst { + template + struct UnConst { typedef U Result; enum { isConst = 0 }; }; - template struct UnConst { + template + struct UnConst { typedef U Result; enum { isConst = 1 }; }; - template struct UnConst { + template + struct UnConst { typedef U& Result; enum { isConst = 1 }; }; - template struct UnVolatile { + template + struct UnVolatile { typedef U Result; enum { isVolatile = 0 }; }; - template struct UnVolatile { + template + struct UnVolatile { typedef U Result; enum { isVolatile = 1 }; }; - template struct UnVolatile { + template + struct UnVolatile { typedef U& Result; enum { isVolatile = 1 }; }; @@ -858,30 +909,13 @@ namespace tp { enum { isConst = UnConst::isConst }; enum { isVolatile = UnVolatile::isVolatile }; enum { isReference = ReferenceTraits::result }; - enum { isMemberPointer = PToMTraits::ReferredType >::result }; - enum { isPointer = PointerTraits::ReferredType >::result }; + enum { isMemberPointer = PToMTraits::ReferredType>::result }; + enum { isPointer = PointerTraits::ReferredType>::result }; - enum { - isStdUnsignedInt = TL::IndexOf::value >= 0 || - TL::IndexOf::ReferredType>::value >= 0 - }; - enum { - isStdSignedInt = TL::IndexOf::value >= 0 || - TL::IndexOf::ReferredType>::value >= 0 - }; - enum { - isStdIntegral = isStdUnsignedInt || isStdSignedInt || - TL::IndexOf::value >= 0 || - TL::IndexOf::ReferredType>::value >= 0 - }; - enum { - isStdFloat = TL::IndexOf::value >= 0 || - TL::IndexOf::ReferredType>::value >= 0 - }; + enum { isStdUnsignedInt = TL::IndexOf::value >= 0 || TL::IndexOf::ReferredType>::value >= 0 }; + enum { isStdSignedInt = TL::IndexOf::value >= 0 || TL::IndexOf::ReferredType>::value >= 0 }; + enum { isStdIntegral = isStdUnsignedInt || isStdSignedInt || TL::IndexOf::value >= 0 || TL::IndexOf::ReferredType>::value >= 0 }; + enum { isStdFloat = TL::IndexOf::value >= 0 || TL::IndexOf::ReferredType>::value >= 0 }; enum { isStdArith = isStdIntegral || isStdFloat }; enum { isStdFundamental = isStdArith || isStdFloat || Conversion::sameType }; @@ -898,5 +932,5 @@ namespace tp { } #ifdef _MSC_VER -#pragma warning( pop ) +#pragma warning(pop) #endif // _MSC_VER \ No newline at end of file diff --git a/Modules/tests/TestArchiver.cpp b/Modules/tests/TestArchiver.cpp index 8cfcd6e..3ed862d 100644 --- a/Modules/tests/TestArchiver.cpp +++ b/Modules/tests/TestArchiver.cpp @@ -8,204 +8,204 @@ using namespace tp; bool sFailed = false; struct Undef { - char character1 = 'a'; - bool boolean = true; - ualni integer = 321; - char character2 = 'a'; + char character1 = 'a'; + bool boolean = true; + ualni integer = 321; + char character2 = 'a'; - void change() { - character1++; - character2--; - integer++; - boolean = !boolean; - } + void change() { + character1++; + character2--; + integer++; + boolean = !boolean; + } - [[nodiscard]] bool operator!=(const Undef& in) const { - if (character1 != in.character1) { - return true; - } - if (character2 != in.character2) { - return true; - } - if (integer != in.integer) { - return true; - } - if (boolean != in.boolean) { - return true; - } - return false; - } + [[nodiscard]] bool operator!=(const Undef& in) const { + if (character1 != in.character1) { + return true; + } + if (character2 != in.character2) { + return true; + } + if (integer != in.integer) { + return true; + } + if (boolean != in.boolean) { + return true; + } + return false; + } }; struct SimpleArchive { - char character = 'a'; - ualni integer = 123; - bool boolean = true; - Undef undef; + char character = 'a'; + ualni integer = 123; + bool boolean = true; + Undef undef; - template - void archive(tArchiver& ar) { - ar % character; - ar % integer; - ar % boolean; - ar % undef; - } + template + void archive(tArchiver& ar) { + ar % character; + ar % integer; + ar % boolean; + ar % undef; + } - void change() { - character++; - integer++; - boolean = !boolean; - undef.change(); - } + void change() { + character++; + integer++; + boolean = !boolean; + undef.change(); + } - [[nodiscard]] bool operator!=(const SimpleArchive& in) const { - if (character != in.character) { - return true; - } - if (integer != in.integer) { - return true; - } - if (boolean != in.boolean) { - return true; - } - if (undef != in.undef) { - return true; - } - return false; - } + [[nodiscard]] bool operator!=(const SimpleArchive& in) const { + if (character != in.character) { + return true; + } + if (integer != in.integer) { + return true; + } + if (boolean != in.boolean) { + return true; + } + if (undef != in.undef) { + return true; + } + return false; + } }; struct Simple { - char character = 'a'; - ualni integer = 123; - bool boolean = true; - Undef undef; + char character = 'a'; + ualni integer = 123; + bool boolean = true; + Undef undef; - template - void archiveRead(tArchiver& ar) { - ar >> character; - ar >> integer; - ar >> boolean; - ar >> undef; - } + template + void archiveRead(tArchiver& ar) { + ar >> character; + ar >> integer; + ar >> boolean; + ar >> undef; + } - template - void archiveWrite(tArchiver& ar) const { - ar << character; - ar << integer; - ar << boolean; - ar << undef; - } + template + void archiveWrite(tArchiver& ar) const { + ar << character; + ar << integer; + ar << boolean; + ar << undef; + } - void change() { - character++; - integer++; - boolean = !boolean; - undef.change(); - } + void change() { + character++; + integer++; + boolean = !boolean; + undef.change(); + } - [[nodiscard]] bool operator!=(const Simple& in) const { - if (character != in.character) { - return true; - } - if (integer != in.integer) { - return true; - } - if (boolean != in.boolean) { - return true; - } - if (undef != in.undef) { - return true; - } - return false; - } + [[nodiscard]] bool operator!=(const Simple& in) const { + if (character != in.character) { + return true; + } + if (integer != in.integer) { + return true; + } + if (boolean != in.boolean) { + return true; + } + if (undef != in.undef) { + return true; + } + return false; + } }; template struct Set { - tType buff[10]; - ualni len = 5; + tType buff[10]; + ualni len = 5; - template - void archiveRead(tArchiver& ar) { - ar >> len; - for (auto i = 0; i < len; i++) { - ar >> buff[i]; - } - } + template + void archiveRead(tArchiver& ar) { + ar >> len; + for (auto i = 0; i < len; i++) { + ar >> buff[i]; + } + } - template - void archiveWrite(tArchiver& ar) const { - ar << len; - for (auto i = 0; i < len; i++) { - ar << buff[i]; - } - } + template + void archiveWrite(tArchiver& ar) const { + ar << len; + for (auto i = 0; i < len; i++) { + ar << buff[i]; + } + } - void change() { - len = 2; - for (auto i = 0; i < len; i++) { - buff[i].change(); - } - } + void change() { + len = 2; + for (auto i = 0; i < len; i++) { + buff[i].change(); + } + } - [[nodiscard]] bool operator!=(const Set& in) const { - for (auto i = 0; i < len; i++) { - if (buff[i] != in.buff[i]) { - return true; - } - } + [[nodiscard]] bool operator!=(const Set& in) const { + for (auto i = 0; i < len; i++) { + if (buff[i] != in.buff[i]) { + return true; + } + } - if (len != in.len) { - return true; - } - return false; - } + if (len != in.len) { + return true; + } + return false; + } }; template struct ComplexCart { - Undef undef; - Set set; + Undef undef; + Set set; - template - void archive(tArchiver& ar) { - ar % set; - ar % undef; - } + template + void archive(tArchiver& ar) { + ar % set; + ar % undef; + } - void change() { - undef.change(); - set.change(); - } + void change() { + undef.change(); + set.change(); + } - [[nodiscard]] bool operator!=(const ComplexCart& in) const { return undef != in.undef || set != in.set; } + [[nodiscard]] bool operator!=(const ComplexCart& in) const { return undef != in.undef || set != in.set; } }; template void test() { - constexpr auto size = 1024; + constexpr auto size = 1024; - const tType val; - tType res; + const tType val; + tType res; - res.change(); + res.change(); - ArchiverExample write; - ArchiverExample read; + ArchiverExample write; + ArchiverExample read; - write % val; + write % val; - for (auto i = 0; i < size; i++) { - read.mBuff[i] = write.mBuff[i]; - } + for (auto i = 0; i < size; i++) { + read.mBuff[i] = write.mBuff[i]; + } - read % res; + read % res; - if (val != res) { - printf("Test %s Failed\n", typeid(tType).name()); - sFailed = true; - } + if (val != res) { + printf("Test %s Failed\n", typeid(tType).name()); + sFailed = true; + } } template @@ -215,16 +215,16 @@ template struct HasArchive()().archive(DeclareValue()()))>> : TrueType {}; void testArchiver() { - printf("has archive method - %i\n", HasArchive>::value); - printf("has archive method - %i\n", ArchiverExample<10, false>::HasFunc::Archive::value); - printf("has archive method - %i\n", ArchiverExample<10, false>::HasFunc::Archive::value); + printf("has archive method - %i\n", HasArchive>::value); + printf("has archive method - %i\n", ArchiverExample<10, false>::HasFunc::Archive::value); + printf("has archive method - %i\n", ArchiverExample<10, false>::HasFunc::Archive::value); - test(); - test(); - test>(); - test>(); + test(); + test(); + test>(); + test>(); - if (sFailed) { - exit(1); - } + if (sFailed) { + exit(1); + } } diff --git a/Modules/tests/Tests.cpp b/Modules/tests/Tests.cpp index 474d6d7..b7fbf49 100644 --- a/Modules/tests/Tests.cpp +++ b/Modules/tests/Tests.cpp @@ -1,24 +1,24 @@ - -#include "Module.hpp" - -void testArchiver(); - -int main() { - tp::ModuleManifest* ModuleDependencies[] = { &tp::gModuleBase, nullptr }; - tp::ModuleManifest TestModule("Test", nullptr, nullptr, ModuleDependencies); - - if (!TestModule.initialize()) { - return 1; - } - - ASSERT(tp::gEnvironment.mWidth == tp::Environment::ArchWidth::X64); - - ASSERT(tp::max(2, 1) == 2) - ASSERT(tp::max(-1, 0) == 0) - ASSERT(tp::max(0, -1) == 0) - ASSERT(tp::min(0, -1) == -1) - - testArchiver(); - - TestModule.deinitialize(); + +#include "Module.hpp" + +void testArchiver(); + +int main() { + tp::ModuleManifest* ModuleDependencies[] = { &tp::gModuleBase, nullptr }; + tp::ModuleManifest TestModule("Test", nullptr, nullptr, ModuleDependencies); + + if (!TestModule.initialize()) { + return 1; + } + + ASSERT(tp::gEnvironment.mWidth == tp::Environment::ArchWidth::X64); + + ASSERT(tp::max(2, 1) == 2) + ASSERT(tp::max(-1, 0) == 0) + ASSERT(tp::max(0, -1) == 0) + ASSERT(tp::min(0, -1) == -1) + + testArchiver(); + + TestModule.deinitialize(); } \ No newline at end of file diff --git a/Objects/applications/Compiler.cpp b/Objects/applications/Compiler.cpp index 93ef9c8..1700479 100644 --- a/Objects/applications/Compiler.cpp +++ b/Objects/applications/Compiler.cpp @@ -1,49 +1,48 @@ - -#include "Compiler/Compiler.h" - -#include "primitives/primitives.h" -#include "MethodObject/MethodObject.h" -#include "log.h" - -using namespace osc; -using namespace tp; -using namespace obj; - -int main(int argc, char* argv[]) { - - tp::alloc_init(); - string::Initialize(); - Logger::init(); - - objects_init(); - primitives_define_types(); - MethodObject::Initialize(); - - { - Compiler compiler; - - tp::string script; - - RelAssert(argc == 2 && "Invalid Arguments"); - - script.loadFile(argv[1]); - - compiler.compile(script); - - GLog->write("oscc : compilation finished", 1); - } - - try { - MethodObject::UnInitialize(); - objects_finalize(); - primitives_uninitialize(); - - Logger::deinit(); - string::UnInitialize(); - tp::alloc_uninit(); - - } - catch (...) { - tp::terminate(); - } + +#include "Compiler/Compiler.h" + +#include "MethodObject/MethodObject.h" +#include "log.h" +#include "primitives/primitives.h" + +using namespace osc; +using namespace tp; +using namespace obj; + +int main(int argc, char* argv[]) { + + tp::alloc_init(); + string::Initialize(); + Logger::init(); + + objects_init(); + primitives_define_types(); + MethodObject::Initialize(); + + { + Compiler compiler; + + tp::string script; + + RelAssert(argc == 2 && "Invalid Arguments"); + + script.loadFile(argv[1]); + + compiler.compile(script); + + GLog->write("oscc : compilation finished", 1); + } + + try { + MethodObject::UnInitialize(); + objects_finalize(); + primitives_uninitialize(); + + Logger::deinit(); + string::UnInitialize(); + tp::alloc_uninit(); + + } catch (...) { + tp::terminate(); + } } \ No newline at end of file diff --git a/Objects/applications/GUI.cpp b/Objects/applications/GUI.cpp index 3b6cdc0..1ece18d 100644 --- a/Objects/applications/GUI.cpp +++ b/Objects/applications/GUI.cpp @@ -20,9 +20,7 @@ namespace ImGui { bool ishovered = false; tp::Vec2F p1; tp::Vec2F p2; - operator bool() { - return opened; - } + operator bool() { return opened; } }; PopupData HoverPopupBegin(const char* id, tp::Vec2F size, tp::Vec2F pos = tp::Vec2F(-1), int flags = 0); @@ -40,8 +38,7 @@ ImGui::PopupData ImGui::HoverPopupBegin(const char* str_id, tp::Vec2F size, tp:: if (pos_p == tp::Vec2F(-1)) { pos = GImGui->CurrentWindow->DC.CursorPos; - } - else { + } else { pos.x = pos_p.x; pos.y = pos_p.y; } @@ -62,7 +59,6 @@ ImGui::PopupData ImGui::HoverPopupBegin(const char* str_id, tp::Vec2F size, tp:: out.p1 = { pos.x, pos.y }; out.p2 = out.p1; out.p2.x += ImGui::GetWindowWidth(); - } return out; } @@ -87,7 +83,6 @@ void ImGui::HoverPopupEnd(ImGui::PopupData& in) { EndPopup(); } - obj::ObjectsGUI::~ObjectsGUI() { if (mClipboard) { obj::NDO->destroy(mClipboard); @@ -109,9 +104,7 @@ void obj::ObjectsGUI::setClipboard(obj::Object* obj) { } } -obj::Object* obj::ObjectsGUI::getClipboard() { - return mClipboard; -} +obj::Object* obj::ObjectsGUI::getClipboard() { return mClipboard; } obj::Object* imgui_object_create_menu(obj::TypeGroups* type_group = NULL) { @@ -134,8 +127,7 @@ obj::Object* imgui_object_create_menu(obj::TypeGroups* type_group = NULL) { if (ImGui::Button((childo->key).read(), { 100, 0 })) { if (childo->key == "null") { newo = NDO_NULL; - } - else { + } else { newo = obj::NDO->create(childo->key); } } @@ -144,9 +136,7 @@ obj::Object* imgui_object_create_menu(obj::TypeGroups* type_group = NULL) { return newo; } -obj::ObjectsGUI::ObjectsGUI() { - assert(obj::NDO && "Objects library is not initialized"); -} +obj::ObjectsGUI::ObjectsGUI() { assert(obj::NDO && "Objects library is not initialized"); } void obj::ObjectsGUI::cd(obj::Object* child, tp::String name) { mActive = child; @@ -178,8 +168,7 @@ void obj::ObjectsGUI::preview(obj::Object* obj) { if (link_lookup.presents(tp::alni(link_iter))) { no_link_preview = true; - } - else { + } else { link_lookup.put(tp::alni(link_iter), 0); } no_link_preview |= max_depth < depth_count; @@ -190,22 +179,18 @@ void obj::ObjectsGUI::preview(obj::Object* obj) { ImGui::Text("=> "); ImGui::SameLine(); preview(linko->getLink()); - } - else { + } else { ImGui::Text("Max preview depth exceeded"); } - } - else { + } else { ImGui::Text("Link Is Null"); } - } - else if (NDO_CAST(obj::IntObject, obj)) { + } else if (NDO_CAST(obj::IntObject, obj)) { tp::alni& val = NDO_CAST(obj::IntObject, obj)->val; int gui_val = int(val); ImGui::InputInt(" ", &gui_val); val = tp::alni(gui_val); - } - else if (NDO_CAST(obj::StringObject, obj)) { + } else if (NDO_CAST(obj::StringObject, obj)) { NDO_CASTV(obj::StringObject, obj, stringo); static char val[2048] = { " " }; if (stringo->val != val) { @@ -216,25 +201,21 @@ void obj::ObjectsGUI::preview(obj::Object* obj) { if (stringo->val != val) { stringo->val = val; } - } - else if (NDO_CAST(obj::BoolObject, obj)) { - boolView((obj::BoolObject*)obj); - } - else if (NDO_CAST(obj::FloatObject, obj)) { + } else if (NDO_CAST(obj::BoolObject, obj)) { + boolView((obj::BoolObject*) obj); + } else if (NDO_CAST(obj::FloatObject, obj)) { tp::alnf& val = NDO_CAST(obj::FloatObject, obj)->val; auto gui_val = float(val); ImGui::InputFloat(" ", &gui_val); val = tp::alnf(gui_val); - } - else if (NDO_CAST(obj::EnumObject, obj)) { - enumView((obj::EnumObject*)obj); - } - else if (NDO_CAST(obj::ColorObject, obj)) { - colorView((obj::ColorObject*)obj); - } - else { - ImGui::Text(obj->type->name); ImGui::SameLine(); + } else if (NDO_CAST(obj::EnumObject, obj)) { + enumView((obj::EnumObject*) obj); + } else if (NDO_CAST(obj::ColorObject, obj)) { + colorView((obj::ColorObject*) obj); + } else { + ImGui::Text(obj->type->name); + ImGui::SameLine(); ImGui::Text(" (No Preview) "); } } @@ -261,12 +242,15 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::interpreterView(obj::Interpreter } // running state - BeginChild("dockable"); { + BeginChild("dockable"); + { auto id = ImGui::GetCurrentWindow()->ID; DockSpace(id); - } EndChild(); + } + EndChild(); - Begin("ByteCodeView"); { + Begin("ByteCodeView"); + { if (Button("Step")) { interp.stepBytecode(); @@ -299,21 +283,21 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::interpreterView(obj::Interpreter const auto bytecode = interp.mCallStack.getBytecode(); tp::halni idx = 0; - for (auto ip = 0; ip < bytecode->mInstructions.size(); ) { + for (auto ip = 0; ip < bytecode->mInstructions.size();) { auto opcode = bytecode->mInstructions[ip]; auto info = obj::gOpcodeInfos.fetch(opcode); PushID(info.name); - TextColored(ImVec4(1.f, 1.f, 1.f, 0.5f), "%i", idx); SameLine(); + TextColored(ImVec4(1.f, 1.f, 1.f, 0.5f), "%i", idx); + SameLine(); if (bytecode->mInstructionIdx == ip) { TextColored(ImVec4(1.f, 0.5f, 0.5f, 1.f), info.name); - } - else { + } else { Text(info.name); } // INFO - auto hd = HoverPopupBegin(tp::String((tp::alni)ip).read(), { 400, 250 }); + auto hd = HoverPopupBegin(tp::String((tp::alni) ip).read(), { 400, 250 }); if (hd) { Text(info.desc); if (info.operands.len) { @@ -339,43 +323,45 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::interpreterView(obj::Interpreter } EndChild(); - } End(); + } + End(); - Begin("SourceCodeView"); { - stringView(interp.mCallStack.mStack.last().mMethod->mScript->mReadable); - } End(); + Begin("SourceCodeView"); + { stringView(interp.mCallStack.mStack.last().mMethod->mScript->mReadable); } + End(); - Begin("OperandStack"); { + Begin("OperandStack"); + { if (!interp.mOperandsStack.mIdx) { Text("No Operands"); } for (auto i = 0; i < interp.mOperandsStack.mIdx; i++) { auto operand = interp.mOperandsStack.mBuff[i]; - tp::alni operand_val = (tp::alni)operand; + tp::alni operand_val = (tp::alni) operand; if (operand_val == NULL) { Text("NULL"); - } - else if (tp::uint2(operand_val) == NULL) { + } else if (tp::uint2(operand_val) == NULL) { Text("2 BYTE VAL : %i", tp::uint2(operand_val)); - } - else { + } else { if (Selectable(operand->type->name, false, 0, ImVec2(100, 0))) { End(); return { operand, "operand" }; } SameLine(); - PushID((tp::alni)operand); + PushID((tp::alni) operand); preview(operand); PopID(); } } - } End(); + } + End(); - Begin("ScopeStack"); { + Begin("ScopeStack"); + { for (auto i = 0; i < interp.mScopeStack.mIdx; i++) { - if (TreeNode(tp::String((tp::alni)i).read())) { + if (TreeNode(tp::String((tp::alni) i).read())) { auto& scope = interp.mScopeStack.mBuff[i]; @@ -412,9 +398,11 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::interpreterView(obj::Interpreter TreePop(); } } - } End(); + } + End(); - Begin("CallStack"); { + Begin("CallStack"); + { for (auto i = 0; i < interp.mCallStack.mStack.size(); i++) { auto method = interp.mCallStack.mStack[i].mMethod; PushID(i); @@ -425,9 +413,11 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::interpreterView(obj::Interpreter } PopID(); } - } End(); + } + End(); - Begin("ConstPool"); { + Begin("ConstPool"); + { auto bc = interp.mCallStack.getBytecode(); tp::alni idx = 0; for (auto const_obj : bc->mConstants) { @@ -435,14 +425,15 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::interpreterView(obj::Interpreter if (Button(const_obj.data()->type->name)) { End(); PopID(); - return {const_obj.data(), tp::String(idx)}; + return { const_obj.data(), tp::String(idx) }; } SameLine(); preview(const_obj.data()); PopID(); idx++; } - } End(); + } + End(); return {}; } @@ -452,7 +443,6 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::colorView(obj::ColorObject* in) return {}; } - obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::enumView(obj::EnumObject* obj) { if (!obj->entries) { @@ -504,8 +494,7 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::linkoView(obj::LinkObject* obj) if (ImGui::Selectable("View")) { return { obj->getLink(), "adress" }; } - } - else { + } else { ImGui::Text("Link Is Null"); } @@ -524,10 +513,11 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::linkoView(obj::LinkObject* obj) } obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::intoView(obj::IntObject* obj) { - ImGui::Text("Int Value: "); ImGui::SameLine(); - int val = (int)obj->val; + ImGui::Text("Int Value: "); + ImGui::SameLine(); + int val = (int) obj->val; ImGui::InputInt(" ", &val); - obj->val = (tp::alni)val; + obj->val = (tp::alni) val; return {}; } @@ -581,20 +571,18 @@ void obj::ObjectsGUI::dictViewEdit(obj::DictObject* dict, tp::String key, obj::O if (key.size() > 100) { ImGui::Text("name is too large"); - } - else { + } else { if (mLastNameEditObject != obj) { tp::memCopy(mNameEdit, key.read(), key.size() + 1); mLastNameEditObject = obj; } - if (ImGui::InputTextEx(" ", "new name", mNameEdit, 100, { 140 , 30 }, ImGuiInputTextFlags_EnterReturnsTrue)) { + if (ImGui::InputTextEx(" ", "new name", mNameEdit, 100, { 140, 30 }, ImGuiInputTextFlags_EnterReturnsTrue)) { auto idx = dict->presents(mNameEdit); if (bool(idx)) { - //Notify("Object with such name Already Exists"); - } - else { + // Notify("Object with such name Already Exists"); + } else { obj::NDO->refinc(obj); dict->remove(key); auto id = tp::String(mNameEdit); @@ -620,7 +608,8 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::dictView(obj::DictObject* obj) { bool popup = false; auto table_flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable; - ImGui::BeginChild("frame", { 0, 0 }, 0, ImGuiWindowFlags_NoBackground); { + ImGui::BeginChild("frame", { 0, 0 }, 0, ImGuiWindowFlags_NoBackground); + { if (!obj->getItems().size()) { ImGui::Text("Dictinary Is Empty. "); } @@ -629,27 +618,27 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::dictView(obj::DictObject* obj) { ImGui::TableSetupColumn("name"); ImGui::TableSetupColumn("info"); for (auto childo : obj->getItems()) { - + ImGui::TableNextRow(0, 30); ImGui::TableSetColumnIndex(0); if (ImGui::Selectable(childo->key.read())) { ImGui::EndTable(); ImGui::EndChild(); - return { childo->val, { tp::String(childo->val->type->name) + tp::String(" ") + childo->key } }; + return { childo->val, { tp::String(childo->val->type->name) + tp::String(" ") + childo->key } }; } - + dictViewEdit(obj, childo->key, childo->val, popup); - + ImGui::TableSetColumnIndex(1); - ImGui::PushID((int)childo->key.read()[0]); + ImGui::PushID((int) childo->key.read()[0]); preview(childo->val); ImGui::PopID(); - } ImGui::EndTable(); } - } ImGui::EndChild(); + } + ImGui::EndChild(); if (!popup) { dictViewDrawCreate(obj); @@ -678,7 +667,7 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::listView(obj::ListObject* obj) { ImGui::TableSetColumnIndex(0); if (ImGui::Selectable(tp::String(idx).read())) { - out = ViewStackNode(childo.data(), { tp::String(childo->type->name) + tp::String("at") + tp::String(idx) } ); + out = ViewStackNode(childo.data(), { tp::String(childo->type->name) + tp::String("at") + tp::String(idx) }); break; } @@ -718,7 +707,7 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::listView(obj::ListObject* obj) { ImGui::TableSetColumnIndex(1); - ImGui::PushID((int)idx); + ImGui::PushID((int) idx); preview(childo.data()); ImGui::PopID(); @@ -758,7 +747,7 @@ void drawStrView(tp::String& in) { } ImGui::BeginChild("str_edit"); - ImGui::InputTextMultiline(" ", val, 2048, { ImGui::GetWindowWidth() , ImGui::GetWindowHeight() }); + ImGui::InputTextMultiline(" ", val, 2048, { ImGui::GetWindowWidth(), ImGui::GetWindowHeight() }); ImGui::EndChild(); if (in != val) { @@ -811,16 +800,15 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::classView(obj::ClassObject* self ImGui::EndTable(); ImGui::TreePop(); ImGui::EndChild(); - return { childo->val, { tp::String(childo->val->type->name) + childo->key } }; + return { childo->val, { tp::String(childo->val->type->name) + childo->key } }; } dictViewEdit(dict, childo->key, childo->val, popup); ImGui::TableSetColumnIndex(1); - ImGui::PushID((int)idx); + ImGui::PushID((int) idx); preview(childo->val); ImGui::PopID(); - } ImGui::EndTable(); @@ -829,13 +817,13 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::classView(obj::ClassObject* self ImGui::TreePop(); } - if (n_methods && ImGui::TreeNodeBehavior(window->GetID("Methods"), tree_flags, "Methods", 0) ) { + if (n_methods && ImGui::TreeNodeBehavior(window->GetID("Methods"), tree_flags, "Methods", 0)) { for (auto childo : dict->getItems()) { if (childo->val->type == &obj::MethodObject::TypeData) { if (ImGui::Selectable(childo->key.read())) { ImGui::TreePop(); ImGui::EndChild(); - return { childo->val, { tp::String(childo->val->type->name) + childo->key } }; + return { childo->val, { tp::String(childo->val->type->name) + childo->key } }; } dictViewEdit(dict, childo->key, childo->val, popup); } @@ -865,8 +853,7 @@ obj::ObjectsGUI::ViewStackNode obj::ObjectsGUI::methodView(obj::MethodObject* in interp.execAll(in); } - } - else { + } else { if (ImGui::Button("Compile")) { in->compile(); } @@ -897,13 +884,14 @@ void obj::ObjectsGUI::explorer() { tp::alni idx = 0; for (auto childo = rev_path.last(); childo; childo = childo->prev) { - ImGui::PushID((int)idx); + ImGui::PushID((int) idx); bool go_back = false; if (childo == rev_path.last()) { - go_back = ImGui::Button(childo->data->id.read()); ImGui::SameLine(); - } - else { - go_back = ImGui::Button((childo->data->id).read()); ImGui::SameLine(); + go_back = ImGui::Button(childo->data->id.read()); + ImGui::SameLine(); + } else { + go_back = ImGui::Button((childo->data->id).read()); + ImGui::SameLine(); } ImGui::PopID(); @@ -919,7 +907,7 @@ void obj::ObjectsGUI::explorer() { if (ImGui::Selectable("Instantiate ")) { setClipboard(obj::NDO->instatiate(curretn_object)); - //Notify("Object copied to clipboard"); + // Notify("Object copied to clipboard"); } ImGui::Separator(); @@ -929,22 +917,22 @@ void obj::ObjectsGUI::explorer() { ImGui::InputTextEx(" ", "save path", path_str, 100, { 100, 30 }, 0); bool save_object = ImGui::Button("Save Object"); - ImGui::SameLine(); ImGui::Checkbox("Compressed", &compressed); + ImGui::SameLine(); + ImGui::Checkbox("Compressed", &compressed); bool load_object = ImGui::Button("Load Object"); if (save_object) { obj::NDO->save(curretn_object, path_str, compressed); - //Notify("Object saved"); + // Notify("Object saved"); } if (load_object) { obj::Object* loadedo = obj::NDO->load(path_str); if (loadedo) { setClipboard(loadedo); - //Notify("Object copied to clipboard"); - } - else { - //Notify("Can't load Object"); + // Notify("Object copied to clipboard"); + } else { + // Notify("Can't load Object"); } } @@ -968,45 +956,32 @@ void obj::ObjectsGUI::explorer() { ViewStackNode new_active; if (NDO_CAST(obj::NullObject, mActive)) { - new_active = nullView((obj::NullObject*)mActive); - } - else if (NDO_CAST(obj::LinkObject, mActive)) { - new_active = linkoView((obj::LinkObject*)mActive); - } - else if (NDO_CAST(obj::IntObject, mActive)) { - new_active = intoView((obj::IntObject*)mActive); - } - else if (NDO_CAST(obj::StringObject, mActive)) { - new_active = stringView((obj::StringObject*)mActive); - } - else if (NDO_CAST(obj::ListObject, mActive)) { - new_active = listView((obj::ListObject*)mActive); - } - else if (NDO_CAST(obj::DictObject, mActive)) { - new_active = dictView((obj::DictObject*)mActive); - } - else if (NDO_CAST(obj::InterpreterObject, mActive)) { - new_active = interpreterView((obj::InterpreterObject*)mActive); - } - else if (NDO_CAST(obj::ClassObject, mActive)) { - new_active = classView((obj::ClassObject*)mActive); - } - else if (NDO_CAST(obj::BoolObject, mActive)) { - new_active = boolView((obj::BoolObject*)mActive); - } - else if (NDO_CAST(obj::FloatObject, mActive)) { - new_active = floatView((obj::FloatObject*)mActive); - } - else if (NDO_CAST(obj::EnumObject, mActive)) { - new_active = enumView((obj::EnumObject*)mActive); - } - else if (NDO_CAST(obj::MethodObject, mActive)) { - new_active = methodView((obj::MethodObject*)mActive); - } - else if (NDO_CAST(obj::ColorObject, mActive)) { - new_active = colorView((obj::ColorObject*)mActive); - } - else { + new_active = nullView((obj::NullObject*) mActive); + } else if (NDO_CAST(obj::LinkObject, mActive)) { + new_active = linkoView((obj::LinkObject*) mActive); + } else if (NDO_CAST(obj::IntObject, mActive)) { + new_active = intoView((obj::IntObject*) mActive); + } else if (NDO_CAST(obj::StringObject, mActive)) { + new_active = stringView((obj::StringObject*) mActive); + } else if (NDO_CAST(obj::ListObject, mActive)) { + new_active = listView((obj::ListObject*) mActive); + } else if (NDO_CAST(obj::DictObject, mActive)) { + new_active = dictView((obj::DictObject*) mActive); + } else if (NDO_CAST(obj::InterpreterObject, mActive)) { + new_active = interpreterView((obj::InterpreterObject*) mActive); + } else if (NDO_CAST(obj::ClassObject, mActive)) { + new_active = classView((obj::ClassObject*) mActive); + } else if (NDO_CAST(obj::BoolObject, mActive)) { + new_active = boolView((obj::BoolObject*) mActive); + } else if (NDO_CAST(obj::FloatObject, mActive)) { + new_active = floatView((obj::FloatObject*) mActive); + } else if (NDO_CAST(obj::EnumObject, mActive)) { + new_active = enumView((obj::EnumObject*) mActive); + } else if (NDO_CAST(obj::MethodObject, mActive)) { + new_active = methodView((obj::MethodObject*) mActive); + } else if (NDO_CAST(obj::ColorObject, mActive)) { + new_active = colorView((obj::ColorObject*) mActive); + } else { ImGui::Text("Preview is Unavaliable"); } @@ -1028,8 +1003,7 @@ void obj::ObjectsGUI::properties(const obj::ObjectType* type, bool top_of_tree_v if (ImGui::TreeNode("Description ")) { if (type->description) { ImGui::Text(type->description); - } - else { + } else { ImGui::Text("Description is not given"); } ImGui::TreePop(); @@ -1052,7 +1026,7 @@ void obj::ObjectsGUI::properties(const obj::ObjectType* type, bool top_of_tree_v ImGui::TreePop(); } - //if (ImGui::TreeNode("Full Type Hierarchy")) { + // if (ImGui::TreeNode("Full Type Hierarchy")) { ImGui::Text("RAM : "); ImGui::Indent(); @@ -1067,16 +1041,15 @@ void obj::ObjectsGUI::properties(const obj::ObjectType* type, bool top_of_tree_v ImGui::Text("With Object Links : %i bytes", obj::NDO->objsize_file_recursive(mActive)); ImGui::Unindent(); - //ImGui::TreePop(); - //} + // ImGui::TreePop(); + //} ImGui::TreePop(); } if (ImGui::TreeNode("Base Type")) { if (type->base) { properties(type->base, false); - } - else { + } else { ImGui::Text("No base type"); } ImGui::TreePop(); @@ -1099,8 +1072,7 @@ void obj::ObjectsGUI::draw() { } ImGui::End(); - } - else { + } else { ImGui::Text("ViewStack is Empty"); } diff --git a/Objects/applications/GUIEntry.cpp b/Objects/applications/GUIEntry.cpp index 3323b16..b96d0b5 100644 --- a/Objects/applications/GUIEntry.cpp +++ b/Objects/applications/GUIEntry.cpp @@ -28,9 +28,7 @@ public: } } - ~GUIWindow() { - Window::destroyWindow(window); - } + ~GUIWindow() { Window::destroyWindow(window); } }; int main() { diff --git a/Objects/applications/Interpreter.cpp b/Objects/applications/Interpreter.cpp index d9b38da..eb38446 100644 --- a/Objects/applications/Interpreter.cpp +++ b/Objects/applications/Interpreter.cpp @@ -1,58 +1,58 @@ - - -#include "MethodObject/methodobject.h" -#include "primitives/primitives.h" - -#include "Interpreter/Interpreter.h" - -#include "log.h" - -using namespace osc; -using namespace tp; -using namespace obj; - -int main(int argc, char* argv[]) { - tp::alloc_init(); - string::Initialize(); - Logger::init(); - - objects_init(); - primitives_define_types(); - MethodObject::Initialize(); - - { - time_ms load_start = get_time(); - RelAssert(argc == 2 && "Invalid Arguments"); - auto obj = NDO->load(argv[1]); - RelAssert(obj && "Failed to Load the File"); - RelAssert(obj->type == &MethodObject::TypeData && "Innvalid file content"); - - Interpreter interp; - NDO_CASTV(MethodObject, obj, method); - - RelAssert(method->mScript && "Innvalid file content"); - time_ms load_end = get_time(); - - GLog->write("\noscvm - execution started\n"); - time_ms exec_start = get_time(); - interp.exec(&method->mScript->mBytecode); - time_ms exec_end = get_time(); - - auto exec_time = (exec_end - exec_start); - auto load_time = (load_end - load_start); - GLog->write(sfmt("\noscvm - execution finished (Load : %f Exec : %f)", load_time, exec_time)); - } - - try { - MethodObject::UnInitialize(); - objects_finalize(); - primitives_uninitialize(); - - Logger::deinit(); - string::UnInitialize(); - tp::alloc_uninit(); - - } catch (...) { - tp::terminate(); - } + + +#include "MethodObject/methodobject.h" +#include "primitives/primitives.h" + +#include "Interpreter/Interpreter.h" + +#include "log.h" + +using namespace osc; +using namespace tp; +using namespace obj; + +int main(int argc, char* argv[]) { + tp::alloc_init(); + string::Initialize(); + Logger::init(); + + objects_init(); + primitives_define_types(); + MethodObject::Initialize(); + + { + time_ms load_start = get_time(); + RelAssert(argc == 2 && "Invalid Arguments"); + auto obj = NDO->load(argv[1]); + RelAssert(obj && "Failed to Load the File"); + RelAssert(obj->type == &MethodObject::TypeData && "Innvalid file content"); + + Interpreter interp; + NDO_CASTV(MethodObject, obj, method); + + RelAssert(method->mScript && "Innvalid file content"); + time_ms load_end = get_time(); + + GLog->write("\noscvm - execution started\n"); + time_ms exec_start = get_time(); + interp.exec(&method->mScript->mBytecode); + time_ms exec_end = get_time(); + + auto exec_time = (exec_end - exec_start); + auto load_time = (load_end - load_start); + GLog->write(sfmt("\noscvm - execution finished (Load : %f Exec : %f)", load_time, exec_time)); + } + + try { + MethodObject::UnInitialize(); + objects_finalize(); + primitives_uninitialize(); + + Logger::deinit(); + string::UnInitialize(); + tp::alloc_uninit(); + + } catch (...) { + tp::terminate(); + } } \ No newline at end of file diff --git a/Objects/applications/TestEntry.cpp b/Objects/applications/TestEntry.cpp index 960c1b0..d285e64 100644 --- a/Objects/applications/TestEntry.cpp +++ b/Objects/applications/TestEntry.cpp @@ -1,87 +1,89 @@ - - -#include "primitives/methodobject.h" -#include "primitives/primitives.h" - -#include "interpreter/interpreter.h" - -#include "compiler/function.h" - -using namespace tp; -using namespace obj; - -void TestCompile(ByteCode& bytecode) { - using namespace BCgen; - - Genereate(bytecode, - StmScope({ - - StmDefFunc("main", {}, { - StmDefLocal("i1", ExprConst(1)), - StmDefLocal("i2", ExprConst(2)), - - //StmDefFunc("add", {"first", "second"}, { - // StmReturn(ExprAdd(ExprLocal("first"), ExprLocal("second"))) - //}), - - StmPrint(ExprLocal("i1")), - StmPrint(ExprConst(" + ")), - StmPrint(ExprLocal("i2")), - StmPrint(ExprConst(" = ")), - - StmPrint(ExprFunc("add")->ExprCall({ ExprLocal("i1"), ExprLocal("i2") })), - - StmPrint(ExprConst("\n")), - }), - - StmPrint(ExprBoolNot(ExprConst(0))), - - StmWhile(ExprConst(false), StmScope({ - StmIgnore(ExprFunc("main")->ExprCall({})) - }) - ), - - StmIf(ExprConst(true), - StmScope({ - //StmIgnore(ExprFunc("main")->ExprCall({})), - //StmPrint(ExprConst("true")), - }), - StmScope({ - //StmPrint(ExprConst("false")), - }) - ) - }) - ); -} - -int main(int argc, char* argv[]) { - - tp::alloc_init(); - string::Initialize(); - Logger::init(); - - objects_init(); - primitives_define_types(); - MethodObject::Initialize(); - - { - Interpreter interp; - - ByteCode bytecode; - TestCompile(bytecode); - - GLog->write(" >> Exec: start \n"); - auto start = get_time(); - interp.exec(&bytecode); - auto end = get_time(); - GLog->write(sfmt("\n >> Exec time %i ms", end - start)); - } - - MethodObject::UnInitialize(); - objects_finalize(); - primitives_uninitialize(); - - Logger::deinit(); - string::UnInitialize(); - tp::alloc_uninit(); + + +#include "primitives/methodobject.h" +#include "primitives/primitives.h" + +#include "interpreter/interpreter.h" + +#include "compiler/function.h" + +using namespace tp; +using namespace obj; + +void TestCompile(ByteCode& bytecode) { + using namespace BCgen; + + Genereate( + bytecode, + StmScope({ + + StmDefFunc( + "main", + {}, + { + StmDefLocal("i1", ExprConst(1)), + StmDefLocal("i2", ExprConst(2)), + + // StmDefFunc("add", {"first", "second"}, { + // StmReturn(ExprAdd(ExprLocal("first"), ExprLocal("second"))) + //}), + + StmPrint(ExprLocal("i1")), + StmPrint(ExprConst(" + ")), + StmPrint(ExprLocal("i2")), + StmPrint(ExprConst(" = ")), + + StmPrint(ExprFunc("add")->ExprCall({ ExprLocal("i1"), ExprLocal("i2") })), + + StmPrint(ExprConst("\n")), + } + ), + + StmPrint(ExprBoolNot(ExprConst(0))), + + StmWhile(ExprConst(false), StmScope({ StmIgnore(ExprFunc("main")->ExprCall({})) })), + + StmIf( + ExprConst(true), + StmScope({ + // StmIgnore(ExprFunc("main")->ExprCall({})), + // StmPrint(ExprConst("true")), + }), + StmScope({ + // StmPrint(ExprConst("false")), + }) + ) }) + ); +} + +int main(int argc, char* argv[]) { + + tp::alloc_init(); + string::Initialize(); + Logger::init(); + + objects_init(); + primitives_define_types(); + MethodObject::Initialize(); + + { + Interpreter interp; + + ByteCode bytecode; + TestCompile(bytecode); + + GLog->write(" >> Exec: start \n"); + auto start = get_time(); + interp.exec(&bytecode); + auto end = get_time(); + GLog->write(sfmt("\n >> Exec time %i ms", end - start)); + } + + MethodObject::UnInitialize(); + objects_finalize(); + primitives_uninitialize(); + + Logger::deinit(); + string::UnInitialize(); + tp::alloc_uninit(); } \ No newline at end of file diff --git a/Objects/applications/test.cpp b/Objects/applications/test.cpp index 6ed1c96..1da1486 100644 --- a/Objects/applications/test.cpp +++ b/Objects/applications/test.cpp @@ -1,75 +1,68 @@ - -#include "primitives/primitives.h" - -#include "compiler/function.h" -#include "interpreter/interpreter.h" - -#include "CmdArgParser.h" - -void compile(char argc, const char* argv[]) { - tp::CmdArgParser args = { - { "script", tp::CmdArgParser::Arg::FILE_IN }, - { "out", "out.mo" } - }; - - if (!args.parse(argc, argv, true)) { - return; - } - - auto& script_file = args.getFile("script"); - auto outpath = args.getString("out"); - - tp::string script; - script.loadFile(&script_file); - - auto method = obj::MethodObject::create(script); - - obj::NDO->save(method, outpath); -} - -void execute(char argc, const char* argv[]) { - tp::CmdArgParser args = { - { "object_path", tp::CmdArgParser::Arg::STR }, - { "debug", false } - }; - - if (!args.parse(argc, argv, true)) { - return; - } - - auto object_path = args.getString("object_path"); - auto debug = args.getBool("debug"); - - auto obj = obj::NDO->load(object_path); - if (!obj) { - printf("Invalid Object File\n"); - return; - } - - NDO_CASTV(obj::MethodObject, obj, method); - if (!method) { - printf("Object Is Not A Method\n"); - return; - } - - obj::Interpreter interpreter; - interpreter.execAll(method); -} - - -int main(char argc, const char* argv[]) { - - tp::ModuleManifest* ModuleDependencies[] = { &obj::gModuleObjects, NULL }; - tp::ModuleManifest TestModule("Test", NULL, NULL, ModuleDependencies); - if (!TestModule.initialize()) { - return 1; - } - -#ifdef OBC - compile(argc, argv); -#elif OBVM - execute(argc, argv); -#endif // OBC - - TestModule.deinitialize(); + +#include "primitives/primitives.h" + +#include "compiler/function.h" +#include "interpreter/interpreter.h" + +#include "CmdArgParser.h" + +void compile(char argc, const char* argv[]) { + tp::CmdArgParser args = { { "script", tp::CmdArgParser::Arg::FILE_IN }, { "out", "out.mo" } }; + + if (!args.parse(argc, argv, true)) { + return; + } + + auto& script_file = args.getFile("script"); + auto outpath = args.getString("out"); + + tp::string script; + script.loadFile(&script_file); + + auto method = obj::MethodObject::create(script); + + obj::NDO->save(method, outpath); +} + +void execute(char argc, const char* argv[]) { + tp::CmdArgParser args = { { "object_path", tp::CmdArgParser::Arg::STR }, { "debug", false } }; + + if (!args.parse(argc, argv, true)) { + return; + } + + auto object_path = args.getString("object_path"); + auto debug = args.getBool("debug"); + + auto obj = obj::NDO->load(object_path); + if (!obj) { + printf("Invalid Object File\n"); + return; + } + + NDO_CASTV(obj::MethodObject, obj, method); + if (!method) { + printf("Object Is Not A Method\n"); + return; + } + + obj::Interpreter interpreter; + interpreter.execAll(method); +} + +int main(char argc, const char* argv[]) { + + tp::ModuleManifest* ModuleDependencies[] = { &obj::gModuleObjects, NULL }; + tp::ModuleManifest TestModule("Test", NULL, NULL, ModuleDependencies); + if (!TestModule.initialize()) { + return 1; + } + +#ifdef OBC + compile(argc, argv); +#elif OBVM + execute(argc, argv); +#endif // OBC + + TestModule.deinitialize(); } \ No newline at end of file diff --git a/Objects/private/compiler/constants.cpp b/Objects/private/compiler/constants.cpp index 3208eaa..6de7e67 100644 --- a/Objects/private/compiler/constants.cpp +++ b/Objects/private/compiler/constants.cpp @@ -1,148 +1,145 @@ -#include "NewPlacement.hpp" -#include "compiler/constants.h" -#include "primitives/primitives.h" -#include "primitives/methodobject.h" - -using namespace obj; -using namespace tp; -using namespace BCgen; - -ConstObject::ConstObject() {} -ConstObject::ConstObject(obj::Object* mObj) : mObj(mObj) {} - -ConstObjectsPool::~ConstObjectsPool() { - if (mDelete) { - for (auto obj : mStrings) { - obj::NDO->destroy(obj->val->mObj); - } - for (auto obj : mIntegers) { - obj::NDO->destroy(obj->val->mObj); - } - for (auto obj : mFloats) { - obj::NDO->destroy(obj->val->mObj); - } - for (auto obj : mMethods) { - obj::NDO->destroy(obj->val->mObj); - } - if (mBoolFalse.mObj) { - obj::NDO->destroy(mBoolFalse.mObj); - } - if (mBoolTrue.mObj) { - obj::NDO->destroy(mBoolTrue.mObj); - } - } - for (auto obj : mStrings) { - delete obj->val; - } - for (auto obj : mIntegers) { - delete obj->val; - } - for (auto obj : mFloats) { - delete obj->val; - } -} - -ConstObject* ConstObjectsPool::registerObject(obj::Object* obj) { - ConstObject* out = new ConstObject(obj); - mTotalObjects++; - return out; -} - -ConstObject* ConstObjectsPool::get(tp::alni val) { - auto idx = mIntegers.presents(val); - ConstObject* const_obj = NULL; - if (idx) { - const_obj = mIntegers.getSlotVal(idx); - } - else { - const_obj = registerObject(IntObject::create(val)); - mIntegers.put(val, const_obj); - } - return const_obj; -} - -ConstObject* ConstObjectsPool::get(tp::String val) { - auto idx = mStrings.presents(val); - ConstObject* const_obj = NULL; - if (idx) { - const_obj = mStrings.getSlotVal(idx); - } - else { - const_obj = registerObject(StringObject::create(val)); - mStrings.put(val, const_obj); - } - return const_obj; -} - -ConstObject* ConstObjectsPool::get(tp::alnf val) { - auto idx = mFloats.presents(val); - ConstObject* const_obj = NULL; - if (idx) { - const_obj = mFloats.getSlotVal(idx); - } - else { - const_obj = registerObject(FloatObject::create(val)); - mFloats.put(val, const_obj); - } - return const_obj; -} - -ConstObject* ConstObjectsPool::get(bool val) { - if (val) { - if (!mBoolTrue.mObj) { - mBoolTrue.mObj = BoolObject::create(val); - mTotalObjects++; - } - return &mBoolTrue; - } - else { - if (!mBoolFalse.mObj) { - mBoolFalse.mObj = BoolObject::create(val); - mTotalObjects++; - } - return &mBoolFalse; - } -} - -ConstObject* ConstObjectsPool::addMethod(tp::String method_id, obj::Object* method) { - ASSERT(NDO_CAST(MethodObject, method) && "Object is not a method object"); - ASSERT(!mMethods.presents(method_id) && "Method Redefinition"); - auto out = registerObject(method); - mMethods.put(method_id, out); - return out; -} - -void ConstObjectsPool::save(tp::Buffer& out) { - out.reserve(mTotalObjects); - tp::alni data_idx = 0; - for (auto obj : mMethods) { - out[data_idx] = obj->val->mObj; - obj->val->mConstIdx = data_idx; - data_idx++; - } - for (auto obj : mStrings) { - out[data_idx] = obj->val->mObj; - obj->val->mConstIdx = data_idx; - data_idx++; - } - for (auto obj : mIntegers) { - out[data_idx] = obj->val->mObj; - obj->val->mConstIdx = data_idx; - data_idx++; - } - for (auto obj : mFloats) { - out[data_idx] = obj->val->mObj; - obj->val->mConstIdx = data_idx; - data_idx++; - } - if (mBoolFalse.mObj) { - out[data_idx] = mBoolFalse.mObj; - mBoolFalse.mConstIdx = data_idx; - data_idx++; - } - if (mBoolTrue.mObj) { - out[data_idx] = mBoolTrue.mObj; - mBoolTrue.mConstIdx = data_idx; - } - mDelete = false; +#include "compiler/constants.h" +#include "NewPlacement.hpp" +#include "primitives/methodobject.h" +#include "primitives/primitives.h" + +using namespace obj; +using namespace tp; +using namespace BCgen; + +ConstObject::ConstObject() {} +ConstObject::ConstObject(obj::Object* mObj) : + mObj(mObj) {} + +ConstObjectsPool::~ConstObjectsPool() { + if (mDelete) { + for (auto obj : mStrings) { + obj::NDO->destroy(obj->val->mObj); + } + for (auto obj : mIntegers) { + obj::NDO->destroy(obj->val->mObj); + } + for (auto obj : mFloats) { + obj::NDO->destroy(obj->val->mObj); + } + for (auto obj : mMethods) { + obj::NDO->destroy(obj->val->mObj); + } + if (mBoolFalse.mObj) { + obj::NDO->destroy(mBoolFalse.mObj); + } + if (mBoolTrue.mObj) { + obj::NDO->destroy(mBoolTrue.mObj); + } + } + for (auto obj : mStrings) { + delete obj->val; + } + for (auto obj : mIntegers) { + delete obj->val; + } + for (auto obj : mFloats) { + delete obj->val; + } +} + +ConstObject* ConstObjectsPool::registerObject(obj::Object* obj) { + ConstObject* out = new ConstObject(obj); + mTotalObjects++; + return out; +} + +ConstObject* ConstObjectsPool::get(tp::alni val) { + auto idx = mIntegers.presents(val); + ConstObject* const_obj = NULL; + if (idx) { + const_obj = mIntegers.getSlotVal(idx); + } else { + const_obj = registerObject(IntObject::create(val)); + mIntegers.put(val, const_obj); + } + return const_obj; +} + +ConstObject* ConstObjectsPool::get(tp::String val) { + auto idx = mStrings.presents(val); + ConstObject* const_obj = NULL; + if (idx) { + const_obj = mStrings.getSlotVal(idx); + } else { + const_obj = registerObject(StringObject::create(val)); + mStrings.put(val, const_obj); + } + return const_obj; +} + +ConstObject* ConstObjectsPool::get(tp::alnf val) { + auto idx = mFloats.presents(val); + ConstObject* const_obj = NULL; + if (idx) { + const_obj = mFloats.getSlotVal(idx); + } else { + const_obj = registerObject(FloatObject::create(val)); + mFloats.put(val, const_obj); + } + return const_obj; +} + +ConstObject* ConstObjectsPool::get(bool val) { + if (val) { + if (!mBoolTrue.mObj) { + mBoolTrue.mObj = BoolObject::create(val); + mTotalObjects++; + } + return &mBoolTrue; + } else { + if (!mBoolFalse.mObj) { + mBoolFalse.mObj = BoolObject::create(val); + mTotalObjects++; + } + return &mBoolFalse; + } +} + +ConstObject* ConstObjectsPool::addMethod(tp::String method_id, obj::Object* method) { + ASSERT(NDO_CAST(MethodObject, method) && "Object is not a method object"); + ASSERT(!mMethods.presents(method_id) && "Method Redefinition"); + auto out = registerObject(method); + mMethods.put(method_id, out); + return out; +} + +void ConstObjectsPool::save(tp::Buffer& out) { + out.reserve(mTotalObjects); + tp::alni data_idx = 0; + for (auto obj : mMethods) { + out[data_idx] = obj->val->mObj; + obj->val->mConstIdx = data_idx; + data_idx++; + } + for (auto obj : mStrings) { + out[data_idx] = obj->val->mObj; + obj->val->mConstIdx = data_idx; + data_idx++; + } + for (auto obj : mIntegers) { + out[data_idx] = obj->val->mObj; + obj->val->mConstIdx = data_idx; + data_idx++; + } + for (auto obj : mFloats) { + out[data_idx] = obj->val->mObj; + obj->val->mConstIdx = data_idx; + data_idx++; + } + if (mBoolFalse.mObj) { + out[data_idx] = mBoolFalse.mObj; + mBoolFalse.mConstIdx = data_idx; + data_idx++; + } + if (mBoolTrue.mObj) { + out[data_idx] = mBoolTrue.mObj; + mBoolTrue.mConstIdx = data_idx; + } + mDelete = false; } \ No newline at end of file diff --git a/Objects/private/compiler/expression.cpp b/Objects/private/compiler/expression.cpp index 322a8c5..a11c81d 100644 --- a/Objects/private/compiler/expression.cpp +++ b/Objects/private/compiler/expression.cpp @@ -1,70 +1,93 @@ -#include "NewPlacement.hpp" -#include "compiler/expression.h" - -using namespace obj; -using namespace BCgen; - -Expression::Expression() {} -Expression::Expression(Type type) : mType(type) {} - -ExpressionChild* Expression::ExprChild(tp::String id) { - return new ExpressionChild(this, id); -} - -ExpressionCall* Expression::ExprCall(tp::InitialierList args) { - return new ExpressionCall(this, args); -} - -ExpressionLocal* obj::BCgen::ExprLocal(tp::String id) { - return new ExpressionLocal(id); -} - -ExpressionSelf* obj::BCgen::ExprSelf() { - return new ExpressionSelf(); -} - -ExpressionNew* obj::BCgen::ExprNew(tp::String type) { - return new ExpressionNew(type); -} - -ExpressionAriphm* obj::BCgen::ExprAriphm(Expression* left, Expression* right, OpCode type) { - return new ExpressionAriphm(left, right, type); -} - -ExpressionFunc* obj::BCgen::ExprFunc(tp::String id) { - return new ExpressionFunc(id); -} - -ExpressionBoolean* obj::BCgen::ExprBool(Expression* left, Expression* right, obj::OpCode type) { - return new ExpressionBoolean(left, right, ExpressionBoolean::BoolType(type)); -} - -ExpressionBoolean* obj::BCgen::ExprBoolNot(Expression* invert) { - return new ExpressionBoolean(invert); -} - -ExpressionBoolean::ExpressionBoolean(Expression* left, Expression* right, BoolType type) -: Expression(Type::BOOLEAN), mLeft(left), mRight(right), mBoolType(type) { -} - -ExpressionBoolean::ExpressionBoolean(Expression* invert) - : Expression(Type::BOOLEAN), mLeft(invert), mBoolType(BoolType::NOT){ -} - -ExpressionCall::ExpressionCall(Expression * mParent, tp::InitialierList args) : Expression(Type::CALL), mParent(mParent) { - mArgs = args; -} - -ExpressionNew::ExpressionNew(tp::String type) : Expression(Type::NEW), mNewType(type) {} -ExpressionLocal::ExpressionLocal(tp::String id) : Expression(Type::LOCAL), mLocalId(id) {} -ExpressionSelf::ExpressionSelf() : Expression(Type::SELF) {} -ExpressionChild::ExpressionChild(Expression* mParent, tp::String id) : Expression(Type::CHILD), mParent(mParent), mLocalId(id) {} -ExpressionAriphm::ExpressionAriphm(Expression* left, Expression* right, OpCode type) : Expression(Type::ARIPHM), mLeft(left), mRight(right), mOpType(type) {} -ExpressionFunc::ExpressionFunc(tp::String id) : Expression(Type::FUNC), mFuncId(id) {} -ExpressionConst::ExpressionConst(tp::String val) : Expression(Type::CONST), mConstType(STR), str(val) {} -ExpressionConst::ExpressionConst(const char* val) : Expression(Type::CONST), mConstType(STR), str(val) {} -ExpressionConst::ExpressionConst(tp::int4 val) : Expression(Type::CONST), mConstType(INT), integer(val) {} -ExpressionConst::ExpressionConst(tp::flt4 val) : Expression(Type::CONST), mConstType(FLT), floating(val) {} -ExpressionConst::ExpressionConst(tp::alni val) : Expression(Type::CONST), mConstType(INT), integer(val) {} -ExpressionConst::ExpressionConst(tp::alnf val) : Expression(Type::CONST), mConstType(FLT), floating(val) {} -ExpressionConst::ExpressionConst(bool val) : Expression(Type::CONST), mConstType(BOOL), boolean(val) {} +#include "compiler/expression.h" +#include "NewPlacement.hpp" + +using namespace obj; +using namespace BCgen; + +Expression::Expression() {} +Expression::Expression(Type type) : + mType(type) {} + +ExpressionChild* Expression::ExprChild(tp::String id) { return new ExpressionChild(this, id); } + +ExpressionCall* Expression::ExprCall(tp::InitialierList args) { return new ExpressionCall(this, args); } + +ExpressionLocal* obj::BCgen::ExprLocal(tp::String id) { return new ExpressionLocal(id); } + +ExpressionSelf* obj::BCgen::ExprSelf() { return new ExpressionSelf(); } + +ExpressionNew* obj::BCgen::ExprNew(tp::String type) { return new ExpressionNew(type); } + +ExpressionAriphm* obj::BCgen::ExprAriphm(Expression* left, Expression* right, OpCode type) { return new ExpressionAriphm(left, right, type); } + +ExpressionFunc* obj::BCgen::ExprFunc(tp::String id) { return new ExpressionFunc(id); } + +ExpressionBoolean* obj::BCgen::ExprBool(Expression* left, Expression* right, obj::OpCode type) { return new ExpressionBoolean(left, right, ExpressionBoolean::BoolType(type)); } + +ExpressionBoolean* obj::BCgen::ExprBoolNot(Expression* invert) { return new ExpressionBoolean(invert); } + +ExpressionBoolean::ExpressionBoolean(Expression* left, Expression* right, BoolType type) : + Expression(Type::BOOLEAN), + mLeft(left), + mRight(right), + mBoolType(type) {} + +ExpressionBoolean::ExpressionBoolean(Expression* invert) : + Expression(Type::BOOLEAN), + mLeft(invert), + mBoolType(BoolType::NOT) {} + +ExpressionCall::ExpressionCall(Expression* mParent, tp::InitialierList args) : + Expression(Type::CALL), + mParent(mParent) { + mArgs = args; +} + +ExpressionNew::ExpressionNew(tp::String type) : + Expression(Type::NEW), + mNewType(type) {} +ExpressionLocal::ExpressionLocal(tp::String id) : + Expression(Type::LOCAL), + mLocalId(id) {} +ExpressionSelf::ExpressionSelf() : + Expression(Type::SELF) {} +ExpressionChild::ExpressionChild(Expression* mParent, tp::String id) : + Expression(Type::CHILD), + mParent(mParent), + mLocalId(id) {} +ExpressionAriphm::ExpressionAriphm(Expression* left, Expression* right, OpCode type) : + Expression(Type::ARIPHM), + mLeft(left), + mRight(right), + mOpType(type) {} +ExpressionFunc::ExpressionFunc(tp::String id) : + Expression(Type::FUNC), + mFuncId(id) {} +ExpressionConst::ExpressionConst(tp::String val) : + Expression(Type::CONST), + mConstType(STR), + str(val) {} +ExpressionConst::ExpressionConst(const char* val) : + Expression(Type::CONST), + mConstType(STR), + str(val) {} +ExpressionConst::ExpressionConst(tp::int4 val) : + Expression(Type::CONST), + mConstType(INT), + integer(val) {} +ExpressionConst::ExpressionConst(tp::flt4 val) : + Expression(Type::CONST), + mConstType(FLT), + floating(val) {} +ExpressionConst::ExpressionConst(tp::alni val) : + Expression(Type::CONST), + mConstType(INT), + integer(val) {} +ExpressionConst::ExpressionConst(tp::alnf val) : + Expression(Type::CONST), + mConstType(FLT), + floating(val) {} +ExpressionConst::ExpressionConst(bool val) : + Expression(Type::CONST), + mConstType(BOOL), + boolean(val) {} diff --git a/Objects/private/compiler/function.cpp b/Objects/private/compiler/function.cpp index c178136..6cb85ae 100644 --- a/Objects/private/compiler/function.cpp +++ b/Objects/private/compiler/function.cpp @@ -1,558 +1,597 @@ - -#include "NewPlacement.hpp" - -#include "compiler/function.h" - -#include "primitives/primitives.h" -#include "primitives/methodobject.h" - -#include "Logging.hpp" - -#include "parser/parser.h" - -using namespace obj; -using namespace tp; -using namespace obj; -using namespace BCgen; - -void obj::BCgen::Genereate(ByteCode& out, StatementScope* body) { - auto root = FunctionDefinition(); - - root.inst(Instruction(OpCode::SCOPE_IN)); - - for (auto child_stm : body->mStatements) { - root.EvalStatement(child_stm.data()); - } - - root.inst(Instruction(OpCode::SCOPE_OUT)); - - root.generateByteCode(out); -} - -ConstObject* FunctionDefinition::defineLocal(tp::String id) { - auto idx = mLocals.presents(id); - //RelAssert(!idx && "Local Redefinition"); - auto const_str_id = mConstants.get(id); - mLocals.put(id, const_str_id); - return const_str_id; -} - -FunctionDefinition::FunctionDefinition(tp::String function_id, tp::Buffer args, FunctionDefinition* prnt) { - mFunctionId = function_id; - inst(Instruction(OpCode::SAVE_ARGS, args.size(), 1)); - for (auto id : args) { - ASSERT(!mLocals.presents(id.data()) && "Argument Redefinition"); - auto const_data = mConstants.get(id.data()); - mArgsOrder.pushBack(const_data); - mLocals.put(id.data(), const_data); - inst(Instruction(const_data)); - } -} - -void FunctionDefinition::EvalStatement(Statement* stm) { - switch (stm->mType) { - case Statement::Type::IGNORE: { - auto stm_ignore = (StatementIgnore*)stm; - EvalExpr(stm_ignore->mExpr); - inst(OpCode::IGNORE); - break; - } - case Statement::Type::WHILE: { - auto stm_while = (StatementWhile*)stm; - - auto check_mark = inst(Instruction()); - - EvalExpr(stm_while->mCondition); - - auto jump_if_inst = inst(Instruction(NULL, Instruction::InstType::JUMP_IF_NOT)); - - if (stm_while->mScope) { - EvalStatement(stm_while->mScope); - } - - auto jump_inst = inst(Instruction(NULL, Instruction::InstType::JUMP)); - auto end_mark = inst(Instruction()); - - jump_if_inst->data.mInstTarget = &end_mark->data; - jump_inst->data.mInstTarget = &check_mark->data; - - break; - } - case Statement::Type::IF: { - auto stm_if = (StatementIf*)stm; - - EvalExpr(stm_if->mCondition); - - auto jump_if_inst = inst(Instruction(NULL, Instruction::InstType::JUMP_IF_NOT)); - - if (stm_if->mOnTrue) { - EvalStatement(stm_if->mOnTrue); - } - - auto jump_inst = inst(Instruction(NULL, Instruction::InstType::JUMP)); - auto else_mark = inst(Instruction()); - - if (stm_if->mOnFalse) { - EvalStatement(stm_if->mOnFalse); - } - - auto end_mark = inst(Instruction()); - - jump_if_inst->data.mInstTarget = &else_mark->data; - jump_inst->data.mInstTarget = &end_mark->data; - - break; - } - case Statement::Type::SCOPE: { - auto stm_scope = (StatementScope*)stm; - if (stm_scope->mPushToScopeStack) { - inst(Instruction(OpCode::SCOPE_IN)); - } - for (auto child_stm : stm_scope->mStatements) { - EvalStatement(child_stm.data()); - } - if (stm_scope->mPushToScopeStack) { - inst(Instruction(OpCode::SCOPE_OUT)); - } - break; - } - case Statement::Type::DEF_FUNC: { - auto stm_func_def = (StatementFuncDef*) stm; - - FunctionDefinition func(stm_func_def->mFunctionId, stm_func_def->mArgs, this); - - // define method as local - auto idx = mLocals.presents(func.mFunctionId); - ASSERT(!idx && "Local Redefinition with function name"); - mLocals.put(func.mFunctionId, mConstants.get(func.mFunctionId)); - - // create and register const func object - auto function_obj = NDO_CAST(MethodObject, NDO->create("method")); - auto method_const_obj = mConstants.addMethod(func.mFunctionId, function_obj); - - for (auto child_stm : stm_func_def->mStatements) { - func.EvalStatement(child_stm.data()); - } - - func.generateByteCode(function_obj->mScript->mBytecode); - - inst(Instruction(OpCode::LOAD_CONST, method_const_obj)); - inst(Instruction(OpCode::LOAD_CONST, mConstants.get(func.mFunctionId))); - inst(Instruction(OpCode::DEF_LOCAL)); - break; - } - case Statement::Type::CLASS_DEF: { - - // do the function definition - auto stm_class_def = (StatementClassDef*)stm; - - FunctionDefinition func(stm_class_def->mClassId, {}, this); - - // define method as local - auto idx = mLocals.presents(func.mFunctionId); - ASSERT(!idx && "Local Redefinition with function name"); - mLocals.put(func.mFunctionId, mConstants.get(func.mFunctionId)); - - // create and register const func object - auto function_obj = NDO_CAST(MethodObject, NDO->create("method")); - auto method_const_obj = mConstants.addMethod(func.mFunctionId, function_obj); - - // compile function - for (auto child_stm : stm_class_def->mScope->mStatements) { - // check for return statements - ASSERT(child_stm.data()->mType != Statement::Type::RET && "return statements are not allowed in class definition"); - func.EvalStatement(child_stm.data()); - } - // create one last instruction - constructing class from function execution state - func.inst(Instruction(OpCode::CLASS_CONSTRUCT)); - func.generateByteCode(function_obj->mScript->mBytecode); - - inst(Instruction(OpCode::LOAD_CONST, method_const_obj)); - inst(Instruction(OpCode::LOAD_CONST, mConstants.get(func.mFunctionId))); - inst(Instruction(OpCode::DEF_LOCAL)); - break; - } - case Statement::Type::DEF_LOCAL: { - auto stm_local_def = (StatementLocalDef*)stm; - - if (!stm_local_def->mIsConstExpr) { - auto const_id = defineLocal(stm_local_def->mLocalId); - EvalExpr(stm_local_def->mNewExpr); - inst(Instruction(OpCode::LOAD_CONST, const_id)); - inst(Instruction(OpCode::DEF_LOCAL)); - - } else { - - tp::String type; - switch (stm_local_def->mConstExpr->mConstType) { - case ExpressionConst::BOOL: { - type = "bool"; - break; - } - case ExpressionConst::INT: { - type = "int"; - break; - } - case ExpressionConst::FLT: { - type = "float"; - break; - } - case ExpressionConst::STR: { - type = "str"; - break; - } - default: { - ASSERT(0 && "Cantbe"); - } - } - - auto new_expr = new ExpressionNew(type); - - EvalStatement(StmDefLocal(stm_local_def->mLocalId, new_expr)); - EvalExpr(stm_local_def->mConstExpr); - inst(Instruction(OpCode::LOAD_LOCAL, mConstants.get(stm_local_def->mLocalId))); - inst(Instruction(OpCode::OBJ_COPY)); - } - break; - } - case Statement::Type::COPY: { - auto stm_cp = (StatementCopy*)stm; - EvalExpr(stm_cp->mRight); - EvalExpr(stm_cp->mLeft); - inst(Instruction(OpCode::OBJ_COPY)); - break; - } - case Statement::Type::PRINT: { - auto stm_prnt = (StatementPrint*)stm; - EvalExpr(stm_prnt->mTarget); - inst(Instruction(OpCode::PRINT)); - break; - } - case Statement::Type::RET: { - auto stm_ret = (StatementReturn*)stm; - if (stm_ret->mRet) { - EvalExpr(stm_ret->mRet); - inst(Instruction(OpCode::RETURN_OBJ)); - } else { - inst(Instruction(OpCode::RETURN)); - } - break; - } - - default: - ASSERT(0) - } - - delete stm; -} - - -void FunctionDefinition::EvalExpr(Expression* expr) { - switch (expr->mType) { - case Expression::Type::BOOLEAN: { - auto boolean = (ExpressionBoolean*)expr; - if (boolean->mBoolType == ExpressionBoolean::BoolType::NOT) { - EvalExpr(boolean->mLeft); - inst(OpCode::NOT); - } else { - EvalExpr(boolean->mRight); - EvalExpr(boolean->mLeft); - inst(OpCode(boolean->mBoolType)); - } - break; - } - case Expression::Type::FUNC: { - auto func = (ExpressionFunc*)expr; - - //RelAssert(mConstants.mMethods.presents(func->mFuncId) && "No such function"); - inst(Instruction(OpCode::LOAD_LOCAL, mConstants.get(func->mFuncId))); - break; - } - case Expression::Type::ARIPHM: { - auto ariphm = (ExpressionAriphm*)expr; - EvalExpr(ariphm->mRight); - EvalExpr(ariphm->mLeft); - inst(Instruction(ariphm->mOpType)); - break; - } - case Expression::Type::NEW: { - auto create_new = (ExpressionNew*)expr; - inst(Instruction(OpCode::LOAD_CONST, mConstants.get(create_new->mNewType))); - inst(Instruction(OpCode::OBJ_CREATE)); - break; - } - case Expression::Type::LOCAL: { - auto local = (ExpressionLocal*)expr; - // RelAssert(mLocals.presents(local->mLocalId) && "undefined local"); - inst(Instruction(OpCode::LOAD_LOCAL, mConstants.get(local->mLocalId))); - break; - } - case Expression::Type::CONST: { - auto constobj = (ExpressionConst*)expr; - switch (constobj->mConstType) { - case ExpressionConst::STR: { - inst(Instruction(OpCode::LOAD_CONST, mConstants.get(constobj->str))); - break; - } - case ExpressionConst::INT: { - inst(Instruction(OpCode::LOAD_CONST, mConstants.get(constobj->integer))); - break; - } - case ExpressionConst::FLT: { - inst(Instruction(OpCode::LOAD_CONST, mConstants.get(constobj->floating))); - break; - } - case ExpressionConst::BOOL: { - inst(Instruction(OpCode::LOAD_CONST, mConstants.get(constobj->boolean))); - break; - } - }; - break; - } - case Expression::Type::CHILD: { - auto child = (ExpressionChild*)expr; - EvalExpr(child->mParent); - inst(Instruction(OpCode::LOAD_CONST, mConstants.get(child->mLocalId))); - inst(Instruction(OpCode::CHILD, child->mMethod, 1)); - break; - } - case Expression::Type::SELF: { - inst(Instruction(OpCode::SELF)); - break; - } - case Expression::Type::CALL: { - auto call = (ExpressionCall*)expr; - inst(Instruction(OpCode::PUSH_ARGS, call->mArgs.size(), 1)); - for (auto arg : call->mArgs) { - EvalExpr(arg.data()); - } - EvalExpr(call->mParent); - inst(Instruction(OpCode::CALL)); - break; - } - - default: - ASSERT(0) - } - delete expr; -} - -tp::alni instSize(const Instruction& inst) { - switch (inst.mInstType) { - case Instruction::InstType::JUMP: - case Instruction::InstType::JUMP_IF_NOT: - case Instruction::InstType::JUMP_IF: { - // 2 bytes for offset 1 byte for instrtuction - return 3; - } - case Instruction::InstType::PURE_CONST: { - return 2; - } - case Instruction::InstType::EXEC: { - tp::alni out = 1; - switch (inst.mArgType) { - case Instruction::ArgType::PARAM: { - out += inst.mParamBytes; - return out; - } - case Instruction::ArgType::CONST: { - out += 2; - if (inst.mConstData2) { - out += 2; - } - return out; - } - case Instruction::ArgType::NO_ARG: { - return out; - } - default: { - ASSERT(0); - } - } - } - case Instruction::InstType::NONE: { - return 0; - } - default: { - ASSERT(0); - } - } - - ASSERT(0); - return 0; -} - -void writeConst(ByteCode& out, tp::alni& idx, tp::uint2 data) { - for (auto byte : tp::Range(sizeof(tp::uint2))) { - out.mInstructions[idx] = OpCode((tp::int1)(data >> byte * 8)); - idx++; - } -} - -void writeParam(ByteCode& out, tp::alni& idx, tp::int1* data, tp::alni size) { - for (auto byte : tp::Range(size)) { - out.mInstructions[idx] = OpCode(data[byte]); - idx++; - } -} - -tp::alni calcOffset(tp::List::Node* jump_inst, Instruction* to) { - tp::alni offset = 0; - bool reversed = jump_inst->data.mInstIdx > to->mInstIdx; - auto iter_node = reversed ? jump_inst : jump_inst->next; - while (&iter_node->data != to) { - offset += instSize(iter_node->data); - iter_node = reversed ? iter_node->prev : iter_node->next; - } - if (reversed) { - offset += instSize(iter_node->data); - } - return reversed ? -offset : offset; -} - -void FunctionDefinition::generateByteCode(ByteCode& out) { - - out.~ByteCode(); - new (&out) ByteCode(); - - mConstants.save(out.mConstants); - - tp::alni inst_len = 0; - for (auto inst_iter : mInstructions) { - inst_len += instSize(inst_iter.data()); - } - out.mInstructions.reserve(inst_len); - - tp::alni idx = 0; - for (auto inst_iter : mInstructions) { - auto inst = inst_iter.data(); - - switch (inst.mInstType) { - case Instruction::InstType::JUMP_IF: - case Instruction::InstType::JUMP_IF_NOT: - case Instruction::InstType::JUMP: { - tp::alni offset = calcOffset(inst_iter.node(), inst.mInstTarget); - - if (offset == 0) { - out.mInstructions[idx] = OpCode::NONE; - idx += 3; - break; - } - - if (inst.mInstType == Instruction::InstType::JUMP_IF) { - if (offset > 0) { - out.mInstructions[idx] = OpCode::JUMP_IF; - } - else { - out.mInstructions[idx] = OpCode::JUMP_IF_R; - } - } - else if (inst.mInstType == Instruction::InstType::JUMP_IF_NOT) { - if (offset > 0) { - out.mInstructions[idx] = OpCode::JUMP_IF_NOT; - } - else { - out.mInstructions[idx] = OpCode::JUMP_IF_NOT_R; - } - } - else { - if (offset > 0) { - out.mInstructions[idx] = OpCode::JUMP; - } - else { - out.mInstructions[idx] = OpCode::JUMP_R; - } - } - - idx++; - - tp::alni offset_mod = abs(offset); - tp::uint2 offset_param = (tp::uint2)offset_mod; - writeParam(out, idx, (tp::int1*)&offset_param, 2); - break; - } - case Instruction::InstType::PURE_CONST: { - writeConst(out, idx, (tp::uint2)inst.mConstData->mConstIdx); - break; - } - case Instruction::InstType::EXEC: { - out.mInstructions[idx] = inst.mOp; - idx++; - switch (inst.mArgType) { - case Instruction::ArgType::PARAM: { - writeParam(out, idx, (tp::int1*) &inst.mParam, inst.mParamBytes); - break; - } - case Instruction::ArgType::CONST: { - writeConst(out, idx, (tp::uint2)inst.mConstData->mConstIdx); - if (inst.mConstData2) { - writeConst(out, idx, (tp::uint2)inst.mConstData2->mConstIdx); - } - break; - } - case Instruction::ArgType::NO_ARG: { - break; - } - default:{ - ASSERT(0); - } - } - break; - } - default: { - ASSERT(0); - } - case Instruction::InstType::NONE: {} - } - } -} - -tp::List::Node* FunctionDefinition::inst(Instruction inst) { - mInstructions.pushBack(inst); - auto out = &mInstructions.last()->data; - out->mInstIdx = mInstructions.length() - 1; - return mInstructions.last(); -} - -static Parser* sParger = NULL; - -void obj::BCgen::init() { - ASSERT(!sParger); - if (!sParger) { - sParger = new Parser(); - } -} - -void obj::BCgen::deinit() { - ASSERT(sParger); - if (sParger) { - delete sParger; - sParger = nullptr; - } -} - -bool obj::BCgen::Compile(obj::MethodObject* method) { - - ASSERT(method); - ASSERT(sParger); - - if (!sParger) return false; - - auto script = method->mScript->mReadable->val; - auto res = sParger->parse(script); - - if (res.err) { - // TODO : print parse error - auto loc = res.err->get_err_location(script.read()); - printf("Parser Error (%i,%i): %s\n", loc.head, loc.tail, res.err->mDescr.read()); - // tp::gLogeer->write(tp::sfmt("Parser Error (%i,%i): \n", loc.head, loc.tail), true, tp::Logger::LogEntry::ERR); - // tp::GLog->write(res.err->mDescr, true, tp::Logger::LogEntry::ERR); - return false; - } - - BCgen::Genereate(method->mScript->mBytecode, res.scope); - - delete res.scope; - - return true; + +#include "NewPlacement.hpp" + +#include "compiler/function.h" + +#include "primitives/methodobject.h" +#include "primitives/primitives.h" + +#include "Logging.hpp" + +#include "parser/parser.h" + +using namespace obj; +using namespace tp; +using namespace obj; +using namespace BCgen; + +void obj::BCgen::Genereate(ByteCode& out, StatementScope* body) { + auto root = FunctionDefinition(); + + root.inst(Instruction(OpCode::SCOPE_IN)); + + for (auto child_stm : body->mStatements) { + root.EvalStatement(child_stm.data()); + } + + root.inst(Instruction(OpCode::SCOPE_OUT)); + + root.generateByteCode(out); +} + +ConstObject* FunctionDefinition::defineLocal(tp::String id) { + auto idx = mLocals.presents(id); + // RelAssert(!idx && "Local Redefinition"); + auto const_str_id = mConstants.get(id); + mLocals.put(id, const_str_id); + return const_str_id; +} + +FunctionDefinition::FunctionDefinition(tp::String function_id, tp::Buffer args, FunctionDefinition* prnt) { + mFunctionId = function_id; + inst(Instruction(OpCode::SAVE_ARGS, args.size(), 1)); + for (auto id : args) { + ASSERT(!mLocals.presents(id.data()) && "Argument Redefinition"); + auto const_data = mConstants.get(id.data()); + mArgsOrder.pushBack(const_data); + mLocals.put(id.data(), const_data); + inst(Instruction(const_data)); + } +} + +void FunctionDefinition::EvalStatement(Statement* stm) { + switch (stm->mType) { + case Statement::Type::IGNORE: + { + auto stm_ignore = (StatementIgnore*) stm; + EvalExpr(stm_ignore->mExpr); + inst(OpCode::IGNORE); + break; + } + case Statement::Type::WHILE: + { + auto stm_while = (StatementWhile*) stm; + + auto check_mark = inst(Instruction()); + + EvalExpr(stm_while->mCondition); + + auto jump_if_inst = inst(Instruction(NULL, Instruction::InstType::JUMP_IF_NOT)); + + if (stm_while->mScope) { + EvalStatement(stm_while->mScope); + } + + auto jump_inst = inst(Instruction(NULL, Instruction::InstType::JUMP)); + auto end_mark = inst(Instruction()); + + jump_if_inst->data.mInstTarget = &end_mark->data; + jump_inst->data.mInstTarget = &check_mark->data; + + break; + } + case Statement::Type::IF: + { + auto stm_if = (StatementIf*) stm; + + EvalExpr(stm_if->mCondition); + + auto jump_if_inst = inst(Instruction(NULL, Instruction::InstType::JUMP_IF_NOT)); + + if (stm_if->mOnTrue) { + EvalStatement(stm_if->mOnTrue); + } + + auto jump_inst = inst(Instruction(NULL, Instruction::InstType::JUMP)); + auto else_mark = inst(Instruction()); + + if (stm_if->mOnFalse) { + EvalStatement(stm_if->mOnFalse); + } + + auto end_mark = inst(Instruction()); + + jump_if_inst->data.mInstTarget = &else_mark->data; + jump_inst->data.mInstTarget = &end_mark->data; + + break; + } + case Statement::Type::SCOPE: + { + auto stm_scope = (StatementScope*) stm; + if (stm_scope->mPushToScopeStack) { + inst(Instruction(OpCode::SCOPE_IN)); + } + for (auto child_stm : stm_scope->mStatements) { + EvalStatement(child_stm.data()); + } + if (stm_scope->mPushToScopeStack) { + inst(Instruction(OpCode::SCOPE_OUT)); + } + break; + } + case Statement::Type::DEF_FUNC: + { + auto stm_func_def = (StatementFuncDef*) stm; + + FunctionDefinition func(stm_func_def->mFunctionId, stm_func_def->mArgs, this); + + // define method as local + auto idx = mLocals.presents(func.mFunctionId); + ASSERT(!idx && "Local Redefinition with function name"); + mLocals.put(func.mFunctionId, mConstants.get(func.mFunctionId)); + + // create and register const func object + auto function_obj = NDO_CAST(MethodObject, NDO->create("method")); + auto method_const_obj = mConstants.addMethod(func.mFunctionId, function_obj); + + for (auto child_stm : stm_func_def->mStatements) { + func.EvalStatement(child_stm.data()); + } + + func.generateByteCode(function_obj->mScript->mBytecode); + + inst(Instruction(OpCode::LOAD_CONST, method_const_obj)); + inst(Instruction(OpCode::LOAD_CONST, mConstants.get(func.mFunctionId))); + inst(Instruction(OpCode::DEF_LOCAL)); + break; + } + case Statement::Type::CLASS_DEF: + { + + // do the function definition + auto stm_class_def = (StatementClassDef*) stm; + + FunctionDefinition func(stm_class_def->mClassId, {}, this); + + // define method as local + auto idx = mLocals.presents(func.mFunctionId); + ASSERT(!idx && "Local Redefinition with function name"); + mLocals.put(func.mFunctionId, mConstants.get(func.mFunctionId)); + + // create and register const func object + auto function_obj = NDO_CAST(MethodObject, NDO->create("method")); + auto method_const_obj = mConstants.addMethod(func.mFunctionId, function_obj); + + // compile function + for (auto child_stm : stm_class_def->mScope->mStatements) { + // check for return statements + ASSERT(child_stm.data()->mType != Statement::Type::RET && "return statements are not allowed in class definition"); + func.EvalStatement(child_stm.data()); + } + // create one last instruction - constructing class from function execution state + func.inst(Instruction(OpCode::CLASS_CONSTRUCT)); + func.generateByteCode(function_obj->mScript->mBytecode); + + inst(Instruction(OpCode::LOAD_CONST, method_const_obj)); + inst(Instruction(OpCode::LOAD_CONST, mConstants.get(func.mFunctionId))); + inst(Instruction(OpCode::DEF_LOCAL)); + break; + } + case Statement::Type::DEF_LOCAL: + { + auto stm_local_def = (StatementLocalDef*) stm; + + if (!stm_local_def->mIsConstExpr) { + auto const_id = defineLocal(stm_local_def->mLocalId); + EvalExpr(stm_local_def->mNewExpr); + inst(Instruction(OpCode::LOAD_CONST, const_id)); + inst(Instruction(OpCode::DEF_LOCAL)); + + } else { + + tp::String type; + switch (stm_local_def->mConstExpr->mConstType) { + case ExpressionConst::BOOL: + { + type = "bool"; + break; + } + case ExpressionConst::INT: + { + type = "int"; + break; + } + case ExpressionConst::FLT: + { + type = "float"; + break; + } + case ExpressionConst::STR: + { + type = "str"; + break; + } + default: + { + ASSERT(0 && "Cantbe"); + } + } + + auto new_expr = new ExpressionNew(type); + + EvalStatement(StmDefLocal(stm_local_def->mLocalId, new_expr)); + EvalExpr(stm_local_def->mConstExpr); + inst(Instruction(OpCode::LOAD_LOCAL, mConstants.get(stm_local_def->mLocalId))); + inst(Instruction(OpCode::OBJ_COPY)); + } + break; + } + case Statement::Type::COPY: + { + auto stm_cp = (StatementCopy*) stm; + EvalExpr(stm_cp->mRight); + EvalExpr(stm_cp->mLeft); + inst(Instruction(OpCode::OBJ_COPY)); + break; + } + case Statement::Type::PRINT: + { + auto stm_prnt = (StatementPrint*) stm; + EvalExpr(stm_prnt->mTarget); + inst(Instruction(OpCode::PRINT)); + break; + } + case Statement::Type::RET: + { + auto stm_ret = (StatementReturn*) stm; + if (stm_ret->mRet) { + EvalExpr(stm_ret->mRet); + inst(Instruction(OpCode::RETURN_OBJ)); + } else { + inst(Instruction(OpCode::RETURN)); + } + break; + } + + default: ASSERT(0) + } + + delete stm; +} + +void FunctionDefinition::EvalExpr(Expression* expr) { + switch (expr->mType) { + case Expression::Type::BOOLEAN: + { + auto boolean = (ExpressionBoolean*) expr; + if (boolean->mBoolType == ExpressionBoolean::BoolType::NOT) { + EvalExpr(boolean->mLeft); + inst(OpCode::NOT); + } else { + EvalExpr(boolean->mRight); + EvalExpr(boolean->mLeft); + inst(OpCode(boolean->mBoolType)); + } + break; + } + case Expression::Type::FUNC: + { + auto func = (ExpressionFunc*) expr; + + // RelAssert(mConstants.mMethods.presents(func->mFuncId) && "No such function"); + inst(Instruction(OpCode::LOAD_LOCAL, mConstants.get(func->mFuncId))); + break; + } + case Expression::Type::ARIPHM: + { + auto ariphm = (ExpressionAriphm*) expr; + EvalExpr(ariphm->mRight); + EvalExpr(ariphm->mLeft); + inst(Instruction(ariphm->mOpType)); + break; + } + case Expression::Type::NEW: + { + auto create_new = (ExpressionNew*) expr; + inst(Instruction(OpCode::LOAD_CONST, mConstants.get(create_new->mNewType))); + inst(Instruction(OpCode::OBJ_CREATE)); + break; + } + case Expression::Type::LOCAL: + { + auto local = (ExpressionLocal*) expr; + // RelAssert(mLocals.presents(local->mLocalId) && "undefined local"); + inst(Instruction(OpCode::LOAD_LOCAL, mConstants.get(local->mLocalId))); + break; + } + case Expression::Type::CONST: + { + auto constobj = (ExpressionConst*) expr; + switch (constobj->mConstType) { + case ExpressionConst::STR: + { + inst(Instruction(OpCode::LOAD_CONST, mConstants.get(constobj->str))); + break; + } + case ExpressionConst::INT: + { + inst(Instruction(OpCode::LOAD_CONST, mConstants.get(constobj->integer))); + break; + } + case ExpressionConst::FLT: + { + inst(Instruction(OpCode::LOAD_CONST, mConstants.get(constobj->floating))); + break; + } + case ExpressionConst::BOOL: + { + inst(Instruction(OpCode::LOAD_CONST, mConstants.get(constobj->boolean))); + break; + } + }; + break; + } + case Expression::Type::CHILD: + { + auto child = (ExpressionChild*) expr; + EvalExpr(child->mParent); + inst(Instruction(OpCode::LOAD_CONST, mConstants.get(child->mLocalId))); + inst(Instruction(OpCode::CHILD, child->mMethod, 1)); + break; + } + case Expression::Type::SELF: + { + inst(Instruction(OpCode::SELF)); + break; + } + case Expression::Type::CALL: + { + auto call = (ExpressionCall*) expr; + inst(Instruction(OpCode::PUSH_ARGS, call->mArgs.size(), 1)); + for (auto arg : call->mArgs) { + EvalExpr(arg.data()); + } + EvalExpr(call->mParent); + inst(Instruction(OpCode::CALL)); + break; + } + + default: ASSERT(0) + } + delete expr; +} + +tp::alni instSize(const Instruction& inst) { + switch (inst.mInstType) { + case Instruction::InstType::JUMP: + case Instruction::InstType::JUMP_IF_NOT: + case Instruction::InstType::JUMP_IF: + { + // 2 bytes for offset 1 byte for instrtuction + return 3; + } + case Instruction::InstType::PURE_CONST: + { + return 2; + } + case Instruction::InstType::EXEC: + { + tp::alni out = 1; + switch (inst.mArgType) { + case Instruction::ArgType::PARAM: + { + out += inst.mParamBytes; + return out; + } + case Instruction::ArgType::CONST: + { + out += 2; + if (inst.mConstData2) { + out += 2; + } + return out; + } + case Instruction::ArgType::NO_ARG: + { + return out; + } + default: + { + ASSERT(0); + } + } + } + case Instruction::InstType::NONE: + { + return 0; + } + default: + { + ASSERT(0); + } + } + + ASSERT(0); + return 0; +} + +void writeConst(ByteCode& out, tp::alni& idx, tp::uint2 data) { + for (auto byte : tp::Range(sizeof(tp::uint2))) { + out.mInstructions[idx] = OpCode((tp::int1)(data >> byte * 8)); + idx++; + } +} + +void writeParam(ByteCode& out, tp::alni& idx, tp::int1* data, tp::alni size) { + for (auto byte : tp::Range(size)) { + out.mInstructions[idx] = OpCode(data[byte]); + idx++; + } +} + +tp::alni calcOffset(tp::List::Node* jump_inst, Instruction* to) { + tp::alni offset = 0; + bool reversed = jump_inst->data.mInstIdx > to->mInstIdx; + auto iter_node = reversed ? jump_inst : jump_inst->next; + while (&iter_node->data != to) { + offset += instSize(iter_node->data); + iter_node = reversed ? iter_node->prev : iter_node->next; + } + if (reversed) { + offset += instSize(iter_node->data); + } + return reversed ? -offset : offset; +} + +void FunctionDefinition::generateByteCode(ByteCode& out) { + + out.~ByteCode(); + new (&out) ByteCode(); + + mConstants.save(out.mConstants); + + tp::alni inst_len = 0; + for (auto inst_iter : mInstructions) { + inst_len += instSize(inst_iter.data()); + } + out.mInstructions.reserve(inst_len); + + tp::alni idx = 0; + for (auto inst_iter : mInstructions) { + auto inst = inst_iter.data(); + + switch (inst.mInstType) { + case Instruction::InstType::JUMP_IF: + case Instruction::InstType::JUMP_IF_NOT: + case Instruction::InstType::JUMP: + { + tp::alni offset = calcOffset(inst_iter.node(), inst.mInstTarget); + + if (offset == 0) { + out.mInstructions[idx] = OpCode::NONE; + idx += 3; + break; + } + + if (inst.mInstType == Instruction::InstType::JUMP_IF) { + if (offset > 0) { + out.mInstructions[idx] = OpCode::JUMP_IF; + } else { + out.mInstructions[idx] = OpCode::JUMP_IF_R; + } + } else if (inst.mInstType == Instruction::InstType::JUMP_IF_NOT) { + if (offset > 0) { + out.mInstructions[idx] = OpCode::JUMP_IF_NOT; + } else { + out.mInstructions[idx] = OpCode::JUMP_IF_NOT_R; + } + } else { + if (offset > 0) { + out.mInstructions[idx] = OpCode::JUMP; + } else { + out.mInstructions[idx] = OpCode::JUMP_R; + } + } + + idx++; + + tp::alni offset_mod = abs(offset); + tp::uint2 offset_param = (tp::uint2) offset_mod; + writeParam(out, idx, (tp::int1*) &offset_param, 2); + break; + } + case Instruction::InstType::PURE_CONST: + { + writeConst(out, idx, (tp::uint2) inst.mConstData->mConstIdx); + break; + } + case Instruction::InstType::EXEC: + { + out.mInstructions[idx] = inst.mOp; + idx++; + switch (inst.mArgType) { + case Instruction::ArgType::PARAM: + { + writeParam(out, idx, (tp::int1*) &inst.mParam, inst.mParamBytes); + break; + } + case Instruction::ArgType::CONST: + { + writeConst(out, idx, (tp::uint2) inst.mConstData->mConstIdx); + if (inst.mConstData2) { + writeConst(out, idx, (tp::uint2) inst.mConstData2->mConstIdx); + } + break; + } + case Instruction::ArgType::NO_ARG: + { + break; + } + default: + { + ASSERT(0); + } + } + break; + } + default: + { + ASSERT(0); + } + case Instruction::InstType::NONE: + { + } + } + } +} + +tp::List::Node* FunctionDefinition::inst(Instruction inst) { + mInstructions.pushBack(inst); + auto out = &mInstructions.last()->data; + out->mInstIdx = mInstructions.length() - 1; + return mInstructions.last(); +} + +static Parser* sParger = NULL; + +void obj::BCgen::init() { + ASSERT(!sParger); + if (!sParger) { + sParger = new Parser(); + } +} + +void obj::BCgen::deinit() { + ASSERT(sParger); + if (sParger) { + delete sParger; + sParger = nullptr; + } +} + +bool obj::BCgen::Compile(obj::MethodObject* method) { + + ASSERT(method); + ASSERT(sParger); + + if (!sParger) return false; + + auto script = method->mScript->mReadable->val; + auto res = sParger->parse(script); + + if (res.err) { + // TODO : print parse error + auto loc = res.err->get_err_location(script.read()); + printf("Parser Error (%i,%i): %s\n", loc.head, loc.tail, res.err->mDescr.read()); + // tp::gLogeer->write(tp::sfmt("Parser Error (%i,%i): \n", loc.head, loc.tail), true, tp::Logger::LogEntry::ERR); + // tp::GLog->write(res.err->mDescr, true, tp::Logger::LogEntry::ERR); + return false; + } + + BCgen::Genereate(method->mScript->mBytecode, res.scope); + + delete res.scope; + + return true; } \ No newline at end of file diff --git a/Objects/private/compiler/instruction.cpp b/Objects/private/compiler/instruction.cpp index 8f84870..f82760a 100644 --- a/Objects/private/compiler/instruction.cpp +++ b/Objects/private/compiler/instruction.cpp @@ -1,30 +1,44 @@ - -#include "NewPlacement.hpp" -#include "compiler/instruction.h" - -using namespace obj; -using namespace tp; -using namespace BCgen; - -Instruction::Instruction(OpCode op) : mOp(op), mArgType(ArgType::NO_ARG), mInstType(InstType::EXEC) {} - -Instruction::Instruction() : mInstType(InstType::NONE) {} - -Instruction::Instruction(ConstObject* constData) - : mConstData(constData), mInstType(InstType::PURE_CONST) {} - -Instruction::Instruction(OpCode op, ConstObject* constData) - : mOp(op), mConstData(constData), mArgType(ArgType::CONST), mInstType(InstType::EXEC) { -} - -Instruction::Instruction(OpCode op, ConstObject* constData, ConstObject* constData2) - : mOp(op), mConstData(constData), mConstData2(constData2), mArgType(ArgType::CONST), mInstType(InstType::EXEC) { -} - -Instruction::Instruction(OpCode op, tp::alni param, tp::alni nBytes) - : mOp(op), mParam(param), mArgType(ArgType::PARAM), mParamBytes(nBytes), mInstType(InstType::EXEC) { -} - -Instruction::Instruction(Instruction* inst, InstType jump_type): mInstTarget(inst) { - mInstType = jump_type; + +#include "compiler/instruction.h" +#include "NewPlacement.hpp" + +using namespace obj; +using namespace tp; +using namespace BCgen; + +Instruction::Instruction(OpCode op) : + mOp(op), + mArgType(ArgType::NO_ARG), + mInstType(InstType::EXEC) {} + +Instruction::Instruction() : + mInstType(InstType::NONE) {} + +Instruction::Instruction(ConstObject* constData) : + mConstData(constData), + mInstType(InstType::PURE_CONST) {} + +Instruction::Instruction(OpCode op, ConstObject* constData) : + mOp(op), + mConstData(constData), + mArgType(ArgType::CONST), + mInstType(InstType::EXEC) {} + +Instruction::Instruction(OpCode op, ConstObject* constData, ConstObject* constData2) : + mOp(op), + mConstData(constData), + mConstData2(constData2), + mArgType(ArgType::CONST), + mInstType(InstType::EXEC) {} + +Instruction::Instruction(OpCode op, tp::alni param, tp::alni nBytes) : + mOp(op), + mParam(param), + mArgType(ArgType::PARAM), + mParamBytes(nBytes), + mInstType(InstType::EXEC) {} + +Instruction::Instruction(Instruction* inst, InstType jump_type) : + mInstTarget(inst) { + mInstType = jump_type; } \ No newline at end of file diff --git a/Objects/private/compiler/statement.cpp b/Objects/private/compiler/statement.cpp index 12f442f..67fcb60 100644 --- a/Objects/private/compiler/statement.cpp +++ b/Objects/private/compiler/statement.cpp @@ -1,116 +1,102 @@ -#include "NewPlacement.hpp" -#include "compiler/statement.h" - -using namespace obj; -using namespace BCgen; - - -StatementFuncDef::StatementFuncDef(tp::String function_id, tp::InitialierList args, tp::InitialierList statements) { - mType = Type::DEF_FUNC; - mArgs = args; - mStatements = statements; - mFunctionId = function_id; -} - -StatementLocalDef::StatementLocalDef(tp::String id, Expression* value) : mLocalId(id), mNewExpr(value) { - mType = Type::DEF_LOCAL; -} - -StatementLocalDef::StatementLocalDef(tp::String id, ExpressionConst* value) : mLocalId(id), mConstExpr(value), mIsConstExpr(true) { - mType = Type::DEF_LOCAL; -} - -StatementCopy::StatementCopy(Expression* left, Expression* right) : mLeft(left), mRight(right) { - mType = Type::COPY; -} - -StatementReturn::StatementReturn() { - mType = Type::RET; -} - -StatementReturn::StatementReturn(Expression* ret) : mRet(ret) { - mType = Type::RET; -} - -StatementPrint::StatementPrint(Expression* target) : mTarget(target) { - mType = Type::PRINT; -} - -StatementScope::StatementScope(tp::InitialierList statements, bool aPushToScopeStack) { - mType = Type::SCOPE; - mStatements = statements; - mPushToScopeStack = aPushToScopeStack; -} - -StatementIf::StatementIf(Expression* condition, StatementScope* on_true, StatementScope* on_false) { - mType = Type::IF; - mOnFalse = on_false; - mOnTrue = on_true; - mCondition = condition; -} - -StatementWhile::StatementWhile(Expression* condition, StatementScope* scope) { - mType = Type::WHILE; - mScope = scope; - mCondition = condition; -} - -StatementIgnore::StatementIgnore(Expression* expr) { - mType = Type::IGNORE; - mExpr = expr; -} - -StatementClassDef::StatementClassDef(tp::String class_id, StatementScope* scope) { - mClassId = class_id; - mScope = scope; - mType = Type::CLASS_DEF; -} -// helpers - -StatementFuncDef* obj::BCgen::StmDefFunc(tp::String id, tp::InitialierList args, tp::InitialierList stms) { - return new StatementFuncDef(id, args, stms); -} - -StatementLocalDef* obj::BCgen::StmDefLocal(tp::String id, Expression* value) { - if (value->mType == Expression::Type::CONST) { - return new StatementLocalDef(id, (ExpressionConst*)value); - } - - return new StatementLocalDef(id, value); -} - -StatementCopy* obj::BCgen::StmCopy(Expression* left, Expression* right) { - return new StatementCopy(left, right); -} - -StatementPrint* obj::BCgen::StmPrint(Expression* target) { - return new StatementPrint(target); -} - -StatementReturn* obj::BCgen::StmReturn() { - return new StatementReturn(); -} - -StatementReturn* obj::BCgen::StmReturn(Expression* obj) { - return new StatementReturn(obj); -} - -StatementIf* obj::BCgen::StmIf(Expression* condition, StatementScope* on_true, StatementScope* on_false) { - return new StatementIf(condition, on_true, on_false); -} - -StatementScope* obj::BCgen::StmScope(tp::InitialierList statements, bool aPushToScopeStack = false) { - return new StatementScope(statements, aPushToScopeStack); -} - -StatementWhile* obj::BCgen::StmWhile(Expression* condition, StatementScope* scope) { - return new StatementWhile(condition, scope); -} - -StatementIgnore* obj::BCgen::StmIgnore(Expression* expr) { - return new StatementIgnore(expr); -} - -StatementClassDef* obj::BCgen::StmClassDef(tp::String id, StatementScope* scope) { - return new StatementClassDef(id, scope); -} \ No newline at end of file +#include "compiler/statement.h" +#include "NewPlacement.hpp" + +using namespace obj; +using namespace BCgen; + +StatementFuncDef::StatementFuncDef(tp::String function_id, tp::InitialierList args, tp::InitialierList statements) { + mType = Type::DEF_FUNC; + mArgs = args; + mStatements = statements; + mFunctionId = function_id; +} + +StatementLocalDef::StatementLocalDef(tp::String id, Expression* value) : + mLocalId(id), + mNewExpr(value) { + mType = Type::DEF_LOCAL; +} + +StatementLocalDef::StatementLocalDef(tp::String id, ExpressionConst* value) : + mLocalId(id), + mConstExpr(value), + mIsConstExpr(true) { + mType = Type::DEF_LOCAL; +} + +StatementCopy::StatementCopy(Expression* left, Expression* right) : + mLeft(left), + mRight(right) { + mType = Type::COPY; +} + +StatementReturn::StatementReturn() { mType = Type::RET; } + +StatementReturn::StatementReturn(Expression* ret) : + mRet(ret) { + mType = Type::RET; +} + +StatementPrint::StatementPrint(Expression* target) : + mTarget(target) { + mType = Type::PRINT; +} + +StatementScope::StatementScope(tp::InitialierList statements, bool aPushToScopeStack) { + mType = Type::SCOPE; + mStatements = statements; + mPushToScopeStack = aPushToScopeStack; +} + +StatementIf::StatementIf(Expression* condition, StatementScope* on_true, StatementScope* on_false) { + mType = Type::IF; + mOnFalse = on_false; + mOnTrue = on_true; + mCondition = condition; +} + +StatementWhile::StatementWhile(Expression* condition, StatementScope* scope) { + mType = Type::WHILE; + mScope = scope; + mCondition = condition; +} + +StatementIgnore::StatementIgnore(Expression* expr) { + mType = Type::IGNORE; + mExpr = expr; +} + +StatementClassDef::StatementClassDef(tp::String class_id, StatementScope* scope) { + mClassId = class_id; + mScope = scope; + mType = Type::CLASS_DEF; +} +// helpers + +StatementFuncDef* obj::BCgen::StmDefFunc(tp::String id, tp::InitialierList args, tp::InitialierList stms) { return new StatementFuncDef(id, args, stms); } + +StatementLocalDef* obj::BCgen::StmDefLocal(tp::String id, Expression* value) { + if (value->mType == Expression::Type::CONST) { + return new StatementLocalDef(id, (ExpressionConst*) value); + } + + return new StatementLocalDef(id, value); +} + +StatementCopy* obj::BCgen::StmCopy(Expression* left, Expression* right) { return new StatementCopy(left, right); } + +StatementPrint* obj::BCgen::StmPrint(Expression* target) { return new StatementPrint(target); } + +StatementReturn* obj::BCgen::StmReturn() { return new StatementReturn(); } + +StatementReturn* obj::BCgen::StmReturn(Expression* obj) { return new StatementReturn(obj); } + +StatementIf* obj::BCgen::StmIf(Expression* condition, StatementScope* on_true, StatementScope* on_false) { return new StatementIf(condition, on_true, on_false); } + +StatementScope* obj::BCgen::StmScope(tp::InitialierList statements, bool aPushToScopeStack = false) { return new StatementScope(statements, aPushToScopeStack); } + +StatementWhile* obj::BCgen::StmWhile(Expression* condition, StatementScope* scope) { return new StatementWhile(condition, scope); } + +StatementIgnore* obj::BCgen::StmIgnore(Expression* expr) { return new StatementIgnore(expr); } + +StatementClassDef* obj::BCgen::StmClassDef(tp::String id, StatementScope* scope) { return new StatementClassDef(id, scope); } \ No newline at end of file diff --git a/Objects/private/core/module.cpp b/Objects/private/core/module.cpp index 91d09e2..538f87f 100644 --- a/Objects/private/core/module.cpp +++ b/Objects/private/core/module.cpp @@ -1,92 +1,91 @@ - -#include "NewPlacement.hpp" - -#include "Tokenizer.hpp" - -#include "compiler/function.h" - -#include "primitives/boolobject.h" -#include "primitives/classobject.h" -#include "primitives/colorobject.h" -#include "primitives/dictobject.h" -#include "primitives/enumobject.h" -#include "primitives/floatobject.h" -#include "primitives/interpreterobject.h" -#include "primitives/intobject.h" -#include "primitives/linkobject.h" -#include "primitives/listobject.h" -#include "primitives/methodobject.h" -#include "primitives/nullobject.h" -#include "primitives/stringobject.h" -#include "primitives/typeobject.h" - -using namespace obj; -using namespace tp; - -static void defineTypes() { - NDO->define(&DictObject::TypeData); - NDO->define(&IntObject::TypeData); - NDO->define(&LinkObject::TypeData); - NDO->define(&ListObject::TypeData); - NDO->define(&NullObject::TypeData); - NDO->define(&StringObject::TypeData); - NDO->define(&BoolObject::TypeData); - NDO->define(&FloatObject::TypeData); - NDO->define(&EnumObject::TypeData); - NDO->define(&ClassObject::TypeData); - NDO->define(&ColorObject::TypeData); - NDO->define(&InterpreterObject::TypeData); - NDO->define(&TypeObject::TypeData); -} - -static void defineGroups() { - NDO->type_groups.addType(&DictObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&IntObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&LinkObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&ListObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&NullObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&StringObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&BoolObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&FloatObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&EnumObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&ClassObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&ColorObject::TypeData, {"Primitives"}); - NDO->type_groups.addType(&InterpreterObject::TypeData, { "scripting" }); -} - - -static bool init(const tp::ModuleManifest*) { - if (!NDO) NDO = new objects_api(); - obj::BCgen::init(); - - MethodObject::Initialize(); - - defineTypes(); - defineGroups(); - - return true; -} - -static void deinit(const tp::ModuleManifest*) { - - NullObject::uninit(); - MethodObject::UnInitialize(); - - obj::BCgen::deinit(); - - assertNoLeaks(); - - delete NDO; - NDO = nullptr; -} - -static tp::ModuleManifest* sModuleDependencies[] = { - // &tp::gModuleCompressor, - &tp::gModuleMath, - &tp::gModuleStrings, - &tp::gModuleTokenizer, - &tp::gModuleConnection, - NULL -}; - + +#include "NewPlacement.hpp" + +#include "Tokenizer.hpp" + +#include "compiler/function.h" + +#include "primitives/boolobject.h" +#include "primitives/classobject.h" +#include "primitives/colorobject.h" +#include "primitives/dictobject.h" +#include "primitives/enumobject.h" +#include "primitives/floatobject.h" +#include "primitives/interpreterobject.h" +#include "primitives/intobject.h" +#include "primitives/linkobject.h" +#include "primitives/listobject.h" +#include "primitives/methodobject.h" +#include "primitives/nullobject.h" +#include "primitives/stringobject.h" +#include "primitives/typeobject.h" + +using namespace obj; +using namespace tp; + +static void defineTypes() { + NDO->define(&DictObject::TypeData); + NDO->define(&IntObject::TypeData); + NDO->define(&LinkObject::TypeData); + NDO->define(&ListObject::TypeData); + NDO->define(&NullObject::TypeData); + NDO->define(&StringObject::TypeData); + NDO->define(&BoolObject::TypeData); + NDO->define(&FloatObject::TypeData); + NDO->define(&EnumObject::TypeData); + NDO->define(&ClassObject::TypeData); + NDO->define(&ColorObject::TypeData); + NDO->define(&InterpreterObject::TypeData); + NDO->define(&TypeObject::TypeData); +} + +static void defineGroups() { + NDO->type_groups.addType(&DictObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&IntObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&LinkObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&ListObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&NullObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&StringObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&BoolObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&FloatObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&EnumObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&ClassObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&ColorObject::TypeData, { "Primitives" }); + NDO->type_groups.addType(&InterpreterObject::TypeData, { "scripting" }); +} + +static bool init(const tp::ModuleManifest*) { + if (!NDO) NDO = new objects_api(); + obj::BCgen::init(); + + MethodObject::Initialize(); + + defineTypes(); + defineGroups(); + + return true; +} + +static void deinit(const tp::ModuleManifest*) { + + NullObject::uninit(); + MethodObject::UnInitialize(); + + obj::BCgen::deinit(); + + assertNoLeaks(); + + delete NDO; + NDO = nullptr; +} + +static tp::ModuleManifest* sModuleDependencies[] = { + // &tp::gModuleCompressor, + &tp::gModuleMath, + &tp::gModuleStrings, + &tp::gModuleTokenizer, + &tp::gModuleConnection, + NULL +}; + tp::ModuleManifest obj::gModuleObjects = tp::ModuleManifest("Objects", init, deinit, sModuleDependencies); \ No newline at end of file diff --git a/Objects/private/core/object.cpp b/Objects/private/core/object.cpp index c2f8f90..a78e69b 100644 --- a/Objects/private/core/object.cpp +++ b/Objects/private/core/object.cpp @@ -1,230 +1,227 @@ - - -#include "NewPlacement.hpp" - -#include "core/object.h" - -#include "primitives/nullobject.h" -#include "primitives/classobject.h" -#include "primitives/methodobject.h" - -#include "interpreter/interpreter.h" -#include "compiler/function.h" - -namespace obj { - - Object* ObjectMemAllocate(const ObjectType* type); - void ObjectMemDeallocate(Object* in); - - objects_api* NDO = NULL; - - void hierarchy_copy(Object* self, const Object* in, const ObjectType* type); - void hierarchy_construct(Object* self, const ObjectType* type); - - objects_api::objects_api() { - tp::memSetVal(sl_callbacks, SAVE_LOAD_MAX_CALLBACK_SLOTS * sizeof(save_load_callbacks*), 0); - interp = new Interpreter(); - } - - objects_api::~objects_api() { - delete interp; - } - - void objects_api::define(ObjectType* type) { - MODULE_SANITY_CHECK(gModuleObjects); - - DEBUG_ASSERT(NDO && "using uninitialize objects api"); - DEBUG_ASSERT(!types.presents(type->name) && "Type Redefinition"); - types.put(type->name, type); - - type->type_methods.init(); - } - - Object* objects_api::create(const tp::String& name) { - MODULE_SANITY_CHECK(gModuleObjects); - - const ObjectType* type = types.get(name); - - Object* obj_instance = ObjectMemAllocate(type); - - if (!obj_instance) { - return NULL; - } - - hierarchy_construct(obj_instance, obj_instance->type); - - setrefc(obj_instance, 0); - - NDO_CASTV(ClassObject, obj_instance, classobj); - if (classobj) { - auto idx = classobj->members->presents("__init__"); - DEBUG_ASSERT(idx); - if (idx) { - auto constructor_obj = classobj->members->getSlotVal(idx); - NDO_CASTV(MethodObject, constructor_obj, constructor_method); - if (constructor_method) { - interp->execAll(constructor_method, classobj); - } - } - } - - return obj_instance; - } - - Object* objects_api::copy(Object* self, const Object* in) { - if (self->type != in->type) { - return NULL; - } - - hierarchy_copy(self, in, self->type); - - return self; - } - - bool objects_api::compare(Object* first, Object* second) { - if (first->type == second->type) { - if (first->type->comparison) { - return first->type->comparison(first, second); - } - - // raw data comparison - return tp::memCompare(first, second, first->type->size) == 0; - } - - return false; - } - - Object* objects_api::instatiate(Object* in) { - obj::Object* obj = NDO->create(in->type->name); - NDO->copy(obj, in); - return obj; - } - - void objects_api::set(Object* self, tp::alni val) { - if (self->type->convesions && self->type->convesions->from_int) { - self->type->convesions->from_int(self, val); - return; - } - } - - void objects_api::set(Object* self, tp::alnf val) { - if (self->type->convesions && self->type->convesions->from_float) { - self->type->convesions->from_float(self, val); - return; - } - } - - void objects_api::set(Object* self, tp::String val) { - if (self->type->convesions && self->type->convesions->from_string) { - self->type->convesions->from_string(self, val); - return; - } - } - - tp::alni objects_api::toInt(Object* self) { - DEBUG_ASSERT(self->type->convesions && self->type->convesions->to_int); - return self->type->convesions->to_int(self); - } - - tp::alnf objects_api::toFloat(Object* self) { - DEBUG_ASSERT(self->type->convesions && self->type->convesions->to_float); - return self->type->convesions->to_float(self); - } - - bool objects_api::toBool(Object* self) { - if (self->type->convesions && self->type->convesions->to_int) { - return (bool) self->type->convesions->to_int(self); - } - return true; - } - - tp::String objects_api::toString(Object* self) { - DEBUG_ASSERT(self->type->convesions && self->type->convesions->to_string); - return self->type->convesions->to_string(self); - } - - void objects_api::destroy(Object* in) { - - if (!in) { - return; - } - - #ifdef OBJECT_REF_COUNT - ObjectMemHead* mh = NDO_MEMH_FROM_NDO(in); - if (mh->refc > 1) { - mh->refc--; - return; - } - #endif - - NDO_CASTV(ClassObject, in, classobj); - if (classobj) { - auto idx = classobj->members->presents("__del__"); - DEBUG_ASSERT(idx); - if (idx) { - auto constructor_obj = classobj->members->getSlotVal(idx); - NDO_CASTV(MethodObject, constructor_obj, constructor_method); - if (constructor_method) { - interp->execAll(constructor_method, classobj); - } - } - } - - for (const ObjectType* iter = in->type; iter; iter = iter->base) { - if (iter->destructor) { - iter->destructor(in); - } - } - - ObjectMemDeallocate(in); - } - - #ifdef OBJECT_REF_COUNT - tp::halni objects_api::getrefc(Object* in) { - ObjectMemHead* mh = NDO_MEMH_FROM_NDO(in); - return (tp::halni)mh->refc; - } - - void objects_api::refinc(Object* in) { - ObjectMemHead* mh = NDO_MEMH_FROM_NDO(in); - mh->refc++; - } - - void objects_api::setrefc(Object* in, tp::halni refc) { - ObjectMemHead* mh = NDO_MEMH_FROM_NDO(in); - mh->refc = refc; - } - #endif - - - void hierarchy_copy(Object* self, const Object* in, const ObjectType* type) { - if (type->base) { - hierarchy_copy(self, in, type->base); - } - - if (type->copy) { - type->copy(self, in); - } - } - - void hierarchy_construct(Object* self, const ObjectType* type) { - if (type->base) { - hierarchy_construct(self, type->base); - } - - if (type->constructor) { - type->constructor(self); - } - } - - Object* ndo_cast(const Object* in, const ObjectType* to_type) { - const ObjectType* typeiter = in->type; - while (typeiter) { - if (typeiter == to_type) { - return (Object*) in; - } - typeiter = typeiter->base; - } - return NULL; - } + + +#include "NewPlacement.hpp" + +#include "core/object.h" + +#include "primitives/classobject.h" +#include "primitives/methodobject.h" +#include "primitives/nullobject.h" + +#include "compiler/function.h" +#include "interpreter/interpreter.h" + +namespace obj { + + Object* ObjectMemAllocate(const ObjectType* type); + void ObjectMemDeallocate(Object* in); + + objects_api* NDO = NULL; + + void hierarchy_copy(Object* self, const Object* in, const ObjectType* type); + void hierarchy_construct(Object* self, const ObjectType* type); + + objects_api::objects_api() { + tp::memSetVal(sl_callbacks, SAVE_LOAD_MAX_CALLBACK_SLOTS * sizeof(save_load_callbacks*), 0); + interp = new Interpreter(); + } + + objects_api::~objects_api() { delete interp; } + + void objects_api::define(ObjectType* type) { + MODULE_SANITY_CHECK(gModuleObjects); + + DEBUG_ASSERT(NDO && "using uninitialize objects api"); + DEBUG_ASSERT(!types.presents(type->name) && "Type Redefinition"); + types.put(type->name, type); + + type->type_methods.init(); + } + + Object* objects_api::create(const tp::String& name) { + MODULE_SANITY_CHECK(gModuleObjects); + + const ObjectType* type = types.get(name); + + Object* obj_instance = ObjectMemAllocate(type); + + if (!obj_instance) { + return NULL; + } + + hierarchy_construct(obj_instance, obj_instance->type); + + setrefc(obj_instance, 0); + + NDO_CASTV(ClassObject, obj_instance, classobj); + if (classobj) { + auto idx = classobj->members->presents("__init__"); + DEBUG_ASSERT(idx); + if (idx) { + auto constructor_obj = classobj->members->getSlotVal(idx); + NDO_CASTV(MethodObject, constructor_obj, constructor_method); + if (constructor_method) { + interp->execAll(constructor_method, classobj); + } + } + } + + return obj_instance; + } + + Object* objects_api::copy(Object* self, const Object* in) { + if (self->type != in->type) { + return NULL; + } + + hierarchy_copy(self, in, self->type); + + return self; + } + + bool objects_api::compare(Object* first, Object* second) { + if (first->type == second->type) { + if (first->type->comparison) { + return first->type->comparison(first, second); + } + + // raw data comparison + return tp::memCompare(first, second, first->type->size) == 0; + } + + return false; + } + + Object* objects_api::instatiate(Object* in) { + obj::Object* obj = NDO->create(in->type->name); + NDO->copy(obj, in); + return obj; + } + + void objects_api::set(Object* self, tp::alni val) { + if (self->type->convesions && self->type->convesions->from_int) { + self->type->convesions->from_int(self, val); + return; + } + } + + void objects_api::set(Object* self, tp::alnf val) { + if (self->type->convesions && self->type->convesions->from_float) { + self->type->convesions->from_float(self, val); + return; + } + } + + void objects_api::set(Object* self, tp::String val) { + if (self->type->convesions && self->type->convesions->from_string) { + self->type->convesions->from_string(self, val); + return; + } + } + + tp::alni objects_api::toInt(Object* self) { + DEBUG_ASSERT(self->type->convesions && self->type->convesions->to_int); + return self->type->convesions->to_int(self); + } + + tp::alnf objects_api::toFloat(Object* self) { + DEBUG_ASSERT(self->type->convesions && self->type->convesions->to_float); + return self->type->convesions->to_float(self); + } + + bool objects_api::toBool(Object* self) { + if (self->type->convesions && self->type->convesions->to_int) { + return (bool) self->type->convesions->to_int(self); + } + return true; + } + + tp::String objects_api::toString(Object* self) { + DEBUG_ASSERT(self->type->convesions && self->type->convesions->to_string); + return self->type->convesions->to_string(self); + } + + void objects_api::destroy(Object* in) { + + if (!in) { + return; + } + +#ifdef OBJECT_REF_COUNT + ObjectMemHead* mh = NDO_MEMH_FROM_NDO(in); + if (mh->refc > 1) { + mh->refc--; + return; + } +#endif + + NDO_CASTV(ClassObject, in, classobj); + if (classobj) { + auto idx = classobj->members->presents("__del__"); + DEBUG_ASSERT(idx); + if (idx) { + auto constructor_obj = classobj->members->getSlotVal(idx); + NDO_CASTV(MethodObject, constructor_obj, constructor_method); + if (constructor_method) { + interp->execAll(constructor_method, classobj); + } + } + } + + for (const ObjectType* iter = in->type; iter; iter = iter->base) { + if (iter->destructor) { + iter->destructor(in); + } + } + + ObjectMemDeallocate(in); + } + +#ifdef OBJECT_REF_COUNT + tp::halni objects_api::getrefc(Object* in) { + ObjectMemHead* mh = NDO_MEMH_FROM_NDO(in); + return (tp::halni) mh->refc; + } + + void objects_api::refinc(Object* in) { + ObjectMemHead* mh = NDO_MEMH_FROM_NDO(in); + mh->refc++; + } + + void objects_api::setrefc(Object* in, tp::halni refc) { + ObjectMemHead* mh = NDO_MEMH_FROM_NDO(in); + mh->refc = refc; + } +#endif + + void hierarchy_copy(Object* self, const Object* in, const ObjectType* type) { + if (type->base) { + hierarchy_copy(self, in, type->base); + } + + if (type->copy) { + type->copy(self, in); + } + } + + void hierarchy_construct(Object* self, const ObjectType* type) { + if (type->base) { + hierarchy_construct(self, type->base); + } + + if (type->constructor) { + type->constructor(self); + } + } + + Object* ndo_cast(const Object* in, const ObjectType* to_type) { + const ObjectType* typeiter = in->type; + while (typeiter) { + if (typeiter == to_type) { + return (Object*) in; + } + typeiter = typeiter->base; + } + return NULL; + } }; \ No newline at end of file diff --git a/Objects/private/core/objectsave.cpp b/Objects/private/core/objectsave.cpp index adc57b4..7d2cf8f 100644 --- a/Objects/private/core/objectsave.cpp +++ b/Objects/private/core/objectsave.cpp @@ -1,444 +1,435 @@ - - -#include "NewPlacement.hpp" -#include "core/object.h" - -#include "primitives/nullobject.h" - -#include "HeapAllocatorGlobal.hpp" - -#include - -namespace obj { - - ObjectMemHead* bottom = nullptr; - - struct ObjectsFileHeader { - char name[10] = {0}; - char version[10] = {0}; - - ObjectsFileHeader(bool default_val = true) { - if (default_val) { - tp::memCopy(&name, "objects", tp::String::Logic::calcLength("objects") + 1); - tp::memCopy(&version, "0", tp::String::Logic::calcLength("0") + 1); - } - } - }; - - - Object* ObjectMemAllocate(const ObjectType* type) { - ObjectMemHead* memh = (ObjectMemHead*) tp::HeapAllocGlobal::allocate(type->size + sizeof(ObjectMemHead)); - if (!memh) { - return NULL; - } - - memh->down = NULL; - memh->flags = 0; - - #ifdef OBJECT_REF_COUNT - memh->refc = (tp::alni) 1; - #endif - - if (bottom) { - bottom->down = memh; - } - memh->up = bottom; - bottom = memh; - - NDO_FROM_MEMH(memh)->type = type; - return NDO_FROM_MEMH(memh); - } - - void ObjectMemDeallocate(Object* in) { - ObjectMemHead* memh = ((ObjectMemHead*) in) - 1; - - if (memh->up) { - memh->up->down = memh->down; - } - - if (memh->down) { - memh->down->up = memh->up; - } else { - bottom = memh->up; - } - - tp::HeapAllocGlobal::deallocate(memh); - } - - void logTypeData(const ObjectType* type) { - printf("type - %s\n", type->name); - if (type->base) { - printf("Based on "); - logTypeData(type->base); - } - } - - void assertNoLeaks() { - if (bottom) { - printf("ERROR : not all objects are destroyed\n"); - tp::ualni idx = 0; - for (ObjectMemHead* memh = bottom; memh; memh = memh->up) { - printf(" ===== Object - %i. Ref count - %i ===== \n", idx, memh->refc); - logTypeData(NDO_FROM_MEMH(memh)->type); - idx++; - } - } - } - - - struct ObjectFileHead { - Object* load_head_adress = 0; - tp::halni refc = 0; - }; - - tp::int1* loaded_file = nullptr; - - - void objects_api::clear_object_flags() { - // clear all object flags - for (ObjectMemHead* iter = bottom; iter; iter = iter->up) { - iter->flags = -1; - } - } - - tp::alni& getObjectFlags(Object* in) { - return NDO_MEMH_FROM_NDO(in)->flags; - } - - tp::alni objsize_ram_util(Object* self, const ObjectType* type) { - tp::alni out = 0; - - if (type->allocated_size) { - out += type->allocated_size(self); - } else { - out += type->size - sizeof(ObjectType*); - } - - if (type->base) { - out += objsize_ram_util(self, type->base); - } else { - out += sizeof(ObjectType*); - } - - return out; - } - - tp::alni objects_api::objsize_ram(Object* self) { - return objsize_ram_util(self, self->type); - } - - tp::alni objects_api::objsize_ram_recursive_util(Object* self, const ObjectType* type, bool different_object) { - tp::alni out = 0; - - if (different_object) { - if (getObjectFlags(self) == 1) { - return 0; - } - - getObjectFlags(self) = 1; - } - - if (type->allocated_size_recursive) { - out += type->allocated_size_recursive(self); - } else { - if (type->allocated_size) { - out += type->allocated_size(self); - } else { - out += type->size - sizeof(ObjectType*); - } - } - - if (type->base) { - out += objsize_ram_recursive_util(self, type->base, false); - } else { - out += sizeof(ObjectType*); - } - - return out; - } - - tp::alni objects_api::objsize_ram_recursive(Object* self) { - clear_object_flags(); - return objsize_ram_recursive_util(self, self->type); - } - - tp::alni objsize_file_util(Object* self, const ObjectType* type) { - tp::alni out = 0; - - if (type->save_size) { - out += type->save_size(self); - } - - if (type->base) { - out += objsize_file_util(self, type->base); - } - return out; - } - - tp::alni objects_api::objsize_file(Object* self) { - return objsize_file_util(self, self->type); - } - - tp::alni objsize_file_recursive_util(Object* self, const ObjectType* type) { - tp::alni out = 0; - - getObjectFlags(self) = 1; - - if (type->save_size) { - out += type->save_size(self); - } - - if (type->childs_retrival) { - tp::Buffer childs = type->childs_retrival(self); - for (auto child : childs) { - if (getObjectFlags(child.data()) != 1) { - out += objsize_file_recursive_util(child.data(), child.data()->type); - } - } - } - - if (type->base) { - out += objsize_file_recursive_util(self, type->base); - } - - return out; - } - - tp::alni objects_api::objsize_file_recursive(Object* self) { - clear_object_flags(); - return objsize_file_recursive_util(self, self->type); - } - - void object_recursive_save(ArchiverOut& ndf, Object* self, const ObjectType* type) { - if (type->base) { - object_recursive_save(ndf, self, type->base); - } - - // automatically offsets for parent type to write - if (type->save) { - type->save(self, ndf); - } - } - - tp::alni objects_api::save(ArchiverOut& ndf, Object* in) { - // if already saved return file_adress - if (NDO_MEMH_FROM_NDO(in)->flags != -1) { - return NDO_MEMH_FROM_NDO(in)->flags; - } - - // save write adress for parent save function call - tp::alni tmp_adress = ndf.getAddress(); - - // save requested object to first available adress - tp::alni save_adress = ndf.getFreeAddress(); - - // save file_adress in memhead - NDO_MEMH_FROM_NDO(in)->flags = save_adress; - - // update write adress - ndf.setAddress(save_adress); - - // save file object header - ObjectFileHead ofh = { 0, getrefc(in) }; - ndf << ofh; - ndf << tp::String(in->type->name); - - // allocate for object file header - ndf.setFreeAddress(ndf.getFreeAddress() + sizeof(ObjectFileHead) + tp::SaveSizeCounter::calc(tp::String(in->type->name))); - - // calc max size needed for saving all hierarchy of types - tp::alni file_alloc_size = objsize_file_util(in, in->type); - - // offes first available adress - ndf.setFreeAddress(ndf.getFreeAddress() + file_alloc_size); - - object_recursive_save(ndf, in, in->type); - - // restore adress for parent save function - ndf.setAddress(tmp_adress); - - // return addres of saved object in file space - return save_adress; - } - - void object_recursive_load(ArchiverIn& ndf, Object* out, const ObjectType* type) { - if (type->base) { - object_recursive_load(ndf, out, type->base); - } - - // automatically offsets for parent type to read - if (type->load) { - type->load(ndf, out); - } - } - - Object* objects_api::load(ArchiverIn& ndf, tp::alni file_adress) { - // check if already saved - if (((ObjectFileHead*) (loaded_file + file_adress))->load_head_adress) { - return ((ObjectFileHead*) (loaded_file + file_adress))->load_head_adress; - } - - // save read address - tp::alni parent_file_adress = ndf.getAddress(); - - // set read address - ndf.setAddress(file_adress); - - ObjectFileHead ofh; - ndf >> ofh; - - tp::String type_name; - ndf >> type_name; - - const ObjectType* object_type = NDO->types.get(type_name); - Object* out = ObjectMemAllocate(object_type); - - if (!out) { - return NULL; - } - - setrefc(out, 0); - - // check for null object - if (out->type == &NullObject::TypeData) { - ObjectMemDeallocate(out); - out = NdoNull_globalInstance; - } - - // save heap adress in "loaded_file" - ((ObjectFileHead*) (loaded_file + file_adress))->load_head_adress = out; - - // loads recursively - object_recursive_load(ndf, out, object_type); - - // restore read address for parent call to continue - ndf.setAddress(parent_file_adress); - - // return heap memory adress - return out; - } - - bool objects_api::save(Object* in, tp::String path, bool compressed) { - ArchiverOut ndf(path.read()); - - if (!ndf.isOpened()) { - return false; - } - - clear_object_flags(); - - // save version info - ObjectsFileHeader header; - ndf << header; - - ndf.setFreeAddress(ndf.getAddress()); - - // pre allocate - for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { - if (sl_callbacks[i]) { - DEBUG_ASSERT(sl_callbacks[i]->size); - ndf.setFreeAddress(ndf.getFreeAddress() + sl_callbacks[i]->size(sl_callbacks[i]->self, ndf)); - } - } - - // pre-save - for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { - if (sl_callbacks[i] && sl_callbacks[i]->pre_save) { - sl_callbacks[i]->pre_save(sl_callbacks[i]->self, ndf); - } - } - - save(ndf, in); - - // post-save - for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { - if (sl_callbacks[i] && sl_callbacks[i]->post_save) { - sl_callbacks[i]->post_save(sl_callbacks[i]->self, ndf); - } - } - - // TODO : add compression - /* - if (compressed) { - auto temp = path + ".bz2"; - tp::compressF2F(path.read(), temp.cstr()); - - File::remove(path.read()); - File::rename(temp.cstr(), path.read()); - } - */ - - return true; - } - - Object* objects_api::load(tp::String path) { - /* - auto temp_file_name = path + ".unz"; - bool unz_res = tp::decompressF2F(path.cstr(), temp_file_name.cstr()); - - if (!unz_res) { - return NULL; - } - - File ndf(temp_file_name.cstr(), tp::osfile_openflags::LOAD); - */ - - ArchiverIn ndf(path.read()); - - if (!ndf.isOpened()) { - return NULL; - } - - // check for compatibility - ObjectsFileHeader current_header; - ObjectsFileHeader loaded_header(false); - - ndf >> loaded_header; - - if (!tp::memEqual(¤t_header, &loaded_header, sizeof(ObjectsFileHeader))) { - return NULL; - } - - ndf.setAddress(0); - - const auto fileSize = ndf.getSize(); - loaded_file = (tp::int1*) malloc(fileSize); - tp::memSetVal(loaded_file, fileSize, 0); - ndf.readBytes(loaded_file, fileSize); - - ndf.setAddress(sizeof(ObjectsFileHeader)); - - // preload - for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { - if (sl_callbacks[i] && sl_callbacks[i]->pre_load) { - sl_callbacks[i]->pre_load(sl_callbacks[i]->self, ndf); - } - } - - Object* out = load(ndf, ndf.getAddress()); - - // post - for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { - if (sl_callbacks[i] && sl_callbacks[i]->post_save) { - sl_callbacks[i]->post_load(sl_callbacks[i]->self, ndf); - } - } - - free(loaded_file); - - /* - ndf.close(); - - if (unz_res == NULL) { - File::remove(temp_file_name.cstr()); - } - */ - - return out; - } - - void objects_api::add_sl_callbacks(save_load_callbacks* in) { - sl_callbacks[sl_callbacks_load_idx] = in; - sl_callbacks_load_idx++; - } + + +#include "NewPlacement.hpp" +#include "core/object.h" + +#include "primitives/nullobject.h" + +#include "HeapAllocatorGlobal.hpp" + +#include + +namespace obj { + + ObjectMemHead* bottom = nullptr; + + struct ObjectsFileHeader { + char name[10] = { 0 }; + char version[10] = { 0 }; + + ObjectsFileHeader(bool default_val = true) { + if (default_val) { + tp::memCopy(&name, "objects", tp::String::Logic::calcLength("objects") + 1); + tp::memCopy(&version, "0", tp::String::Logic::calcLength("0") + 1); + } + } + }; + + Object* ObjectMemAllocate(const ObjectType* type) { + ObjectMemHead* memh = (ObjectMemHead*) tp::HeapAllocGlobal::allocate(type->size + sizeof(ObjectMemHead)); + if (!memh) { + return NULL; + } + + memh->down = NULL; + memh->flags = 0; + +#ifdef OBJECT_REF_COUNT + memh->refc = (tp::alni) 1; +#endif + + if (bottom) { + bottom->down = memh; + } + memh->up = bottom; + bottom = memh; + + NDO_FROM_MEMH(memh)->type = type; + return NDO_FROM_MEMH(memh); + } + + void ObjectMemDeallocate(Object* in) { + ObjectMemHead* memh = ((ObjectMemHead*) in) - 1; + + if (memh->up) { + memh->up->down = memh->down; + } + + if (memh->down) { + memh->down->up = memh->up; + } else { + bottom = memh->up; + } + + tp::HeapAllocGlobal::deallocate(memh); + } + + void logTypeData(const ObjectType* type) { + printf("type - %s\n", type->name); + if (type->base) { + printf("Based on "); + logTypeData(type->base); + } + } + + void assertNoLeaks() { + if (bottom) { + printf("ERROR : not all objects are destroyed\n"); + tp::ualni idx = 0; + for (ObjectMemHead* memh = bottom; memh; memh = memh->up) { + printf(" ===== Object - %i. Ref count - %i ===== \n", idx, memh->refc); + logTypeData(NDO_FROM_MEMH(memh)->type); + idx++; + } + } + } + + struct ObjectFileHead { + Object* load_head_adress = 0; + tp::halni refc = 0; + }; + + tp::int1* loaded_file = nullptr; + + void objects_api::clear_object_flags() { + // clear all object flags + for (ObjectMemHead* iter = bottom; iter; iter = iter->up) { + iter->flags = -1; + } + } + + tp::alni& getObjectFlags(Object* in) { return NDO_MEMH_FROM_NDO(in)->flags; } + + tp::alni objsize_ram_util(Object* self, const ObjectType* type) { + tp::alni out = 0; + + if (type->allocated_size) { + out += type->allocated_size(self); + } else { + out += type->size - sizeof(ObjectType*); + } + + if (type->base) { + out += objsize_ram_util(self, type->base); + } else { + out += sizeof(ObjectType*); + } + + return out; + } + + tp::alni objects_api::objsize_ram(Object* self) { return objsize_ram_util(self, self->type); } + + tp::alni objects_api::objsize_ram_recursive_util(Object* self, const ObjectType* type, bool different_object) { + tp::alni out = 0; + + if (different_object) { + if (getObjectFlags(self) == 1) { + return 0; + } + + getObjectFlags(self) = 1; + } + + if (type->allocated_size_recursive) { + out += type->allocated_size_recursive(self); + } else { + if (type->allocated_size) { + out += type->allocated_size(self); + } else { + out += type->size - sizeof(ObjectType*); + } + } + + if (type->base) { + out += objsize_ram_recursive_util(self, type->base, false); + } else { + out += sizeof(ObjectType*); + } + + return out; + } + + tp::alni objects_api::objsize_ram_recursive(Object* self) { + clear_object_flags(); + return objsize_ram_recursive_util(self, self->type); + } + + tp::alni objsize_file_util(Object* self, const ObjectType* type) { + tp::alni out = 0; + + if (type->save_size) { + out += type->save_size(self); + } + + if (type->base) { + out += objsize_file_util(self, type->base); + } + return out; + } + + tp::alni objects_api::objsize_file(Object* self) { return objsize_file_util(self, self->type); } + + tp::alni objsize_file_recursive_util(Object* self, const ObjectType* type) { + tp::alni out = 0; + + getObjectFlags(self) = 1; + + if (type->save_size) { + out += type->save_size(self); + } + + if (type->childs_retrival) { + tp::Buffer childs = type->childs_retrival(self); + for (auto child : childs) { + if (getObjectFlags(child.data()) != 1) { + out += objsize_file_recursive_util(child.data(), child.data()->type); + } + } + } + + if (type->base) { + out += objsize_file_recursive_util(self, type->base); + } + + return out; + } + + tp::alni objects_api::objsize_file_recursive(Object* self) { + clear_object_flags(); + return objsize_file_recursive_util(self, self->type); + } + + void object_recursive_save(ArchiverOut& ndf, Object* self, const ObjectType* type) { + if (type->base) { + object_recursive_save(ndf, self, type->base); + } + + // automatically offsets for parent type to write + if (type->save) { + type->save(self, ndf); + } + } + + tp::alni objects_api::save(ArchiverOut& ndf, Object* in) { + // if already saved return file_adress + if (NDO_MEMH_FROM_NDO(in)->flags != -1) { + return NDO_MEMH_FROM_NDO(in)->flags; + } + + // save write adress for parent save function call + tp::alni tmp_adress = ndf.getAddress(); + + // save requested object to first available adress + tp::alni save_adress = ndf.getFreeAddress(); + + // save file_adress in memhead + NDO_MEMH_FROM_NDO(in)->flags = save_adress; + + // update write adress + ndf.setAddress(save_adress); + + // save file object header + ObjectFileHead ofh = { 0, getrefc(in) }; + ndf << ofh; + ndf << tp::String(in->type->name); + + // allocate for object file header + ndf.setFreeAddress(ndf.getFreeAddress() + sizeof(ObjectFileHead) + tp::SaveSizeCounter::calc(tp::String(in->type->name))); + + // calc max size needed for saving all hierarchy of types + tp::alni file_alloc_size = objsize_file_util(in, in->type); + + // offes first available adress + ndf.setFreeAddress(ndf.getFreeAddress() + file_alloc_size); + + object_recursive_save(ndf, in, in->type); + + // restore adress for parent save function + ndf.setAddress(tmp_adress); + + // return addres of saved object in file space + return save_adress; + } + + void object_recursive_load(ArchiverIn& ndf, Object* out, const ObjectType* type) { + if (type->base) { + object_recursive_load(ndf, out, type->base); + } + + // automatically offsets for parent type to read + if (type->load) { + type->load(ndf, out); + } + } + + Object* objects_api::load(ArchiverIn& ndf, tp::alni file_adress) { + // check if already saved + if (((ObjectFileHead*) (loaded_file + file_adress))->load_head_adress) { + return ((ObjectFileHead*) (loaded_file + file_adress))->load_head_adress; + } + + // save read address + tp::alni parent_file_adress = ndf.getAddress(); + + // set read address + ndf.setAddress(file_adress); + + ObjectFileHead ofh; + ndf >> ofh; + + tp::String type_name; + ndf >> type_name; + + const ObjectType* object_type = NDO->types.get(type_name); + Object* out = ObjectMemAllocate(object_type); + + if (!out) { + return NULL; + } + + setrefc(out, 0); + + // check for null object + if (out->type == &NullObject::TypeData) { + ObjectMemDeallocate(out); + out = NdoNull_globalInstance; + } + + // save heap adress in "loaded_file" + ((ObjectFileHead*) (loaded_file + file_adress))->load_head_adress = out; + + // loads recursively + object_recursive_load(ndf, out, object_type); + + // restore read address for parent call to continue + ndf.setAddress(parent_file_adress); + + // return heap memory adress + return out; + } + + bool objects_api::save(Object* in, tp::String path, bool compressed) { + ArchiverOut ndf(path.read()); + + if (!ndf.isOpened()) { + return false; + } + + clear_object_flags(); + + // save version info + ObjectsFileHeader header; + ndf << header; + + ndf.setFreeAddress(ndf.getAddress()); + + // pre allocate + for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { + if (sl_callbacks[i]) { + DEBUG_ASSERT(sl_callbacks[i]->size); + ndf.setFreeAddress(ndf.getFreeAddress() + sl_callbacks[i]->size(sl_callbacks[i]->self, ndf)); + } + } + + // pre-save + for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { + if (sl_callbacks[i] && sl_callbacks[i]->pre_save) { + sl_callbacks[i]->pre_save(sl_callbacks[i]->self, ndf); + } + } + + save(ndf, in); + + // post-save + for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { + if (sl_callbacks[i] && sl_callbacks[i]->post_save) { + sl_callbacks[i]->post_save(sl_callbacks[i]->self, ndf); + } + } + + // TODO : add compression + /* + if (compressed) { + auto temp = path + ".bz2"; + tp::compressF2F(path.read(), temp.cstr()); + + File::remove(path.read()); + File::rename(temp.cstr(), path.read()); + } + */ + + return true; + } + + Object* objects_api::load(tp::String path) { + /* + auto temp_file_name = path + ".unz"; + bool unz_res = tp::decompressF2F(path.cstr(), temp_file_name.cstr()); + + if (!unz_res) { + return NULL; + } + + File ndf(temp_file_name.cstr(), tp::osfile_openflags::LOAD); + */ + + ArchiverIn ndf(path.read()); + + if (!ndf.isOpened()) { + return NULL; + } + + // check for compatibility + ObjectsFileHeader current_header; + ObjectsFileHeader loaded_header(false); + + ndf >> loaded_header; + + if (!tp::memEqual(¤t_header, &loaded_header, sizeof(ObjectsFileHeader))) { + return NULL; + } + + ndf.setAddress(0); + + const auto fileSize = ndf.getSize(); + loaded_file = (tp::int1*) malloc(fileSize); + tp::memSetVal(loaded_file, fileSize, 0); + ndf.readBytes(loaded_file, fileSize); + + ndf.setAddress(sizeof(ObjectsFileHeader)); + + // preload + for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { + if (sl_callbacks[i] && sl_callbacks[i]->pre_load) { + sl_callbacks[i]->pre_load(sl_callbacks[i]->self, ndf); + } + } + + Object* out = load(ndf, ndf.getAddress()); + + // post + for (tp::alni i = 0; i < SAVE_LOAD_MAX_CALLBACK_SLOTS; i++) { + if (sl_callbacks[i] && sl_callbacks[i]->post_save) { + sl_callbacks[i]->post_load(sl_callbacks[i]->self, ndf); + } + } + + free(loaded_file); + + /* + ndf.close(); + + if (unz_res == NULL) { + File::remove(temp_file_name.cstr()); + } + */ + + return out; + } + + void objects_api::add_sl_callbacks(save_load_callbacks* in) { + sl_callbacks[sl_callbacks_load_idx] = in; + sl_callbacks_load_idx++; + } }; \ No newline at end of file diff --git a/Objects/private/core/scriptsection.cpp b/Objects/private/core/scriptsection.cpp index 930cf55..f5f10c3 100644 --- a/Objects/private/core/scriptsection.cpp +++ b/Objects/private/core/scriptsection.cpp @@ -1,268 +1,255 @@ - -#include "NewPlacement.hpp" -#include "HeapAllocatorGlobal.hpp" - -#include "core/scriptsection.h" - -using namespace obj; - -ScriptSection* gScriptSection = NULL; - -struct script_data_head { - tp::alni refc = 0; - tp::alni store_adress = 0; -}; - -void set_script_head_store_adress(Script* in, tp::alni address) { - ((script_data_head*)in - 1)->store_adress = address; -} - -tp::alni get_script_head_store_adress(Script* in) { - return ((script_data_head*)in - 1)->store_adress; -} - -Script* ScriptSection::createScript() { - auto sdhead = (script_data_head*)tp::HeapAllocGlobal::allocate(sizeof(script_data_head) + sizeof(Script)); - auto out = (Script*)(sdhead + 1); - - if (!sdhead) { - return NULL; - } - - sdhead->refc = 1; - sdhead->store_adress = -1; - - mScripts.pushBack(out); - - new (out) Script(); - out->mReadable = obj::StringObject::create(""); - obj::NDO->refinc(out->mReadable); - return out; -} - -void ScriptSection::delete_script(Script* script) { - script->~Script(); - obj::NDO->destroy(script->mReadable); - - tp::HeapAllocGlobal::deallocate((((script_data_head*)script) - 1)); -} - -void ScriptSection::reference_script(Script* script) { - (((script_data_head*)script) - 1)->refc++; -} - -void ScriptSection::abandonScript(Script* script) { - if ((((script_data_head*)script) - 1)->refc > 1) { - (((script_data_head*)script) - 1)->refc--; - } - else { - // ISSUE : on delete list structure is outdated - // FIXME : use pool alloc with ref count - // forwarding to global destruction - //delete_script(script); - } -} - -void ScriptSection::changeScript(Script** current_script, Script** new_script) { - abandonScript(*current_script); - reference_script(*new_script); - - *current_script = *new_script; -} - -tp::alni ScriptSection::get_script_file_adress(Script* in) { - return get_script_head_store_adress(in); -} - -tp::alni ScriptSection::save_script_table_to_file_size(ScriptSection* self, ArchiverOut& file) { - tp::alni size = 0; - size += 5; // header - size += sizeof(tp::alni); // scripts length - - for (auto iter : self->mScripts) { - - set_script_head_store_adress(iter.data(), file.getAddress() + size); - - size += sizeof(tp::alni); // scripts string obj ref - size += sizeof(tp::alni); // constants length - - for (auto const_obj : iter->mBytecode.mConstants) { - size += sizeof(tp::alni); // constant object addres - } - - // instructions - size += tp::SaveSizeCounter::calc(iter->mBytecode.mInstructions); - } - - size += sizeof(tp::alni); // objects mem offset - size += 5; // header - return size; -} - -void ScriptSection::save_script_table_to_file(ScriptSection* self, ArchiverOut& file) { - // header - file.writeBytes("/scr/", 5); - - // scripts length - tp::alni scripts_count = self->mScripts.length(); - file << scripts_count; - - for (auto iter : self->mScripts) { - - // scripts string obj ref - auto obj_addres = obj::NDO->save(file, iter->mReadable); - file << obj_addres; - - // constants length - tp::alni consts_count = iter->mBytecode.mConstants.size(); - file << consts_count; - - for (auto const_obj : iter->mBytecode.mConstants) { - // constant object addres - auto obj_addres = obj::NDO->save(file, const_obj.data()); - file << obj_addres; - } - - // mInstructions - file << iter->mBytecode.mInstructions; - } - - // header - file.writeBytes("/scr/", 5); - - tp::alni objects_mem_offset = file.getFreeAddress(); - file << objects_mem_offset; -} - -void load_constants(ScriptSection* self, ArchiverIn& file, tp::alni start_addr) { - auto addres = file.getAddress(); - - file.setAddress(start_addr); - file.setAddress( start_addr + 5); // header - - tp::alni scripts_count; - file >> scripts_count; - - for (tp::alni i = 0; i < scripts_count; i++) { - - auto script = self->get_scritp_from_file_adress(file.getAddress()); - - // script text - tp::alni str_addr; - file >> str_addr; - - NDO->destroy(script->mReadable); // we already have string object in the script when creating script - script->mReadable = NDO_CAST(obj::StringObject, obj::NDO->load(file, str_addr)); - - file.setAddress(file.getAddress() + sizeof(tp::alni)); // constants length - - for (auto const_obj : script->mBytecode.mConstants) { - tp::alni consts_addr; - file >> consts_addr; - const_obj.data() = obj::NDO->load(file, consts_addr); - } - - // instructions - file.setAddress(file.getAddress() + tp::SaveSizeCounter::calc(script->mBytecode.mInstructions)); - } - - file.setAddress(addres); -} - -void ScriptSection::load_script_table_from_file(ScriptSection* self, ArchiverIn& file) { - for (auto iter : self->mScripts) { - set_script_head_store_adress(iter.data(), -1); - } - - auto section_start_addr = file.getAddress(); - - // header - file.setAddress(file.getAddress() + 5); - - // scripts length - tp::alni scripts_count; - file >> scripts_count; - - for (tp::alni i = 0; i < scripts_count; i++) { - - auto new_script = self->createScript(); - set_script_head_store_adress(new_script, file.getAddress()); - - // scripts text - file.setAddress(file.getAddress() + sizeof(tp::alni)); - - // constants length - tp::alni consts_count; - file >> consts_count; - - new_script->mBytecode.mConstants.reserve(consts_count); - - for (tp::alni j = 0; j < consts_count; j++) { - // constant object addres - tp::alni consts_addr; - file >> consts_addr; - - // skiping - //new_script->mBytecode.mConstants[j] = obj::NDO->load(file, consts_addr); - } - - // mInstructions - file >> new_script->mBytecode.mInstructions; - } - - load_constants(self, file, section_start_addr); - - // header - file.setAddress(file.getAddress() + 5); - - tp::alni objects_mem_offset; - file >> objects_mem_offset; - - file.setAddress(objects_mem_offset); -} - -Script* ScriptSection::get_scritp_from_file_adress(tp::alni file_adress) { - for (auto iter : mScripts) { - if (get_script_head_store_adress(iter.data()) == file_adress) { - return iter.data(); - } - } - return NULL; -} - -ScriptSection::~ScriptSection() { - for (auto iter : mScripts) { - delete_script(iter.data()); - } -} - -obj::save_load_callbacks ScriptSection::slcb_script_section = { - .self = gScriptSection, - .pre_save = (obj::pre_save_callback*)ScriptSection::save_script_table_to_file, - .size = (obj::slcb_size_callback*)ScriptSection::save_script_table_to_file_size, - .pre_load = (obj::pre_load_callback*)ScriptSection::load_script_table_from_file, - .post_save = NULL, - .post_load = NULL, -}; - - -void ScriptSection::initialize() { - ASSERT(!gScriptSection); - gScriptSection = new ScriptSection(); - - ASSERT(obj::NDO && "Forgot to initialize objects?"); - - slcb_script_section.self = gScriptSection; - obj::NDO->add_sl_callbacks(&slcb_script_section); -} - -void ScriptSection::uninitialize() { - ASSERT(gScriptSection); - delete gScriptSection; - gScriptSection = nullptr; -} - -ScriptSection* ScriptSection::globalHandle() { - return gScriptSection; -} - + +#include "HeapAllocatorGlobal.hpp" +#include "NewPlacement.hpp" + +#include "core/scriptsection.h" + +using namespace obj; + +ScriptSection* gScriptSection = NULL; + +struct script_data_head { + tp::alni refc = 0; + tp::alni store_adress = 0; +}; + +void set_script_head_store_adress(Script* in, tp::alni address) { ((script_data_head*) in - 1)->store_adress = address; } + +tp::alni get_script_head_store_adress(Script* in) { return ((script_data_head*) in - 1)->store_adress; } + +Script* ScriptSection::createScript() { + auto sdhead = (script_data_head*) tp::HeapAllocGlobal::allocate(sizeof(script_data_head) + sizeof(Script)); + auto out = (Script*) (sdhead + 1); + + if (!sdhead) { + return NULL; + } + + sdhead->refc = 1; + sdhead->store_adress = -1; + + mScripts.pushBack(out); + + new (out) Script(); + out->mReadable = obj::StringObject::create(""); + obj::NDO->refinc(out->mReadable); + return out; +} + +void ScriptSection::delete_script(Script* script) { + script->~Script(); + obj::NDO->destroy(script->mReadable); + + tp::HeapAllocGlobal::deallocate((((script_data_head*) script) - 1)); +} + +void ScriptSection::reference_script(Script* script) { (((script_data_head*) script) - 1)->refc++; } + +void ScriptSection::abandonScript(Script* script) { + if ((((script_data_head*) script) - 1)->refc > 1) { + (((script_data_head*) script) - 1)->refc--; + } else { + // ISSUE : on delete list structure is outdated + // FIXME : use pool alloc with ref count + // forwarding to global destruction + // delete_script(script); + } +} + +void ScriptSection::changeScript(Script** current_script, Script** new_script) { + abandonScript(*current_script); + reference_script(*new_script); + + *current_script = *new_script; +} + +tp::alni ScriptSection::get_script_file_adress(Script* in) { return get_script_head_store_adress(in); } + +tp::alni ScriptSection::save_script_table_to_file_size(ScriptSection* self, ArchiverOut& file) { + tp::alni size = 0; + size += 5; // header + size += sizeof(tp::alni); // scripts length + + for (auto iter : self->mScripts) { + + set_script_head_store_adress(iter.data(), file.getAddress() + size); + + size += sizeof(tp::alni); // scripts string obj ref + size += sizeof(tp::alni); // constants length + + for (auto const_obj : iter->mBytecode.mConstants) { + size += sizeof(tp::alni); // constant object addres + } + + // instructions + size += tp::SaveSizeCounter::calc(iter->mBytecode.mInstructions); + } + + size += sizeof(tp::alni); // objects mem offset + size += 5; // header + return size; +} + +void ScriptSection::save_script_table_to_file(ScriptSection* self, ArchiverOut& file) { + // header + file.writeBytes("/scr/", 5); + + // scripts length + tp::alni scripts_count = self->mScripts.length(); + file << scripts_count; + + for (auto iter : self->mScripts) { + + // scripts string obj ref + auto obj_addres = obj::NDO->save(file, iter->mReadable); + file << obj_addres; + + // constants length + tp::alni consts_count = iter->mBytecode.mConstants.size(); + file << consts_count; + + for (auto const_obj : iter->mBytecode.mConstants) { + // constant object addres + auto obj_addres = obj::NDO->save(file, const_obj.data()); + file << obj_addres; + } + + // mInstructions + file << iter->mBytecode.mInstructions; + } + + // header + file.writeBytes("/scr/", 5); + + tp::alni objects_mem_offset = file.getFreeAddress(); + file << objects_mem_offset; +} + +void load_constants(ScriptSection* self, ArchiverIn& file, tp::alni start_addr) { + auto addres = file.getAddress(); + + file.setAddress(start_addr); + file.setAddress(start_addr + 5); // header + + tp::alni scripts_count; + file >> scripts_count; + + for (tp::alni i = 0; i < scripts_count; i++) { + + auto script = self->get_scritp_from_file_adress(file.getAddress()); + + // script text + tp::alni str_addr; + file >> str_addr; + + NDO->destroy(script->mReadable); // we already have string object in the script when creating script + script->mReadable = NDO_CAST(obj::StringObject, obj::NDO->load(file, str_addr)); + + file.setAddress(file.getAddress() + sizeof(tp::alni)); // constants length + + for (auto const_obj : script->mBytecode.mConstants) { + tp::alni consts_addr; + file >> consts_addr; + const_obj.data() = obj::NDO->load(file, consts_addr); + } + + // instructions + file.setAddress(file.getAddress() + tp::SaveSizeCounter::calc(script->mBytecode.mInstructions)); + } + + file.setAddress(addres); +} + +void ScriptSection::load_script_table_from_file(ScriptSection* self, ArchiverIn& file) { + for (auto iter : self->mScripts) { + set_script_head_store_adress(iter.data(), -1); + } + + auto section_start_addr = file.getAddress(); + + // header + file.setAddress(file.getAddress() + 5); + + // scripts length + tp::alni scripts_count; + file >> scripts_count; + + for (tp::alni i = 0; i < scripts_count; i++) { + + auto new_script = self->createScript(); + set_script_head_store_adress(new_script, file.getAddress()); + + // scripts text + file.setAddress(file.getAddress() + sizeof(tp::alni)); + + // constants length + tp::alni consts_count; + file >> consts_count; + + new_script->mBytecode.mConstants.reserve(consts_count); + + for (tp::alni j = 0; j < consts_count; j++) { + // constant object addres + tp::alni consts_addr; + file >> consts_addr; + + // skiping + // new_script->mBytecode.mConstants[j] = obj::NDO->load(file, consts_addr); + } + + // mInstructions + file >> new_script->mBytecode.mInstructions; + } + + load_constants(self, file, section_start_addr); + + // header + file.setAddress(file.getAddress() + 5); + + tp::alni objects_mem_offset; + file >> objects_mem_offset; + + file.setAddress(objects_mem_offset); +} + +Script* ScriptSection::get_scritp_from_file_adress(tp::alni file_adress) { + for (auto iter : mScripts) { + if (get_script_head_store_adress(iter.data()) == file_adress) { + return iter.data(); + } + } + return NULL; +} + +ScriptSection::~ScriptSection() { + for (auto iter : mScripts) { + delete_script(iter.data()); + } +} + +obj::save_load_callbacks ScriptSection::slcb_script_section = { + .self = gScriptSection, + .pre_save = (obj::pre_save_callback*) ScriptSection::save_script_table_to_file, + .size = (obj::slcb_size_callback*) ScriptSection::save_script_table_to_file_size, + .pre_load = (obj::pre_load_callback*) ScriptSection::load_script_table_from_file, + .post_save = NULL, + .post_load = NULL, +}; + +void ScriptSection::initialize() { + ASSERT(!gScriptSection); + gScriptSection = new ScriptSection(); + + ASSERT(obj::NDO && "Forgot to initialize objects?"); + + slcb_script_section.self = gScriptSection; + obj::NDO->add_sl_callbacks(&slcb_script_section); +} + +void ScriptSection::uninitialize() { + ASSERT(gScriptSection); + delete gScriptSection; + gScriptSection = nullptr; +} + +ScriptSection* ScriptSection::globalHandle() { return gScriptSection; } diff --git a/Objects/private/core/typegroups.cpp b/Objects/private/core/typegroups.cpp index b666233..0ce1589 100644 --- a/Objects/private/core/typegroups.cpp +++ b/Objects/private/core/typegroups.cpp @@ -1,81 +1,83 @@ - -#include "NewPlacement.hpp" - -#include "core/typegroups.h" - -#include "core/object.h" - -using namespace obj; - -obj::TypeGroups::TypeGroups() : is_group(true) { - new (&childs) Dict(); -} - -obj::TypeGroups::TypeGroups(bool is_group) : is_group(is_group) { - if (is_group) { - new (&childs) Dict(); - } else { - type = NULL; - } -} - -bool obj::TypeGroups::isGroup() { return is_group; } - -obj::TypeGroups::Dict* obj::TypeGroups::getChilds() { - DEBUG_ASSERT(is_group); - return &childs; -} - -void obj::TypeGroups::setType(ObjectType* type) { - DEBUG_ASSERT(!is_group); - this->type = type; -} - -void obj::TypeGroups::addType(ObjectType* type, tp::InitialierList path, tp::alni cur_dir_idx) { - DEBUG_ASSERT(is_group); - - tp::alni dir_len = (tp::alni) path.size(); - - if (dir_len == cur_dir_idx) { - TypeGroups* type_ref = new TypeGroups(false); - type_ref->setType(type); - childs.put(type->name, type_ref); - return; - } - - TypeGroups* group = NULL; - tp::alni index = 0; - - for (auto dir : path) { - if (index != cur_dir_idx) { - index++; - continue; - } - - auto child_idx = childs.presents(dir); - if (child_idx) { - group = childs.getSlotVal(child_idx); - } else { - group = new TypeGroups(true); - childs.put(dir, group); - } - - group->addType(type, path, cur_dir_idx + 1); - - break; - } -} - -const obj::ObjectType* obj::TypeGroups::getType() { - DEBUG_ASSERT(!is_group); - return type; -} - -obj::TypeGroups::~TypeGroups() { - if (is_group) { - for (auto& child : childs) { - delete child->val; - } - childs.~Map(); - } + +#include "NewPlacement.hpp" + +#include "core/typegroups.h" + +#include "core/object.h" + +using namespace obj; + +obj::TypeGroups::TypeGroups() : + is_group(true) { + new (&childs) Dict(); +} + +obj::TypeGroups::TypeGroups(bool is_group) : + is_group(is_group) { + if (is_group) { + new (&childs) Dict(); + } else { + type = NULL; + } +} + +bool obj::TypeGroups::isGroup() { return is_group; } + +obj::TypeGroups::Dict* obj::TypeGroups::getChilds() { + DEBUG_ASSERT(is_group); + return &childs; +} + +void obj::TypeGroups::setType(ObjectType* type) { + DEBUG_ASSERT(!is_group); + this->type = type; +} + +void obj::TypeGroups::addType(ObjectType* type, tp::InitialierList path, tp::alni cur_dir_idx) { + DEBUG_ASSERT(is_group); + + tp::alni dir_len = (tp::alni) path.size(); + + if (dir_len == cur_dir_idx) { + TypeGroups* type_ref = new TypeGroups(false); + type_ref->setType(type); + childs.put(type->name, type_ref); + return; + } + + TypeGroups* group = NULL; + tp::alni index = 0; + + for (auto dir : path) { + if (index != cur_dir_idx) { + index++; + continue; + } + + auto child_idx = childs.presents(dir); + if (child_idx) { + group = childs.getSlotVal(child_idx); + } else { + group = new TypeGroups(true); + childs.put(dir, group); + } + + group->addType(type, path, cur_dir_idx + 1); + + break; + } +} + +const obj::ObjectType* obj::TypeGroups::getType() { + DEBUG_ASSERT(!is_group); + return type; +} + +obj::TypeGroups::~TypeGroups() { + if (is_group) { + for (auto& child : childs) { + delete child->val; + } + childs.~Map(); + } } \ No newline at end of file diff --git a/Objects/private/core/typemethods.cpp b/Objects/private/core/typemethods.cpp index 1b22194..b7f45ed 100644 --- a/Objects/private/core/typemethods.cpp +++ b/Objects/private/core/typemethods.cpp @@ -1,138 +1,134 @@ - -#include "NewPlacement.hpp" - -#include "core/typemethods.h" - -#include "primitives/nullobject.h" -#include "primitives/typeobject.h" -#include "primitives/floatobject.h" - -#include "interpreter/interpreter.h" - - -using namespace obj; - -TypeMethod obj::gDefaultTypeMethods[] = { - { - .nameid = "type", - .descr = "retrieves typeobject", - .exec = [](const TypeMethod* tm) { - tm->ret.obj = TypeObject::create(tm->self->type); - }, - .ret = { "typeobject", NULL }, - }, - { - .nameid = "to_str", - .descr = "converts to string", - .exec = [](const TypeMethod* tm) { - if (tm->self->type->convesions && tm->self->type->convesions->to_string) { - tm->ret.obj = StringObject::create(NDO->toString(tm->self)); - } - }, - .ret = { "string object", NULL }, - }, - { - .nameid = "to_float", - .descr = "converts to float", - .exec = [](const TypeMethod* tm) { - if (tm->self->type->convesions && tm->self->type->convesions->to_float) { - tm->ret.obj = FloatObject::create(NDO->toFloat(tm->self)); - } - }, - .ret = { "string object", NULL }, - }, -}; - -tp::int2 TypeMethods::presents(tp::String id) const { - for (tp::int2 idx = 0; idx < mNMethods; idx++) { - if (id == methods[idx]->nameid) { - return idx; - } - } - - tp::int2 idx = 0; - for (auto& tm : gDefaultTypeMethods) { - if (id == tm.nameid) { - return { tp::int2(idx + MAX_TYPE_METHODS) }; - } - idx++; - } - - return -1; -} - -TypeMethods::LookupKey TypeMethods::presents(const ObjectType* type, tp::String id) { - - tp::int2 depth = 0; - tp::int2 idx = 0; - - for (auto iter_type = type; iter_type; iter_type = iter_type->base) { - idx = iter_type->type_methods.presents(id); - if (idx != -1) { - break; - } - depth++; - } - - return { idx, depth}; -} - -const TypeMethod* TypeMethods::getMethod(tp::int2 key) const { - if (key < MAX_TYPE_METHODS) { - return methods[key]; - } - return &gDefaultTypeMethods[key - MAX_TYPE_METHODS]; -} - -const TypeMethod* TypeMethods::getMethod(const ObjectType* type, LookupKey key) { - auto type_iter = type; - for (auto idx = 0; idx < key.type_depth; idx++) { - type_iter = type_iter->base; - } - return type_iter->type_methods.getMethod(key.key); -} - -void TypeMethods::init() { - while (methods[mNMethods]) { - mNMethods++; - } - - for (tp::int1 i = 0; i < mNMethods; i++) { - methods[i]->init(); - } - - // initialize and use finate state automata to lookup methods -} - -tp::halni TypeMethods::nMethods() const { - return mNMethods; -} - -void TypeMethod::operator()(Interpreter* interp) const{ - for (auto i = 1; i <= mNargs; i++) { - args[mNargs - i].obj = interp->mOperandsStack.getOperand(); - //NDO->refinc(args[i].obj); - ASSERT(args[mNargs - i].obj && "expected an argument"); - } - - ASSERT(!interp->mOperandsStack.getOperand() && "args remained"); - interp->mOperandsStack.getOperand(); - - self = interp->mLastParent; - - exec(this); - - if (ret.obj) { - interp->mOperandsStack.push(ret.obj); - interp->mScopeStack.addTempReturn(ret.obj); - } - else { - interp->mOperandsStack.push(NDO_NULL_REF); - } -} - -void TypeMethod::init() { - while (args[mNargs].descr) { - mNargs++; - } + +#include "NewPlacement.hpp" + +#include "core/typemethods.h" + +#include "primitives/floatobject.h" +#include "primitives/nullobject.h" +#include "primitives/typeobject.h" + +#include "interpreter/interpreter.h" + +using namespace obj; + +TypeMethod obj::gDefaultTypeMethods[] = { + { + .nameid = "type", + .descr = "retrieves typeobject", + .exec = [](const TypeMethod* tm) { tm->ret.obj = TypeObject::create(tm->self->type); }, + .ret = { "typeobject", NULL }, + }, + { + .nameid = "to_str", + .descr = "converts to string", + .exec = + [](const TypeMethod* tm) { + if (tm->self->type->convesions && tm->self->type->convesions->to_string) { + tm->ret.obj = StringObject::create(NDO->toString(tm->self)); + } + }, + .ret = { "string object", NULL }, + }, + { + .nameid = "to_float", + .descr = "converts to float", + .exec = + [](const TypeMethod* tm) { + if (tm->self->type->convesions && tm->self->type->convesions->to_float) { + tm->ret.obj = FloatObject::create(NDO->toFloat(tm->self)); + } + }, + .ret = { "string object", NULL }, + }, +}; + +tp::int2 TypeMethods::presents(tp::String id) const { + for (tp::int2 idx = 0; idx < mNMethods; idx++) { + if (id == methods[idx]->nameid) { + return idx; + } + } + + tp::int2 idx = 0; + for (auto& tm : gDefaultTypeMethods) { + if (id == tm.nameid) { + return { tp::int2(idx + MAX_TYPE_METHODS) }; + } + idx++; + } + + return -1; +} + +TypeMethods::LookupKey TypeMethods::presents(const ObjectType* type, tp::String id) { + + tp::int2 depth = 0; + tp::int2 idx = 0; + + for (auto iter_type = type; iter_type; iter_type = iter_type->base) { + idx = iter_type->type_methods.presents(id); + if (idx != -1) { + break; + } + depth++; + } + + return { idx, depth }; +} + +const TypeMethod* TypeMethods::getMethod(tp::int2 key) const { + if (key < MAX_TYPE_METHODS) { + return methods[key]; + } + return &gDefaultTypeMethods[key - MAX_TYPE_METHODS]; +} + +const TypeMethod* TypeMethods::getMethod(const ObjectType* type, LookupKey key) { + auto type_iter = type; + for (auto idx = 0; idx < key.type_depth; idx++) { + type_iter = type_iter->base; + } + return type_iter->type_methods.getMethod(key.key); +} + +void TypeMethods::init() { + while (methods[mNMethods]) { + mNMethods++; + } + + for (tp::int1 i = 0; i < mNMethods; i++) { + methods[i]->init(); + } + + // initialize and use finate state automata to lookup methods +} + +tp::halni TypeMethods::nMethods() const { return mNMethods; } + +void TypeMethod::operator()(Interpreter* interp) const { + for (auto i = 1; i <= mNargs; i++) { + args[mNargs - i].obj = interp->mOperandsStack.getOperand(); + // NDO->refinc(args[i].obj); + ASSERT(args[mNargs - i].obj && "expected an argument"); + } + + ASSERT(!interp->mOperandsStack.getOperand() && "args remained"); + interp->mOperandsStack.getOperand(); + + self = interp->mLastParent; + + exec(this); + + if (ret.obj) { + interp->mOperandsStack.push(ret.obj); + interp->mScopeStack.addTempReturn(ret.obj); + } else { + interp->mOperandsStack.push(NDO_NULL_REF); + } +} + +void TypeMethod::init() { + while (args[mNargs].descr) { + mNargs++; + } } \ No newline at end of file diff --git a/Objects/private/interpreter/callstack.cpp b/Objects/private/interpreter/callstack.cpp index ccf37aa..4a68cb0 100644 --- a/Objects/private/interpreter/callstack.cpp +++ b/Objects/private/interpreter/callstack.cpp @@ -1,40 +1,36 @@ - -#include "NewPlacement.hpp" - -#include "interpreter/callstack.h" - -#include "interpreter/bytecode.h" -#include "primitives/methodobject.h" - -using namespace obj; - -void CallStack::enter(const CallStack::CallFrame& frame) { - if (mStack.size()) { - auto& last_frame = mStack.last(); - last_frame.mIp = last_frame.mMethod->mScript->mBytecode.mInstructionIdx; - } - - frame.mMethod->mScript->mBytecode.mArgumentsLoaded = 0; - frame.mMethod->mScript->mBytecode.mInstructionIdx = 0; - obj::NDO->refinc(frame.mMethod); - mStack.append(frame); -} - -void CallStack::leave() { - auto frame = mStack.last(); - obj::NDO->destroy(frame.mMethod); - mStack.pop(); - - if (mStack.size()) { - auto& last_frame = mStack.last(); - last_frame.mMethod->mScript->mBytecode.mInstructionIdx = last_frame.mIp; - } -} - -ByteCode* CallStack::getBytecode() { - return &mStack.last().mMethod->mScript->mBytecode; -} - -tp::halni CallStack::len() const { - return mStack.size(); -} \ No newline at end of file + +#include "NewPlacement.hpp" + +#include "interpreter/callstack.h" + +#include "interpreter/bytecode.h" +#include "primitives/methodobject.h" + +using namespace obj; + +void CallStack::enter(const CallStack::CallFrame& frame) { + if (mStack.size()) { + auto& last_frame = mStack.last(); + last_frame.mIp = last_frame.mMethod->mScript->mBytecode.mInstructionIdx; + } + + frame.mMethod->mScript->mBytecode.mArgumentsLoaded = 0; + frame.mMethod->mScript->mBytecode.mInstructionIdx = 0; + obj::NDO->refinc(frame.mMethod); + mStack.append(frame); +} + +void CallStack::leave() { + auto frame = mStack.last(); + obj::NDO->destroy(frame.mMethod); + mStack.pop(); + + if (mStack.size()) { + auto& last_frame = mStack.last(); + last_frame.mMethod->mScript->mBytecode.mInstructionIdx = last_frame.mIp; + } +} + +ByteCode* CallStack::getBytecode() { return &mStack.last().mMethod->mScript->mBytecode; } + +tp::halni CallStack::len() const { return mStack.size(); } \ No newline at end of file diff --git a/Objects/private/interpreter/interpreter.cpp b/Objects/private/interpreter/interpreter.cpp index bf3a660..83a1f9e 100644 --- a/Objects/private/interpreter/interpreter.cpp +++ b/Objects/private/interpreter/interpreter.cpp @@ -1,573 +1,609 @@ - -#include "NewPlacement.hpp" - -#include "interpreter/interpreter.h" - -#include "primitives/primitives.h" - -#include "Logging.hpp" - -#include "Timing.hpp" - -using namespace obj; - -inline tp::uint1 read_byte(ByteCode* bytecode) { - auto out = (tp::uint1)bytecode->mInstructions[bytecode->mInstructionIdx]; - bytecode->mInstructionIdx++; - return out; -} - -// exeption for opcodes -// reads 2 bytes from instructions in order to load constant onto operands stack -tp::uint2 loadConstDataIdx(ByteCode* bytecode) { - tp::uint2 out = 0; - out |= ((tp::uint2) read_byte(bytecode)); - out |= ((tp::uint2) read_byte(bytecode) << 8); - return out; -} - -// exeption for opcodes -// reads 2 bytes from instructions in order to load constant onto operands stack -void skip_param(ByteCode* bytecode) { - bytecode->mInstructionIdx += 2; -} - -tp::uint2 param(ByteCode* bytecode) { - return loadConstDataIdx(bytecode); -} - -void Interpreter::exec(obj::MethodObject* method, obj::ClassObject* self, obj::DictObject* globals, tp::InitialierList globals2) { - if (!method->mScript->mBytecode.mInstructions.size()) { - return; - } - - mCallStack.enter({ NULL, method, 0 }); - mCallStack.mStack.last().mSelf = self; - - stepBytecodeIn(); - - if (globals) { - for (auto glb : globals->getItems()) { - mScopeStack.addLocal(glb->val, glb->key); - } - } - - for (auto global_def : globals2) { - mScopeStack.addLocal(global_def.obj, global_def.id); - } -} - -bool Interpreter::finished() { - return !mCallStack.len(); -} - -void Interpreter::stepBytecode() { - tp::halni call_depth = mCallStack.len(); - do { - stepBytecodeIn(); - if (finished()) { - return; - } - } while (call_depth != mCallStack.len()); -} - -void Interpreter::stepBytecodeOut() { - if (finished()) { - return; - } - - tp::halni call_depth = mCallStack.len(); - if (!call_depth) { - return; - } - - do { - stepBytecodeIn(); - if (finished()) { - return; - } - } while (call_depth - 1 != mCallStack.len()); -} - -void Interpreter::stepBytecodeIn() { - using namespace obj; - using namespace tp; - - DEBUG_BREAK(finished()); - - auto bytecode = mCallStack.getBytecode(); - - if (bytecode->mInstructionIdx >= (tp::ualni) bytecode->mInstructions.size()) { - // just return - if (mScopeStack.mIdx) { - mScopeStack.leaveScope(); - } - - mCallStack.leave(); - - if (mCallStack.len()) { - mOperandsStack.push(NDO_NULL_REF); - } - return; - } - - auto opcode = bytecode->mInstructions[bytecode->mInstructionIdx]; - bytecode->mInstructionIdx++; - - switch (opcode) { - - case OpCode::NONE: { - break; - } - - case OpCode::HALT: { - while (true) { - tp::sleep(3); - } - break; - } - - case OpCode::TERMINATE: { - //tp::terminate(0); - } - - case OpCode::IGNORE: { - NDO->destroy(mOperandsStack.getOperand()); - break; - } - - case OpCode::LOAD_CONST: { - auto idx = loadConstDataIdx(bytecode); - auto const_obj = bytecode->mConstants[idx]; - mOperandsStack.push(const_obj); - break; - } - - case OpCode::LOAD_LOCAL: { - auto idx = loadConstDataIdx(bytecode); - auto const_obj = bytecode->mConstants[idx]; - NDO_CASTV(StringObject, const_obj, local_id); - ASSERT(local_id && "Invalid Object Type"); - auto local = mScopeStack.getLocal(local_id->val); - mOperandsStack.push(local); - break; - } - - case OpCode::SCOPE_IN: { - mScopeStack.enterScope(true); - break; - } - - case OpCode::JUMP: { - bytecode->mInstructionIdx += param(bytecode); - break; - } - - case OpCode::JUMP_IF: { - auto cond = mOperandsStack.getOperand(); - if (NDO->toBool(cond)) { - bytecode->mInstructionIdx += param(bytecode); - } else { - skip_param(bytecode); - } - break; - } - - case OpCode::JUMP_IF_NOT: { - auto cond = mOperandsStack.getOperand(); - if (!NDO->toBool(cond)) { - bytecode->mInstructionIdx += param(bytecode); - } else { - skip_param(bytecode); - } - break; - } - - case OpCode::JUMP_R: { - bytecode->mInstructionIdx -= param(bytecode); - break; - } - - case OpCode::JUMP_IF_R: { - auto cond = mOperandsStack.getOperand(); - if (NDO->toBool(cond)) { - bytecode->mInstructionIdx -= param(bytecode); - } else { - skip_param(bytecode); - } - break; - } - - case OpCode::JUMP_IF_NOT_R: { - auto cond = mOperandsStack.getOperand(); - if (!NDO->toBool(cond)) { - bytecode->mInstructionIdx -= param(bytecode); - } else { - skip_param(bytecode); - } - break; - } - - case OpCode::SCOPE_OUT: { - mScopeStack.leaveScope(); - break; - } - - case OpCode::PRINT: { - auto obj = mOperandsStack.getOperand(); - if (obj->type->convesions && obj->type->convesions->to_string) { - auto str = NDO->toString(obj); - gLogger->write(str, true); - } else { - gLogger->write(String(obj->type->name), true); - } - break; - } - - case OpCode::OBJ_CREATE_LOCAL: { - auto type = mOperandsStack.getOperand(); - auto id = mOperandsStack.getOperand(); - mScopeStack.addLocal(NDO->create(type->val), id->val); - break; - } - - case OpCode::DEF_LOCAL: { - auto id = mOperandsStack.getOperand(); - auto obj = mOperandsStack.getOperand(); - mScopeStack.addLocal(obj, id->val); - NDO->refinc(obj); - //mScopeStack.popTemp(); - break; - } - - case OpCode::OBJ_CREATE: { - auto type = mOperandsStack.getOperand(); - Object* new_obj = NULL; - - // basic types - auto idx = NDO->types.presents(type->val); - if (idx) { - auto new_obj = NDO->create(type->val); - - mOperandsStack.push(new_obj); - mScopeStack.addTemp(new_obj); - break; - } - - - // class creation - auto local_class = mScopeStack.getLocal(type->val); - NDO_CASTV(MethodObject, local_class, method); - ASSERT(method); - - // class is a function - execute it as a constructor - - // PUSH_ARGS protocol - tp::uint2 len = 0; - mOperandsStack.push((Object*)len); - mOperandsStack.push(NULL); - - // CALL protocol - mScopeStack.enterScope(false); - mCallStack.enter({ NULL, method, 0 }); - break; - } - - case OpCode::CLASS_CONSTRUCT: { - auto class_obj = (ClassObject*)NDO->create("class"); - - for (auto local : mScopeStack.getCurrentScope()->mLocals) { - class_obj->addMember(local->val, local->key); - } - - mOperandsStack.push(class_obj); - mScopeStack.addTempReturn(class_obj); - - mScopeStack.leaveScope(); - mCallStack.leave(); - return; - } - - case OpCode::RETURN: { - //mScopeStack.addTempReturn(NDO_NULL_REF); - mScopeStack.leaveScope(); - mCallStack.leave(); - if (mCallStack.len()) { - mOperandsStack.push(NDO_NULL_REF); - } - break; - } - - case OpCode::PUSH_ARGS: { - - // Layout of OperandsStack: - // .... - // +1) length : to chech number of args - // +2) NULL : stop saving args - // +3) object1 - // +4) object2 - // ... - - tp::uint2 len = read_byte(bytecode); - mOperandsStack.push((Object*) len); - mOperandsStack.push(NULL); - break; - } - - case OpCode::SAVE_ARGS: { - tp::uint2 args_len = read_byte(bytecode); - auto argument = mOperandsStack.getOperand(); - - while (argument) { - NDO->refinc(argument); - - auto argument_id = bytecode->mConstants[loadConstDataIdx(bytecode)]; - NDO_CASTV(StringObject, argument_id, id); - DEBUG_ASSERT(id); - mScopeStack.addLocal(argument, id->val); - bytecode->mArgumentsLoaded++; - argument = mOperandsStack.getOperand(); - } - - tp::uint2 saved_len = tp::uint2 (tp::ualni (mOperandsStack.getOperand())); - ASSERT(args_len == saved_len && "invalid number of arguments passefd"); - - break; - } - - case OpCode::RETURN_OBJ: { - if (mCallStack.len() > 1) { - auto ret = mOperandsStack.getOperand(); - mOperandsStack.push(ret); - mScopeStack.addTempReturn(ret); - } - - mScopeStack.leaveScope(); - mCallStack.leave(); - break; - } - - case OpCode::CALL: { - auto obj = mOperandsStack.getOperand(); - - if (!mIsTypeMethod) { - NDO_CASTV(MethodObject, obj, method); - - mScopeStack.enterScope(false); - mCallStack.enter({ NULL, method, 0 }); - - // push self - mCallStack.mStack.last().mSelf = mLastParent; - break; - } - - (*mTypeMethod)(this); - mIsTypeMethod = false; - mTypeMethod = NULL; - break; - } - - case OpCode::OBJ_ADD: { - auto left = mOperandsStack.getOperand(); - auto right = mOperandsStack.getOperand(); - - ASSERT(left->type == right->type && "addition of different types is not implemented"); - ASSERT(left->type->ariphmetics && left->type->ariphmetics->add && "cannot add object of this type"); - - auto res = NDO->instatiate(left); - res->type->ariphmetics->add(res, right); - - mScopeStack.addTemp(res); - mOperandsStack.push(res); - break; - } - case OpCode::OBJ_SUB: { - auto left = mOperandsStack.getOperand(); - auto right = mOperandsStack.getOperand(); - - ASSERT(left->type == right->type && "addition of different types is not implemented"); - ASSERT(left->type->ariphmetics && left->type->ariphmetics->add && "cannot add object of this type"); - - auto res = NDO->instatiate(left); - res->type->ariphmetics->sub(res, right); - - mScopeStack.addTemp(res); - mOperandsStack.push(res); - break; - } - case OpCode::OBJ_MUL: { - auto left = mOperandsStack.getOperand(); - auto right = mOperandsStack.getOperand(); - - ASSERT(left->type == right->type && "addition of different types is not implemented"); - ASSERT(left->type->ariphmetics && left->type->ariphmetics->add && "cannot add object of this type"); - - auto res = NDO->instatiate(left); - res->type->ariphmetics->mul(res, right); - - mScopeStack.addTemp(res); - mOperandsStack.push(res); - break; - } - case OpCode::OBJ_DIV: { - auto left = mOperandsStack.getOperand(); - auto right = mOperandsStack.getOperand(); - - ASSERT(left->type == right->type && "addition of different types is not implemented"); - ASSERT(left->type->ariphmetics && left->type->ariphmetics->add && "cannot add object of this type"); - - auto res = NDO->instatiate(left); - res->type->ariphmetics->div(res, right); - - mScopeStack.addTemp(res); - mOperandsStack.push(res); - break; - } - - case OpCode::OBJ_COPY: { - auto left = mOperandsStack.getOperand(); - auto right = mOperandsStack.getOperand(); - NDO->copy(left, right); - break; - } - - case OpCode::CHILD: { - auto child_id = mOperandsStack.getOperand(); - auto parent = mOperandsStack.getOperand(); - bool is_method = read_byte(bytecode); - - Object* child = NULL; - TypeMethods::LookupKey tm_key; - - if (is_method) { - tm_key = TypeMethods::presents(parent->type, child_id->val); - } - - if (tm_key) { - mTypeMethod = TypeMethods::getMethod(parent->type, tm_key); - mIsTypeMethod = true; - - } else { - NDO_CASTV(ClassObject, parent, class_obj); - ASSERT(class_obj && "not a class object"); - auto idx = class_obj->members->presents(child_id->val); - ASSERT(idx && "No child with such id"); - child = class_obj->members->getSlotVal(idx); - } - - //mScopeStack.addTemp(obj); - mOperandsStack.push(child); - mLastParent = parent; - break; - } - - case OpCode::SELF: { - //mScopeStack.addTemp(obj); - ASSERT(mCallStack.mStack.last().mSelf); - mOperandsStack.push(mCallStack.mStack.last().mSelf); - break; - } - - case OpCode::OBJ_LOAD: { - auto path = mOperandsStack.getOperand(); - auto obj = NDO->load(path->val); - mScopeStack.addTemp(obj); - mOperandsStack.push(obj); - break; - } - case OpCode::OBJ_SAVE: { - auto path = mOperandsStack.getOperand(); - auto target = mOperandsStack.getOperand(); - NDO->save(target, path->val); - break; - } - - case OpCode::AND: { - auto left = NDO->toBool(mOperandsStack.getOperand()); - auto right = NDO->toBool(mOperandsStack.getOperand()); - auto out = BoolObject::create(left && right); - mScopeStack.addTemp(out); - mOperandsStack.push(out); - break; - } - case OpCode::OR: { - auto left = NDO->toBool(mOperandsStack.getOperand()); - auto right = NDO->toBool(mOperandsStack.getOperand()); - auto out = BoolObject::create(left || right); - mScopeStack.addTemp(out); - mOperandsStack.push(out); - break; - } - case OpCode::NOT: { - auto inv = NDO->toBool(mOperandsStack.getOperand()); - auto out = BoolObject::create(!inv); - mScopeStack.addTemp(out); - mOperandsStack.push(out); - break; - } - case OpCode::NOT_EQUAL: { - auto left = mOperandsStack.getOperand(); - auto right = mOperandsStack.getOperand(); - auto out = BoolObject::create(!NDO->compare(left, right)); - mScopeStack.addTemp(out); - mOperandsStack.push(out); - break; - } - case OpCode::EQUAL: { - auto left = mOperandsStack.getOperand(); - auto right = mOperandsStack.getOperand(); - auto out = BoolObject::create(NDO->compare(left, right)); - mScopeStack.addTemp(out); - mOperandsStack.push(out); - break; - } - - case OpCode::MORE: { - auto left = NDO->toFloat(mOperandsStack.getOperand()); - auto right = NDO->toFloat(mOperandsStack.getOperand()); - auto out = BoolObject::create(left > right); - mScopeStack.addTemp(out); - mOperandsStack.push(out); - break; - } - case OpCode::LESS: { - auto left = NDO->toFloat(mOperandsStack.getOperand()); - auto right = NDO->toFloat(mOperandsStack.getOperand()); - auto out = BoolObject::create(left < right); - mScopeStack.addTemp(out); - mOperandsStack.push(out); - break; - } - case OpCode::EQUAL_OR_MORE: { - auto left = NDO->toFloat(mOperandsStack.getOperand()); - auto right = NDO->toFloat(mOperandsStack.getOperand()); - auto out = BoolObject::create(left >= right); - mScopeStack.addTemp(out); - mOperandsStack.push(out); - break; - } - case OpCode::EQUAL_OR_LESS: { - auto left = NDO->toFloat(mOperandsStack.getOperand()); - auto right = NDO->toFloat(mOperandsStack.getOperand()); - auto out = BoolObject::create(left <= right); - mScopeStack.addTemp(out); - mOperandsStack.push(out); - break; - } - - default: { - ASSERT("Invalid OpCode"); - } - } -} - -void Interpreter::execAll(obj::MethodObject* method, obj::ClassObject* self, obj::DictObject* globals, tp::InitialierList globals2) { - if (!method->mScript->mBytecode.mInstructions.size()) { - return; - } - - exec(method, self, globals, globals2); - while (!finished()) { - stepBytecodeIn(); - } + +#include "NewPlacement.hpp" + +#include "interpreter/interpreter.h" + +#include "primitives/primitives.h" + +#include "Logging.hpp" + +#include "Timing.hpp" + +using namespace obj; + +inline tp::uint1 read_byte(ByteCode* bytecode) { + auto out = (tp::uint1) bytecode->mInstructions[bytecode->mInstructionIdx]; + bytecode->mInstructionIdx++; + return out; +} + +// exeption for opcodes +// reads 2 bytes from instructions in order to load constant onto operands stack +tp::uint2 loadConstDataIdx(ByteCode* bytecode) { + tp::uint2 out = 0; + out |= ((tp::uint2) read_byte(bytecode)); + out |= ((tp::uint2) read_byte(bytecode) << 8); + return out; +} + +// exeption for opcodes +// reads 2 bytes from instructions in order to load constant onto operands stack +void skip_param(ByteCode* bytecode) { bytecode->mInstructionIdx += 2; } + +tp::uint2 param(ByteCode* bytecode) { return loadConstDataIdx(bytecode); } + +void Interpreter::exec(obj::MethodObject* method, obj::ClassObject* self, obj::DictObject* globals, tp::InitialierList globals2) { + if (!method->mScript->mBytecode.mInstructions.size()) { + return; + } + + mCallStack.enter({ NULL, method, 0 }); + mCallStack.mStack.last().mSelf = self; + + stepBytecodeIn(); + + if (globals) { + for (auto glb : globals->getItems()) { + mScopeStack.addLocal(glb->val, glb->key); + } + } + + for (auto global_def : globals2) { + mScopeStack.addLocal(global_def.obj, global_def.id); + } +} + +bool Interpreter::finished() { return !mCallStack.len(); } + +void Interpreter::stepBytecode() { + tp::halni call_depth = mCallStack.len(); + do { + stepBytecodeIn(); + if (finished()) { + return; + } + } while (call_depth != mCallStack.len()); +} + +void Interpreter::stepBytecodeOut() { + if (finished()) { + return; + } + + tp::halni call_depth = mCallStack.len(); + if (!call_depth) { + return; + } + + do { + stepBytecodeIn(); + if (finished()) { + return; + } + } while (call_depth - 1 != mCallStack.len()); +} + +void Interpreter::stepBytecodeIn() { + using namespace obj; + using namespace tp; + + DEBUG_BREAK(finished()); + + auto bytecode = mCallStack.getBytecode(); + + if (bytecode->mInstructionIdx >= (tp::ualni) bytecode->mInstructions.size()) { + // just return + if (mScopeStack.mIdx) { + mScopeStack.leaveScope(); + } + + mCallStack.leave(); + + if (mCallStack.len()) { + mOperandsStack.push(NDO_NULL_REF); + } + return; + } + + auto opcode = bytecode->mInstructions[bytecode->mInstructionIdx]; + bytecode->mInstructionIdx++; + + switch (opcode) { + + case OpCode::NONE: + { + break; + } + + case OpCode::HALT: + { + while (true) { + tp::sleep(3); + } + break; + } + + case OpCode::TERMINATE: + { + // tp::terminate(0); + } + + case OpCode::IGNORE: + { + NDO->destroy(mOperandsStack.getOperand()); + break; + } + + case OpCode::LOAD_CONST: + { + auto idx = loadConstDataIdx(bytecode); + auto const_obj = bytecode->mConstants[idx]; + mOperandsStack.push(const_obj); + break; + } + + case OpCode::LOAD_LOCAL: + { + auto idx = loadConstDataIdx(bytecode); + auto const_obj = bytecode->mConstants[idx]; + NDO_CASTV(StringObject, const_obj, local_id); + ASSERT(local_id && "Invalid Object Type"); + auto local = mScopeStack.getLocal(local_id->val); + mOperandsStack.push(local); + break; + } + + case OpCode::SCOPE_IN: + { + mScopeStack.enterScope(true); + break; + } + + case OpCode::JUMP: + { + bytecode->mInstructionIdx += param(bytecode); + break; + } + + case OpCode::JUMP_IF: + { + auto cond = mOperandsStack.getOperand(); + if (NDO->toBool(cond)) { + bytecode->mInstructionIdx += param(bytecode); + } else { + skip_param(bytecode); + } + break; + } + + case OpCode::JUMP_IF_NOT: + { + auto cond = mOperandsStack.getOperand(); + if (!NDO->toBool(cond)) { + bytecode->mInstructionIdx += param(bytecode); + } else { + skip_param(bytecode); + } + break; + } + + case OpCode::JUMP_R: + { + bytecode->mInstructionIdx -= param(bytecode); + break; + } + + case OpCode::JUMP_IF_R: + { + auto cond = mOperandsStack.getOperand(); + if (NDO->toBool(cond)) { + bytecode->mInstructionIdx -= param(bytecode); + } else { + skip_param(bytecode); + } + break; + } + + case OpCode::JUMP_IF_NOT_R: + { + auto cond = mOperandsStack.getOperand(); + if (!NDO->toBool(cond)) { + bytecode->mInstructionIdx -= param(bytecode); + } else { + skip_param(bytecode); + } + break; + } + + case OpCode::SCOPE_OUT: + { + mScopeStack.leaveScope(); + break; + } + + case OpCode::PRINT: + { + auto obj = mOperandsStack.getOperand(); + if (obj->type->convesions && obj->type->convesions->to_string) { + auto str = NDO->toString(obj); + gLogger->write(str, true); + } else { + gLogger->write(String(obj->type->name), true); + } + break; + } + + case OpCode::OBJ_CREATE_LOCAL: + { + auto type = mOperandsStack.getOperand(); + auto id = mOperandsStack.getOperand(); + mScopeStack.addLocal(NDO->create(type->val), id->val); + break; + } + + case OpCode::DEF_LOCAL: + { + auto id = mOperandsStack.getOperand(); + auto obj = mOperandsStack.getOperand(); + mScopeStack.addLocal(obj, id->val); + NDO->refinc(obj); + // mScopeStack.popTemp(); + break; + } + + case OpCode::OBJ_CREATE: + { + auto type = mOperandsStack.getOperand(); + Object* new_obj = NULL; + + // basic types + auto idx = NDO->types.presents(type->val); + if (idx) { + auto new_obj = NDO->create(type->val); + + mOperandsStack.push(new_obj); + mScopeStack.addTemp(new_obj); + break; + } + + // class creation + auto local_class = mScopeStack.getLocal(type->val); + NDO_CASTV(MethodObject, local_class, method); + ASSERT(method); + + // class is a function - execute it as a constructor + + // PUSH_ARGS protocol + tp::uint2 len = 0; + mOperandsStack.push((Object*) len); + mOperandsStack.push(NULL); + + // CALL protocol + mScopeStack.enterScope(false); + mCallStack.enter({ NULL, method, 0 }); + break; + } + + case OpCode::CLASS_CONSTRUCT: + { + auto class_obj = (ClassObject*) NDO->create("class"); + + for (auto local : mScopeStack.getCurrentScope()->mLocals) { + class_obj->addMember(local->val, local->key); + } + + mOperandsStack.push(class_obj); + mScopeStack.addTempReturn(class_obj); + + mScopeStack.leaveScope(); + mCallStack.leave(); + return; + } + + case OpCode::RETURN: + { + // mScopeStack.addTempReturn(NDO_NULL_REF); + mScopeStack.leaveScope(); + mCallStack.leave(); + if (mCallStack.len()) { + mOperandsStack.push(NDO_NULL_REF); + } + break; + } + + case OpCode::PUSH_ARGS: + { + + // Layout of OperandsStack: + // .... + // +1) length : to chech number of args + // +2) NULL : stop saving args + // +3) object1 + // +4) object2 + // ... + + tp::uint2 len = read_byte(bytecode); + mOperandsStack.push((Object*) len); + mOperandsStack.push(NULL); + break; + } + + case OpCode::SAVE_ARGS: + { + tp::uint2 args_len = read_byte(bytecode); + auto argument = mOperandsStack.getOperand(); + + while (argument) { + NDO->refinc(argument); + + auto argument_id = bytecode->mConstants[loadConstDataIdx(bytecode)]; + NDO_CASTV(StringObject, argument_id, id); + DEBUG_ASSERT(id); + mScopeStack.addLocal(argument, id->val); + bytecode->mArgumentsLoaded++; + argument = mOperandsStack.getOperand(); + } + + tp::uint2 saved_len = tp::uint2(tp::ualni(mOperandsStack.getOperand())); + ASSERT(args_len == saved_len && "invalid number of arguments passefd"); + + break; + } + + case OpCode::RETURN_OBJ: + { + if (mCallStack.len() > 1) { + auto ret = mOperandsStack.getOperand(); + mOperandsStack.push(ret); + mScopeStack.addTempReturn(ret); + } + + mScopeStack.leaveScope(); + mCallStack.leave(); + break; + } + + case OpCode::CALL: + { + auto obj = mOperandsStack.getOperand(); + + if (!mIsTypeMethod) { + NDO_CASTV(MethodObject, obj, method); + + mScopeStack.enterScope(false); + mCallStack.enter({ NULL, method, 0 }); + + // push self + mCallStack.mStack.last().mSelf = mLastParent; + break; + } + + (*mTypeMethod)(this); + mIsTypeMethod = false; + mTypeMethod = NULL; + break; + } + + case OpCode::OBJ_ADD: + { + auto left = mOperandsStack.getOperand(); + auto right = mOperandsStack.getOperand(); + + ASSERT(left->type == right->type && "addition of different types is not implemented"); + ASSERT(left->type->ariphmetics && left->type->ariphmetics->add && "cannot add object of this type"); + + auto res = NDO->instatiate(left); + res->type->ariphmetics->add(res, right); + + mScopeStack.addTemp(res); + mOperandsStack.push(res); + break; + } + case OpCode::OBJ_SUB: + { + auto left = mOperandsStack.getOperand(); + auto right = mOperandsStack.getOperand(); + + ASSERT(left->type == right->type && "addition of different types is not implemented"); + ASSERT(left->type->ariphmetics && left->type->ariphmetics->add && "cannot add object of this type"); + + auto res = NDO->instatiate(left); + res->type->ariphmetics->sub(res, right); + + mScopeStack.addTemp(res); + mOperandsStack.push(res); + break; + } + case OpCode::OBJ_MUL: + { + auto left = mOperandsStack.getOperand(); + auto right = mOperandsStack.getOperand(); + + ASSERT(left->type == right->type && "addition of different types is not implemented"); + ASSERT(left->type->ariphmetics && left->type->ariphmetics->add && "cannot add object of this type"); + + auto res = NDO->instatiate(left); + res->type->ariphmetics->mul(res, right); + + mScopeStack.addTemp(res); + mOperandsStack.push(res); + break; + } + case OpCode::OBJ_DIV: + { + auto left = mOperandsStack.getOperand(); + auto right = mOperandsStack.getOperand(); + + ASSERT(left->type == right->type && "addition of different types is not implemented"); + ASSERT(left->type->ariphmetics && left->type->ariphmetics->add && "cannot add object of this type"); + + auto res = NDO->instatiate(left); + res->type->ariphmetics->div(res, right); + + mScopeStack.addTemp(res); + mOperandsStack.push(res); + break; + } + + case OpCode::OBJ_COPY: + { + auto left = mOperandsStack.getOperand(); + auto right = mOperandsStack.getOperand(); + NDO->copy(left, right); + break; + } + + case OpCode::CHILD: + { + auto child_id = mOperandsStack.getOperand(); + auto parent = mOperandsStack.getOperand(); + bool is_method = read_byte(bytecode); + + Object* child = NULL; + TypeMethods::LookupKey tm_key; + + if (is_method) { + tm_key = TypeMethods::presents(parent->type, child_id->val); + } + + if (tm_key) { + mTypeMethod = TypeMethods::getMethod(parent->type, tm_key); + mIsTypeMethod = true; + + } else { + NDO_CASTV(ClassObject, parent, class_obj); + ASSERT(class_obj && "not a class object"); + auto idx = class_obj->members->presents(child_id->val); + ASSERT(idx && "No child with such id"); + child = class_obj->members->getSlotVal(idx); + } + + // mScopeStack.addTemp(obj); + mOperandsStack.push(child); + mLastParent = parent; + break; + } + + case OpCode::SELF: + { + // mScopeStack.addTemp(obj); + ASSERT(mCallStack.mStack.last().mSelf); + mOperandsStack.push(mCallStack.mStack.last().mSelf); + break; + } + + case OpCode::OBJ_LOAD: + { + auto path = mOperandsStack.getOperand(); + auto obj = NDO->load(path->val); + mScopeStack.addTemp(obj); + mOperandsStack.push(obj); + break; + } + case OpCode::OBJ_SAVE: + { + auto path = mOperandsStack.getOperand(); + auto target = mOperandsStack.getOperand(); + NDO->save(target, path->val); + break; + } + + case OpCode::AND: + { + auto left = NDO->toBool(mOperandsStack.getOperand()); + auto right = NDO->toBool(mOperandsStack.getOperand()); + auto out = BoolObject::create(left && right); + mScopeStack.addTemp(out); + mOperandsStack.push(out); + break; + } + case OpCode::OR: + { + auto left = NDO->toBool(mOperandsStack.getOperand()); + auto right = NDO->toBool(mOperandsStack.getOperand()); + auto out = BoolObject::create(left || right); + mScopeStack.addTemp(out); + mOperandsStack.push(out); + break; + } + case OpCode::NOT: + { + auto inv = NDO->toBool(mOperandsStack.getOperand()); + auto out = BoolObject::create(!inv); + mScopeStack.addTemp(out); + mOperandsStack.push(out); + break; + } + case OpCode::NOT_EQUAL: + { + auto left = mOperandsStack.getOperand(); + auto right = mOperandsStack.getOperand(); + auto out = BoolObject::create(!NDO->compare(left, right)); + mScopeStack.addTemp(out); + mOperandsStack.push(out); + break; + } + case OpCode::EQUAL: + { + auto left = mOperandsStack.getOperand(); + auto right = mOperandsStack.getOperand(); + auto out = BoolObject::create(NDO->compare(left, right)); + mScopeStack.addTemp(out); + mOperandsStack.push(out); + break; + } + + case OpCode::MORE: + { + auto left = NDO->toFloat(mOperandsStack.getOperand()); + auto right = NDO->toFloat(mOperandsStack.getOperand()); + auto out = BoolObject::create(left > right); + mScopeStack.addTemp(out); + mOperandsStack.push(out); + break; + } + case OpCode::LESS: + { + auto left = NDO->toFloat(mOperandsStack.getOperand()); + auto right = NDO->toFloat(mOperandsStack.getOperand()); + auto out = BoolObject::create(left < right); + mScopeStack.addTemp(out); + mOperandsStack.push(out); + break; + } + case OpCode::EQUAL_OR_MORE: + { + auto left = NDO->toFloat(mOperandsStack.getOperand()); + auto right = NDO->toFloat(mOperandsStack.getOperand()); + auto out = BoolObject::create(left >= right); + mScopeStack.addTemp(out); + mOperandsStack.push(out); + break; + } + case OpCode::EQUAL_OR_LESS: + { + auto left = NDO->toFloat(mOperandsStack.getOperand()); + auto right = NDO->toFloat(mOperandsStack.getOperand()); + auto out = BoolObject::create(left <= right); + mScopeStack.addTemp(out); + mOperandsStack.push(out); + break; + } + + default: + { + ASSERT("Invalid OpCode"); + } + } +} + +void Interpreter::execAll(obj::MethodObject* method, obj::ClassObject* self, obj::DictObject* globals, tp::InitialierList globals2) { + if (!method->mScript->mBytecode.mInstructions.size()) { + return; + } + + exec(method, self, globals, globals2); + while (!finished()) { + stepBytecodeIn(); + } } \ No newline at end of file diff --git a/Objects/private/interpreter/opcodes.cpp b/Objects/private/interpreter/opcodes.cpp index db9df0b..9dfb194 100644 --- a/Objects/private/interpreter/opcodes.cpp +++ b/Objects/private/interpreter/opcodes.cpp @@ -1,384 +1,371 @@ - -#include "Utils.hpp" - -#include "interpreter/opcodes.h" - -namespace obj { - OpcodeInfos gOpcodeInfos; -}; - -using namespace obj; - -#define CONST_IDX_BYTES 2 - -#define OP(opcode, name, desc, ops, params) \ - add(opcode, { #name, #desc, ops, params } ); - -OpcodeInfos::OperandsInfo::OperandsInfo() {} -OpcodeInfos::OperandsInfo::OperandsInfo(tp::InitialierList list) { - DEBUG_ASSERT(MAX_OPERANDS >= list.size()); - for (auto item : list) { - buff[len] = item; - len++; - } -} - -OpcodeInfos::ParamsInfo::ParamsInfo() {} -OpcodeInfos::ParamsInfo::ParamsInfo(tp::InitialierList list) { - DEBUG_ASSERT(MAX_PARAMS >= list.size()); - for (auto item : list) { - buff[len] = item; - len++; - } -} - -tp::uint1 OpcodeInfos::OpInfo::opsize() { - tp::uint1 out = 1; - for (auto i = 0; i < params.len; i++) { - out += params.buff[i].bytes; - } - return out; -} - -OpcodeInfos::OpcodeInfos() { - - add(OpCode::NONE, { "NONE", "Does Nothing" }); - add(OpCode::HALT, { "HALT", "Halts for 3 sec" }); - add(OpCode::TERMINATE, { "TERMINATE", "Terminates the process" }); - add(OpCode::DEF_LOCAL, { - .name = "DEF LOCAL", - .desc = "Adds object to the locals", - .operands = { - { "str", "local id" }, - { "any", "object to be local" } - } - } - ); - add(OpCode::LOAD_CONST, { - .name = "LOAD CONST", - .desc = "Loads const object from the const pool", - .params = { - { "const obj idx", CONST_IDX_BYTES }, - } - } - ); - add(OpCode::LOAD_LOCAL, { - .name = "LOAD LOCAL", - .desc = "Loads local object from the locals", - .params = { - { "idx of const StringObject - represents name id", CONST_IDX_BYTES }, - } - } - ); - add(OpCode::IGNORE, { - .name = "IGNORE", - .desc = "Ignores returned object by destroying it", - } - ); - add(OpCode::SCOPE_IN, { - .name = "SCOPE IN", - .desc = "Enters new scope", - } - ); - add(OpCode::SCOPE_OUT, { - .name = "SCOPE OUT", - .desc = "Leaves current scope", - } - ); - add(OpCode::CALL, { - .name = "CALL", - .desc = "Leaves current scope", - .operands = { - { "method", "method object" }, - } - } - ); - add(OpCode::RETURN_OBJ, { - .name = "RETURN OBJ", - .desc = "Returns Operand", - .operands = { - { "any", "object to be returned" }, - } - } - ); - add(OpCode::RETURN, { - .name = "RETURN", - .desc = "Returns Null Object", - } - ); - add(OpCode::CHILD, { - .name = "CHILD", - .desc = "Retrieves child from class", - .operands = { - { "str", "child id" }, - { "class", "parent class" }, - }, - .params = { - { "is method ?", 1 } - } - } - ); - add(OpCode::PUSH_ARGS, { - .name = "PUSH ARGS", - .desc = "Pushes Separator on the OperandsStack", - .params = { - { "length to chech number of args", 1 } - } - } - ); - add(OpCode::SAVE_ARGS, { - .name = "SAVE ARGS", - .desc = "Pushes operands to locals", - .params = { - { "number of arguments in function defenition", 1 } - } - } - ); - add(OpCode::OBJ_CREATE_LOCAL, { - .name = "CREATE LOCAL OBJ", - .desc = "creates object of given type and adds it to the locals", - .operands = { - { "str", "types" }, - { "str", "name id" }, - } - } - ); - add(OpCode::OBJ_CREATE, { - .name = "CREATE OBJ", - .desc = "creates object of given type", - .operands = { - { "str", "types" }, - } - } - ); - add(OpCode::OBJ_COPY, { - .name = "COPY", - .desc = "Copies objects", - .operands = { - { "any", "self" }, - { "any", "target" }, - } - } - ); - add(OpCode::OBJ_SAVE, { - .name = "SAVE", - .desc = "Saves object to a file", - .operands = { - { "str", "path" }, - { "any", "self" }, - } - } - ); - add(OpCode::OBJ_LOAD, { - .name = "LOAD", - .desc = "loads object from a file", - .operands = { - { "str", "path" }, - { "any", "self" }, - } - } - ); - add(OpCode::OBJ_ADD, { - .name = "ADD", - .desc = "Adds objects of the same type that supports ariphmetics", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::OBJ_SUB, { - .name = "SUB", - .desc = "Subtruts objects of the same type that supports ariphmetics", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::OBJ_MUL, { - .name = "MUL", - .desc = "Multiplies objects of the same type that supports ariphmetics", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::OBJ_DIV, { - .name = "DIV", - .desc = "Divides objects of the same type that supports ariphmetics", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::AND, { - .name = "AND", - .desc = "Logical AND of objects of the same type that supports boolean ariphmetics", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::OR, { - .name = "OR", - .desc = "Logical OR of objects of the same type that supports boolean ariphmetics", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::EQUAL, { - .name = "EQUAL", - .desc = "Compares objects", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::NOT_EQUAL, { - .name = "NOT EQUAL", - .desc = "Compares objects and inverts the resault", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::MORE, { - .name = "MORE", - .desc = " > ", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::LESS, { - .name = "LESS", - .desc = " < ", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::EQUAL_OR_MORE, { - .name = "GRATER OR EQUAL", - .desc = " >= ", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::EQUAL_OR_LESS, { - .name = "LESS OR EQUAL", - .desc = " <= ", - .operands = { - { "any", "left" }, - { "any", "right" }, - } - } - ); - add(OpCode::NOT, { - .name = "NOT", - .desc = "Inverts the object bolean representation", - .operands = { - { "any", "self" }, - } - } - ); - add(OpCode::JUMP, { - .name = "JUMP", - .desc = "Offsets the instruction pointer", - .params = { - { "ip offset unsigned", 2 }, - } - } - ); - add(OpCode::JUMP_R, { - .name = "JUMP R", - .desc = "Offsets the instruction pointer in reversed direction", - .params = { - { "ip offset unsigned", 2 }, - } - } - ); - add(OpCode::JUMP_IF, { - .name = "JUMP IF", - .desc = "Offsets the instruction pointer if condition is met", - .operands = { - { "any", "condition object" }, - }, - .params = { - { "ip offset unsigned", 2 }, - } - } - ); - add(OpCode::JUMP_IF_R, { - .name = "JUMP IF R", - .desc = "Offsets the instruction pointer in reversed direction if condition is met", - .operands = { - { "any", "condition object" }, - }, - .params = { - { "ip offset unsigned", 2 }, - } - } - ); - add(OpCode::JUMP_IF_NOT, { - .name = "JUMP IF R", - .desc = "Offsets the instruction pointer if condition is NOT met", - .operands = { - { "any", "condition object" }, - }, - .params = { - { "ip offset unsigned", 2 }, - } - } - ); - add(OpCode::JUMP_IF_NOT_R, { - .name = "JUMP IF R", - .desc = "Offsets the instruction pointer in reversed direction if condition is NOT met", - .operands = { - { "any", "condition object" }, - }, - .params = { - { "ip offset unsigned", 2 }, - } - } - ); - add(OpCode::PRINT, { - .name = "PRINT", - .desc = "Prints the object string representation", - .operands = { - { "any", "self" }, - } - } - ); - add(OpCode::CLASS_CONSTRUCT, { - .name = "CLASS CONSTRUCT", - .desc = "Creates class from the function execution state", - } - ); - add(OpCode::SELF, { - .name = "SELF", - .desc = "retrieves parent class of the current method", - } - ); -} - -OpcodeInfos::OpInfo OpcodeInfos::fetch(OpCode code) { - DEBUG_ASSERT((tp::alni)code >= 0 && (tp::alni)code < (tp::alni)OpCode::END_OPCODES); - return buff[(tp::alni)code]; -} - -void OpcodeInfos::add(OpCode code, const OpInfo& info) { - buff[(tp::alni)code] = info; -} \ No newline at end of file + +#include "Utils.hpp" + +#include "interpreter/opcodes.h" + +namespace obj { + OpcodeInfos gOpcodeInfos; +}; + +using namespace obj; + +#define CONST_IDX_BYTES 2 + +#define OP(opcode, name, desc, ops, params) add(opcode, { #name, #desc, ops, params }); + +OpcodeInfos::OperandsInfo::OperandsInfo() {} +OpcodeInfos::OperandsInfo::OperandsInfo(tp::InitialierList list) { + DEBUG_ASSERT(MAX_OPERANDS >= list.size()); + for (auto item : list) { + buff[len] = item; + len++; + } +} + +OpcodeInfos::ParamsInfo::ParamsInfo() {} +OpcodeInfos::ParamsInfo::ParamsInfo(tp::InitialierList list) { + DEBUG_ASSERT(MAX_PARAMS >= list.size()); + for (auto item : list) { + buff[len] = item; + len++; + } +} + +tp::uint1 OpcodeInfos::OpInfo::opsize() { + tp::uint1 out = 1; + for (auto i = 0; i < params.len; i++) { + out += params.buff[i].bytes; + } + return out; +} + +OpcodeInfos::OpcodeInfos() { + + add(OpCode::NONE, { "NONE", "Does Nothing" }); + add(OpCode::HALT, { "HALT", "Halts for 3 sec" }); + add(OpCode::TERMINATE, { "TERMINATE", "Terminates the process" }); + add(OpCode::DEF_LOCAL, { .name = "DEF LOCAL", .desc = "Adds object to the locals", .operands = { { "str", "local id" }, { "any", "object to be local" } } }); + add(OpCode::LOAD_CONST, { + .name = "LOAD CONST", + .desc = "Loads const object from the const pool", + .params = { + { "const obj idx", CONST_IDX_BYTES }, + } + } + ); + add(OpCode::LOAD_LOCAL, { + .name = "LOAD LOCAL", + .desc = "Loads local object from the locals", + .params = { + { "idx of const StringObject - represents name id", CONST_IDX_BYTES }, + } + } + ); + add( + OpCode::IGNORE, + { + .name = "IGNORE", + .desc = "Ignores returned object by destroying it", + } + ); + add( + OpCode::SCOPE_IN, + { + .name = "SCOPE IN", + .desc = "Enters new scope", + } + ); + add( + OpCode::SCOPE_OUT, + { + .name = "SCOPE OUT", + .desc = "Leaves current scope", + } + ); + add(OpCode::CALL, { + .name = "CALL", + .desc = "Leaves current scope", + .operands = { + { "method", "method object" }, + } + } + ); + add(OpCode::RETURN_OBJ, { + .name = "RETURN OBJ", + .desc = "Returns Operand", + .operands = { + { "any", "object to be returned" }, + } + } + ); + add( + OpCode::RETURN, + { + .name = "RETURN", + .desc = "Returns Null Object", + } + ); + add(OpCode::CHILD, { + .name = "CHILD", + .desc = "Retrieves child from class", + .operands = { + { "str", "child id" }, + { "class", "parent class" }, + }, + .params = { + { "is method ?", 1 } + } + } + ); + add(OpCode::PUSH_ARGS, { .name = "PUSH ARGS", .desc = "Pushes Separator on the OperandsStack", .params = { { "length to chech number of args", 1 } } }); + add(OpCode::SAVE_ARGS, { .name = "SAVE ARGS", .desc = "Pushes operands to locals", .params = { { "number of arguments in function defenition", 1 } } }); + add(OpCode::OBJ_CREATE_LOCAL, { + .name = "CREATE LOCAL OBJ", + .desc = "creates object of given type and adds it to the locals", + .operands = { + { "str", "types" }, + { "str", "name id" }, + } + } + ); + add(OpCode::OBJ_CREATE, { + .name = "CREATE OBJ", + .desc = "creates object of given type", + .operands = { + { "str", "types" }, + } + } + ); + add(OpCode::OBJ_COPY, { + .name = "COPY", + .desc = "Copies objects", + .operands = { + { "any", "self" }, + { "any", "target" }, + } + } + ); + add(OpCode::OBJ_SAVE, { + .name = "SAVE", + .desc = "Saves object to a file", + .operands = { + { "str", "path" }, + { "any", "self" }, + } + } + ); + add(OpCode::OBJ_LOAD, { + .name = "LOAD", + .desc = "loads object from a file", + .operands = { + { "str", "path" }, + { "any", "self" }, + } + } + ); + add(OpCode::OBJ_ADD, { + .name = "ADD", + .desc = "Adds objects of the same type that supports ariphmetics", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::OBJ_SUB, { + .name = "SUB", + .desc = "Subtruts objects of the same type that supports ariphmetics", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::OBJ_MUL, { + .name = "MUL", + .desc = "Multiplies objects of the same type that supports ariphmetics", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::OBJ_DIV, { + .name = "DIV", + .desc = "Divides objects of the same type that supports ariphmetics", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::AND, { + .name = "AND", + .desc = "Logical AND of objects of the same type that supports boolean ariphmetics", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::OR, { + .name = "OR", + .desc = "Logical OR of objects of the same type that supports boolean ariphmetics", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::EQUAL, { + .name = "EQUAL", + .desc = "Compares objects", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::NOT_EQUAL, { + .name = "NOT EQUAL", + .desc = "Compares objects and inverts the resault", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::MORE, { + .name = "MORE", + .desc = " > ", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::LESS, { + .name = "LESS", + .desc = " < ", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::EQUAL_OR_MORE, { + .name = "GRATER OR EQUAL", + .desc = " >= ", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::EQUAL_OR_LESS, { + .name = "LESS OR EQUAL", + .desc = " <= ", + .operands = { + { "any", "left" }, + { "any", "right" }, + } + } + ); + add(OpCode::NOT, { + .name = "NOT", + .desc = "Inverts the object bolean representation", + .operands = { + { "any", "self" }, + } + } + ); + add(OpCode::JUMP, { + .name = "JUMP", + .desc = "Offsets the instruction pointer", + .params = { + { "ip offset unsigned", 2 }, + } + } + ); + add(OpCode::JUMP_R, { + .name = "JUMP R", + .desc = "Offsets the instruction pointer in reversed direction", + .params = { + { "ip offset unsigned", 2 }, + } + } + ); + add(OpCode::JUMP_IF, { + .name = "JUMP IF", + .desc = "Offsets the instruction pointer if condition is met", + .operands = { + { "any", "condition object" }, + }, + .params = { + { "ip offset unsigned", 2 }, + } + } + ); + add(OpCode::JUMP_IF_R, { + .name = "JUMP IF R", + .desc = "Offsets the instruction pointer in reversed direction if condition is met", + .operands = { + { "any", "condition object" }, + }, + .params = { + { "ip offset unsigned", 2 }, + } + } + ); + add(OpCode::JUMP_IF_NOT, { + .name = "JUMP IF R", + .desc = "Offsets the instruction pointer if condition is NOT met", + .operands = { + { "any", "condition object" }, + }, + .params = { + { "ip offset unsigned", 2 }, + } + } + ); + add(OpCode::JUMP_IF_NOT_R, { + .name = "JUMP IF R", + .desc = "Offsets the instruction pointer in reversed direction if condition is NOT met", + .operands = { + { "any", "condition object" }, + }, + .params = { + { "ip offset unsigned", 2 }, + } + } + ); + add(OpCode::PRINT, { + .name = "PRINT", + .desc = "Prints the object string representation", + .operands = { + { "any", "self" }, + } + } + ); + add( + OpCode::CLASS_CONSTRUCT, + { + .name = "CLASS CONSTRUCT", + .desc = "Creates class from the function execution state", + } + ); + add( + OpCode::SELF, + { + .name = "SELF", + .desc = "retrieves parent class of the current method", + } + ); +} + +OpcodeInfos::OpInfo OpcodeInfos::fetch(OpCode code) { + DEBUG_ASSERT((tp::alni) code >= 0 && (tp::alni) code < (tp::alni) OpCode::END_OPCODES); + return buff[(tp::alni) code]; +} + +void OpcodeInfos::add(OpCode code, const OpInfo& info) { buff[(tp::alni) code] = info; } \ No newline at end of file diff --git a/Objects/private/interpreter/operandsstack.cpp b/Objects/private/interpreter/operandsstack.cpp index 75799d8..e4de0a2 100644 --- a/Objects/private/interpreter/operandsstack.cpp +++ b/Objects/private/interpreter/operandsstack.cpp @@ -1,32 +1,30 @@ - -#include "NewPlacement.hpp" - -#include "interpreter/operandsstack.h" - -using namespace obj; - -OperandStack::OperandStack() { - mBuff = new Operand[MAX_STACK_SIZE]; - mIdx = 0; -} - -void OperandStack::push(Operand operand) { - ASSERT(MAX_STACK_SIZE - 1 > mIdx && "stack overflow"); - mBuff[mIdx] = operand; - mIdx++; -} - -void OperandStack::pop() { - ASSERT(mIdx != NULL && "stack overflow"); - mIdx--; -} - -Operand OperandStack::getOperand() { - auto ret = mBuff[mIdx - 1]; - mIdx--; - return ret; -} - -OperandStack::~OperandStack() { - delete[] mBuff; -} + +#include "NewPlacement.hpp" + +#include "interpreter/operandsstack.h" + +using namespace obj; + +OperandStack::OperandStack() { + mBuff = new Operand[MAX_STACK_SIZE]; + mIdx = 0; +} + +void OperandStack::push(Operand operand) { + ASSERT(MAX_STACK_SIZE - 1 > mIdx && "stack overflow"); + mBuff[mIdx] = operand; + mIdx++; +} + +void OperandStack::pop() { + ASSERT(mIdx != NULL && "stack overflow"); + mIdx--; +} + +Operand OperandStack::getOperand() { + auto ret = mBuff[mIdx - 1]; + mIdx--; + return ret; +} + +OperandStack::~OperandStack() { delete[] mBuff; } diff --git a/Objects/private/interpreter/scopestack.cpp b/Objects/private/interpreter/scopestack.cpp index f00e408..cdffaee 100644 --- a/Objects/private/interpreter/scopestack.cpp +++ b/Objects/private/interpreter/scopestack.cpp @@ -1,90 +1,85 @@ - -#include "NewPlacement.hpp" - -#include "interpreter/scopestack.h" - -using namespace obj; - -Scope::~Scope() { - for (auto local : mLocals) { - obj::NDO->destroy(local->val); - } - for (auto tmp : mTemps) { - obj::NDO->destroy(tmp.data()); - } -} - -obj::Object* ScopeStack::getLocalUtil(Scope& scope, tp::String* id) { - - auto idx = scope.mLocals.presents(*id); - - if (idx) { - return scope.mLocals.getSlotVal(idx); - } - else { - mIterIdx--; - Scope& parent_scope = mBuff[mIterIdx]; - ASSERT(parent_scope.mChildReachable && "Undefined Local Reference"); - return getLocalUtil(parent_scope, id); - } -} - -ScopeStack::ScopeStack() { - mBuff = (Scope*) tp::HeapAllocGlobal::allocate(sizeof(Scope) * MAX_STACK_SIZE); - mIdx = 0; - mIterIdx = 0; -} - -void ScopeStack::enterScope(bool aChildReachable) { - ASSERT(MAX_STACK_SIZE - 1 > mIdx && "stack overflow"); - new (&mBuff[mIdx]) Scope(); - mBuff[mIdx].mChildReachable = aChildReachable; - mIdx++; -} - -void ScopeStack::leaveScope() { - ASSERT(mIdx != NULL && "stack overflow"); - mBuff[mIdx - 1].~Scope(); - mIdx--; -} - -void ScopeStack::addTemp(obj::Object* tmp) { - obj::NDO->refinc(tmp); - mBuff[mIdx - 1].mTemps.pushBack(tmp); -} - -void ScopeStack::popTemp() { - obj::NDO->destroy(mBuff[mIdx - 1].mTemps.last()->data); - mBuff[mIdx - 1].mTemps.popBack(); -} - -void ScopeStack::addTempReturn(obj::Object* ret) { - if (mIdx >= 2) { - obj::NDO->refinc(ret); - mBuff[mIdx - 2].mTemps.pushBack(ret); - } -} - -void ScopeStack::addLocal(obj::Object* local, tp::String id) { - DEBUG_ASSERT(mIdx != 0 && "No scope given"); - Scope::ObjDict& locals = mBuff[mIdx - 1].mLocals; - auto idx = locals.presents(id); - if (idx) { - obj::NDO->destroy(locals.getSlotVal(idx)); - } - obj::NDO->refinc(local); - locals.put(id, local); -} - -obj::Object* ScopeStack::getLocal(tp::String& str) { - mIterIdx = mIdx - 1; - return getLocalUtil(mBuff[mIdx - 1], &str); -} - -Scope* ScopeStack::getCurrentScope() { - return &mBuff[mIdx - 1]; -} - -ScopeStack::~ScopeStack() { - tp::HeapAllocGlobal::deallocate(mBuff); -} + +#include "NewPlacement.hpp" + +#include "interpreter/scopestack.h" + +using namespace obj; + +Scope::~Scope() { + for (auto local : mLocals) { + obj::NDO->destroy(local->val); + } + for (auto tmp : mTemps) { + obj::NDO->destroy(tmp.data()); + } +} + +obj::Object* ScopeStack::getLocalUtil(Scope& scope, tp::String* id) { + + auto idx = scope.mLocals.presents(*id); + + if (idx) { + return scope.mLocals.getSlotVal(idx); + } else { + mIterIdx--; + Scope& parent_scope = mBuff[mIterIdx]; + ASSERT(parent_scope.mChildReachable && "Undefined Local Reference"); + return getLocalUtil(parent_scope, id); + } +} + +ScopeStack::ScopeStack() { + mBuff = (Scope*) tp::HeapAllocGlobal::allocate(sizeof(Scope) * MAX_STACK_SIZE); + mIdx = 0; + mIterIdx = 0; +} + +void ScopeStack::enterScope(bool aChildReachable) { + ASSERT(MAX_STACK_SIZE - 1 > mIdx && "stack overflow"); + new (&mBuff[mIdx]) Scope(); + mBuff[mIdx].mChildReachable = aChildReachable; + mIdx++; +} + +void ScopeStack::leaveScope() { + ASSERT(mIdx != NULL && "stack overflow"); + mBuff[mIdx - 1].~Scope(); + mIdx--; +} + +void ScopeStack::addTemp(obj::Object* tmp) { + obj::NDO->refinc(tmp); + mBuff[mIdx - 1].mTemps.pushBack(tmp); +} + +void ScopeStack::popTemp() { + obj::NDO->destroy(mBuff[mIdx - 1].mTemps.last()->data); + mBuff[mIdx - 1].mTemps.popBack(); +} + +void ScopeStack::addTempReturn(obj::Object* ret) { + if (mIdx >= 2) { + obj::NDO->refinc(ret); + mBuff[mIdx - 2].mTemps.pushBack(ret); + } +} + +void ScopeStack::addLocal(obj::Object* local, tp::String id) { + DEBUG_ASSERT(mIdx != 0 && "No scope given"); + Scope::ObjDict& locals = mBuff[mIdx - 1].mLocals; + auto idx = locals.presents(id); + if (idx) { + obj::NDO->destroy(locals.getSlotVal(idx)); + } + obj::NDO->refinc(local); + locals.put(id, local); +} + +obj::Object* ScopeStack::getLocal(tp::String& str) { + mIterIdx = mIdx - 1; + return getLocalUtil(mBuff[mIdx - 1], &str); +} + +Scope* ScopeStack::getCurrentScope() { return &mBuff[mIdx - 1]; } + +ScopeStack::~ScopeStack() { tp::HeapAllocGlobal::deallocate(mBuff); } diff --git a/Objects/private/parser/parser.cpp b/Objects/private/parser/parser.cpp index 8c159d7..3ce2330 100644 --- a/Objects/private/parser/parser.cpp +++ b/Objects/private/parser/parser.cpp @@ -1,919 +1,840 @@ - -#include "Logging.hpp" -#include "List.hpp" - -#include "parser/parser.h" -#include "compiler/function.h" - -#include - -#define MAX_STREAM_LENGTH 1024 * 8 * 200 - -#define REQUIRE(expr, desc, on_catch) DEBUG_BREAK(mRes.err); if (!(expr)) { mRes.err = new Error(desc, mTok.getCursorPrev().mAdvancedOffset); on_catch; return NULL; } -#define CHECK(expr, on_catch) if (!(expr)) { on_catch; return NULL; } -#define CHECK_ERROR(value, on_catch) if (mRes.err || !value) { on_catch; return NULL; } - -using namespace tp; -using namespace obj; -using namespace BCgen; - -bool Parser::Token::isAriphm() { - switch (type) { - case Token::ADD: - case Token::SUB: - case Token::DIV: - case Token::MUL: - return true; - default: - return false; - } -} - -bool Parser::Token::isBoolean() { - switch (type) { - case Token::EQUAL: - case Token::NOT_EQUAL: - case Token::BOOL_AND: - case Token::BOOL_OR: - case Token::MORE: - case Token::LESS: - case Token::QE_OR_MORE: - case Token::QE_OR_LESS: - return true; - default: - return false; - } -} - -Parser::Parser() { - mTok.build({ - { "\n|\t| |\r", Token::SPACE }, - { "var", Token::VAR }, - { "class", Token::CLASS_DEF }, - { "self", Token::SELF }, - { "\\{", Token::SCOPE_IN }, - { "\\}", Token::SCOPE_OUT }, - { "=", Token::ASSIGN }, - { "def", Token::DEF_FUNC }, - { "<<", Token::PRINT }, - { "if", Token::IF }, - { "else", Token::ELSE }, - { "while", Token::WHILE }, - { "\\(", Token::BRACKET_IN }, - { "\\)", Token::BRACKET_OUT }, - { ",", Token::COMMA }, - { "new", Token::NEW }, - { "\\.", Token::CHILD }, - { "return", Token::RETURN }, - { "==", Token::EQUAL }, - { "!=", Token::NOT_EQUAL }, - { ">", Token::MORE }, - { "<", Token::LESS }, - { ">=", Token::QE_OR_MORE }, - { "<=", Token::QE_OR_LESS }, - { "!", Token::BOOL_NOT }, - { "&&", Token::BOOL_AND }, - { "\\|\\|", Token::BOOL_OR }, - { "\\+", Token::ADD }, - { "\\*", Token::MUL }, - { "\\-", Token::SUB }, - { "/", Token::DIV }, - { ";", Token::STM_END }, - { "true", Token::CONST_TRUE }, - { "false", Token::CONST_FALSE }, - { "((\\-)|(\\+))?[0-9]+i?", Token::CONST_INT }, - { R"(((\-)|(\+))?([0-9]+)(\.)([0-9]*)?f?)", Token::CONST_FLOAT }, - { R"((/\*){\*-\*}*(\*/))", Token::COMMENT_BLOCK }, - { R"("{"-"}*")", Token::CONST_STRING }, - - { "([a-z]|[A-Z]|_)+([a-z]|[A-Z]|[0-9]|_)*", Token::ID }, - }); -} - -tp::String to_string(const char* stream, tp::alni len) { - tp::String out; - out.resize(len); - tp::memCopy(out.write(), stream, len); - return out; -} - -Parser::Token Parser::tokRead() { - Token out; - - if (!tokInputLeft()) { - Token out; - out.type = Token::NO_TOKEN; - return out; - } - - auto crs_start = mTok.getCursor(); - out.type = mTok.readTok(); - out.token = to_string(crs_start.str(), mTok.lastTokLEn()); - - switch (out.type) { - case Token::CONST_FALSE: - out.boolean = false; - break; - case Token::CONST_TRUE: - out.boolean = true; - break; - case Token::CONST_INT: { - char* p_end; - out.integer = std::strtol(out.token.read(), &p_end, 10); - DEBUG_ASSERT(out.token.read() != p_end); - break; - } - case Token::CONST_FLOAT: { - char* p_end; - out.floating = std::strtod(out.token.read(), &p_end); - DEBUG_ASSERT(out.token.read() != p_end); - break; - } - case Token::CONST_STRING: { - out.str = to_string(crs_start.str() + 1, mTok.lastTokLEn() - 2); - break; - } - } - - return out; -} - -Parser::Token Parser::tokLookup() { - auto crs = mTok.getCursor(); - auto out = tokRead(); - mTok.setCursor(crs); - return out; -} - -bool Parser::tokInputLeft() { - auto type = mTok.lookupTok(); - - while (mTok.isInputLeft() && type == Token::SPACE || (type >= Token::__END__ && type <= Token::__START__)) { - mTok.skipTok(); - type = mTok.lookupTok(); - } - - return type != Token::SOURCE_END_TOKEN; -} - -void Parser::tokSkip() { - if (!tokInputLeft()) { - return; - } - mTok.skipTok(); -} - -Parser::Tokenizer::Cursor Parser::tokGetCursor() { return mTok.getCursor();} -void Parser::tokSetCursor(Tokenizer::Cursor crs) { mTok.setCursor(crs); } - -Expression* Parser::parseExprCompound() { - CHECK(tokRead() == Token::BRACKET_IN, {}); - auto ret = parseExpr(); - CHECK_ERROR(ret, {}); - REQUIRE(tokRead() == Token::BRACKET_OUT, "Expected Closing Bracket", {}); - return ret; -} - -Expression* Parser::parseExprNEW() { - CHECK(tokRead() == Token::NEW, {}); - auto name = tokRead(); - REQUIRE(name == Token::ID, "Expected Identifier", {}); - - REQUIRE(tokRead() == Token::BRACKET_IN, "Expected opening brackets", {}); - REQUIRE(tokRead() == Token::BRACKET_OUT, "Expected closing brackets", {}); - - return ExprNew(name.token); -} - -Expression* Parser::parseExprLOCAL() { - auto local_id_tok = tokRead(); - if (local_id_tok == Token::ID) { - return ExprLocal(local_id_tok.token); - } - else if (local_id_tok == Token::SELF) { - return ExprSelf(); - } - return NULL; -} - -Expression* Parser::parseExprCONST() { - auto tok = tokRead(); - switch (tok) { - case Token::CONST_FALSE: - return ExprConst(false); - case Token::CONST_TRUE: - return ExprConst(true); - case Token::CONST_INT: - return ExprConst(tok.integer); - case Token::CONST_FLOAT: - return ExprConst(tok.floating); - case Token::CONST_STRING: - return ExprConst(tok.str); - default: - REQUIRE(0, "not a const Expr", {}); - } -} - -Expression* Parser::parseExprCHILD(Expression* prnt) { - CHECK(tokRead() == Token::CHILD, {}); - auto id = tokRead(); - REQUIRE(id == Token::ID, "Exprected Identifier", {}); - return prnt->ExprChild(id.str); -} - -Expression* Parser::parseExprCALL(Expression* prnt) { - CHECK(tokRead() == Token::BRACKET_IN, {}); - - List args; - -READ_ARG: - Expression* expr = NULL; - auto tok = tokLookup(); - REQUIRE(tok != Token::NO_TOKEN, "Missing Closing Bracket", {}); - - if (tok != Token::BRACKET_OUT) { - - expr = parseExpr(); - CHECK_ERROR(expr, { - for (auto arg : args) { - delete arg.data(); - } - }); - - args.pushBack(expr); - - tok = tokLookup(); - if (tok == Token::COMMA) { - tokSkip(); - goto READ_ARG; - } - else if (tok != Token::BRACKET_OUT) { - for (auto arg : args) { - delete arg.data(); - } - REQUIRE(0, "Expected A Closing Bracket", {}); - } - } - tokSkip(); - - auto out = prnt->ExprCall({}); - out->mArgs.reserve(args.length()); - - ualni idx = 0; - for (auto arg : args) { - out->mArgs[idx] = arg.data(); - idx++; - } - - return out; -} - -Expression* Parser::parseExprAriphm() { - - tp::InitialierList expessions = { - ExprType::Compound, - ExprType::NEW, - ExprType::LOCAL, - ExprType::CONST, - }; - - Expression* left = parseExpr(expessions); - CHECK_ERROR(left, {}); - - Expression* ret = NULL; - -PARSE: - - Expression* right = NULL; - - auto tok = tokLookup(); - if (tok.isAriphm()) { - tokSkip(); - - - right = parseExpr(expessions); - - if (mRes.err) { - if (ret) { - goto PRECEDENCE; - } - - delete left; - return NULL; - } - - } - else { - CHECK(ret, { - delete left; - }); - goto PRECEDENCE; - } - - switch (tok) { - case Token::ADD: - ret = ExprAriphm(left, right, OpCode::OBJ_ADD); - break; - case Token::SUB: - ret = ExprAriphm(left, right, OpCode::OBJ_SUB); - break; - case Token::DIV: - ret = ExprAriphm(left, right, OpCode::OBJ_DIV); - break; - case Token::MUL: - ret = ExprAriphm(left, right, OpCode::OBJ_MUL); - } - - left = ret; - goto PARSE; - -PRECEDENCE: - // FIXME: Not Implemented - - return ret; -} - -Expression* Parser::parseExprBOOLEAN() { - - tp::InitialierList expessions = { - ExprType::Compound, - ExprType::NEW, - ExprType::LOCAL, - ExprType::CONST, - ExprType::BOOLEAN_NOT, - }; - - - Expression* left = parseExpr(expessions); - CHECK_ERROR(left, {}); - - Expression* ret = NULL; - -PARSE: - - Expression* right = NULL; - - auto tok = tokLookup(); - if (tok.isBoolean()) { - tokSkip(); - - right = parseExpr(expessions); - - if (mRes.err) { - if (ret) { - goto PRECEDENCE; - } - - delete left; - return NULL; - } - - } - else { - CHECK(ret, { - delete left; - }); - goto PRECEDENCE; - } - - switch (tok) { - case Token::EQUAL: - ret = ExprBool(left, right, OpCode::EQUAL); - break; - case Token::NOT_EQUAL: - ret = ExprBool(left, right, OpCode::NOT_EQUAL); - break; - case Token::BOOL_AND: - ret = ExprBool(left, right, OpCode::AND); - break; - case Token::BOOL_OR: - ret = ExprBool(left, right, OpCode::OR); - break; - case Token::MORE: - ret = ExprBool(left, right, OpCode::MORE); - break; - case Token::LESS: - ret = ExprBool(left, right, OpCode::LESS); - break; - case Token::QE_OR_MORE: - ret = ExprBool(left, right, OpCode::EQUAL_OR_MORE); - break; - case Token::QE_OR_LESS: - ret = ExprBool(left, right, OpCode::EQUAL_OR_LESS); - } - - left = ret; - goto PARSE; - -PRECEDENCE: - // FIXME: Not Implemented - - return ret; -} - -Expression* Parser::parseExprBOOLEAN_NOT() { - CHECK(tokRead() == Token::BOOL_NOT, {}); - - tp::InitialierList exprs = { - ExprType::Compound, - ExprType::BOOLEAN, - ExprType::Ariphm, - ExprType::NEW, - ExprType::LOCAL, - ExprType::CONST, - }; - - auto out = parseExpr(exprs); - CHECK_ERROR(out, {}); - - return ExprBoolNot(out); -} - -Expression* Parser::parseExprFUNC() { - auto op_tok = tokRead(); - CHECK(op_tok == Token::ID, {}); - return ExprFunc(op_tok.token); -} - -// passed prnt isno longer responsability of callee -// suc : returns top level parent -// err : returns NULL -Expression* Parser::parseExprChain(Expression* prnt) { - - PARSE_CHAIN: - auto tok = tokLookup(); - - switch (tok) { - case Token::CHILD: { - tokRead(); - - auto child_id = tokRead(); - REQUIRE(child_id == Token::ID, "expected an id", { - delete prnt; - }); - - prnt = prnt->ExprChild(child_id.token); - goto PARSE_CHAIN; - } - - case Token::BRACKET_IN: { - - auto new_prnt = parseExprCALL(prnt); - CHECK_ERROR(new_prnt, { - delete prnt; - }); - - if (prnt->mType == Expression::Type::CHILD) { - ((ExpressionChild*)prnt)->mMethod = true; - } - - prnt = new_prnt; - goto PARSE_CHAIN; - } - } - - return prnt; -} - -Expression* Parser::parseExpr(tp::InitialierList expressions) { - - Expression* out = NULL; - - List errors; - - for (auto expr_type : expressions) { - auto crs = tokGetCursor(); - switch (expr_type) { - case Parser::ExprType::BOOLEAN_NOT: - out = parseExprBOOLEAN_NOT(); - break; - case Parser::ExprType::BOOLEAN: - out = parseExprBOOLEAN(); - break; - case Parser::ExprType::Ariphm: - out = parseExprAriphm(); - break; - case Parser::ExprType::NEW: - out = parseExprNEW(); - break; - case Parser::ExprType::LOCAL: - out = parseExprLOCAL(); - break; - case Parser::ExprType::CONST: - out = parseExprCONST(); - break; - case Parser::ExprType::Compound: - out = parseExprCompound(); - break; - } - - if (out) { - break; - } - - tokSetCursor(crs); - if (mRes.err) { - errors.pushBack(mRes.err); - mRes.err = NULL; - } - } - - if (out) { - // check for child expression and calls - out = parseExprChain(out); - - // check errors - if (mRes.err) { - errors.pushBack(mRes.err); - mRes.err = NULL; - goto ERRORS; - } - - for (auto err : errors) { - delete err.data(); - } - - return out; - } - - ERRORS: - Error* error = NULL; - tp::alni max_advanced = 0; - for (auto err : errors) { - if (err.data()->mAdvanecedIdx && err.data()->mAdvanecedIdx > max_advanced) { - max_advanced = err.data()->mAdvanecedIdx; - error = err.data(); - } - } - - if (error) { - mRes.err = new Error(*error); - - for (auto err : errors) { - delete err.data(); - } - - return NULL; - } - REQUIRE(0, "Expected and expression", {}); -} - -Statement* Parser::parseStmCall() { - - Expression* expr = parseExpr(); - CHECK_ERROR(expr, {}); - - REQUIRE(expr->mType == Expression::Type::CALL, - "expression statement can only be function call", { - delete expr; - }); - - if (tokRead() != Token::STM_END) { - delete expr; - REQUIRE(0, "Expected End Of Statement", {}); - } - - return StmIgnore(expr); -} - -Statement* Parser::parseStmDefFunc() { - CHECK(tokRead() == Token::DEF_FUNC, {}); - List args; - auto name = tokRead(); - REQUIRE(name == Token::ID, "Expected an Identifier", {}); - - REQUIRE(tokRead() == Token::BRACKET_IN, "Expected Opening Bracket", {}); - -READ_ARG: - auto tok = tokLookup(); - - REQUIRE(tok != Token::NO_TOKEN, "Missing Closing Bracket", {}); - - if (tok == Token::ID) { - args.pushBack(tok.token); - tokSkip(); - tok = tokLookup(); - } - - if (tok == Token::COMMA) { - tokSkip(); - goto READ_ARG; - } - - REQUIRE(tok == Token::BRACKET_OUT, "Expected Closing Bracket", {}); - tokSkip(); - - auto func_def = StmDefFunc(name.token, {}, {}); - - func_def->mArgs.reserve(args.length()); - - ualni idx = 0; - for (auto iter : args) { - func_def->mArgs[idx] = iter.data(); - idx++; - } - - StatementScope* scope = parseScope(true); - CHECK_ERROR(scope, { - delete func_def; - }); - - func_def->mStatements.reserve(scope->mStatements.size()); - - idx = 0; - for (auto stm : scope->mStatements) { - func_def->mStatements[idx] = stm.data(); - idx++; - } - - delete scope; - return func_def; -} - -Statement* Parser::parseStmDefLocal() { - CHECK(tokRead() == Token::VAR, {}); - - auto tok = tokRead(); - REQUIRE(tok == Token::ID, "Expected an Identifier", {}); - REQUIRE(tokRead() == Token::ASSIGN, "Expected an assigment", {}); - - auto expr = parseExpr(); - CHECK_ERROR(expr, {}); - - if (tokRead() != Token::STM_END) { - delete expr; - REQUIRE(0, "Expected End Of Statement", {}); - } - - return StmDefLocal(tok.token, expr); -} - -Statement* Parser::parseStmReturn() { - CHECK(tokRead() == Token::RETURN, {}); - auto crs = tokGetCursor(); - - auto expr = parseExpr(); - if (mRes.err) { - tokSetCursor(crs); - delete mRes.err; - mRes.err = NULL; - } - - if (tokRead() != Token::STM_END) { - if (expr) delete expr; - REQUIRE(0, "Expected End Of Statement", {}); - } - - return expr ? StmReturn(expr) : StmReturn(); -} - -Statement* Parser::parseStmPrint() { - CHECK(tokRead() == Token::PRINT, {}); - auto expr = parseExpr(); - CHECK_ERROR(expr, {}); - - if (tokRead() != Token::STM_END) { - delete expr; - REQUIRE(0, "Expected End Of Statement", {}); - } - return StmPrint(expr); -} - -Statement* Parser::parseStmIf() { - CHECK(tokRead() == Token::IF, {}); - - // single if - REQUIRE(tokRead() == Token::BRACKET_IN, "Expected Opening Bracket", {}); - auto expr = parseExpr(); - CHECK_ERROR(expr, {}); - - if (tokRead() != Token::BRACKET_OUT) { - delete expr; - REQUIRE(0, "Expected Closing Bracket", {}); - } - - auto ontrue = parseScope(false); - CHECK_ERROR(ontrue, {}); - - // if-else - auto crs = tokGetCursor(); - if (tokRead() == Token::ELSE) { - StatementScope* onfalse = parseScope(false); - CHECK_ERROR(onfalse, { - delete ontrue; - delete expr; - }); - - return StmIf(expr, ontrue, onfalse); - } - tokSetCursor(crs); - - return StmIf(expr, ontrue, NULL); -} - -Statement* Parser::parseStmWhile() { - CHECK(tokRead() == Token::WHILE, {}); - - REQUIRE(tokRead() == Token::BRACKET_IN, "Expected Opening Bracket", {}); - auto expr = parseExpr(); - CHECK_ERROR(expr, {}); - - if (tokRead() != Token::BRACKET_OUT) { - delete expr; - REQUIRE(0, "Expected Closing Bracket", {}); - } - - auto scope = parseScope(false); - CHECK_ERROR(scope, {}); - - return StmWhile(expr, scope); -} - -Statement* Parser::parseStmCopy() { - auto left = parseExpr(); - CHECK_ERROR(left, {}); - - CHECK(tokRead() == Token::ASSIGN, {}); - - auto right = parseExpr(); - CHECK_ERROR(right, { - delete left; - }); - - if (tokRead() != Token::STM_END) { - delete left; - delete right; - REQUIRE(0, "Expected End Of Statement", {}); - } - - return StmCopy(left, right); -} - -Statement* Parser::parseStmClassDef() { - CHECK(tokRead() == Token::CLASS_DEF, {}); - - auto id = tokRead(); - REQUIRE(id == Token::ID, "Expected an Identifier", {}); - - auto scope = parseScope(true); - CHECK_ERROR(scope, {}); - - return StmClassDef(id.token, scope); -} - -Statement* Parser::parseStm(tp::InitialierList stm_types) { - Statement* out = NULL; - - List errors; - - for (auto stm_type : stm_types) { - auto crs = tokGetCursor(); - switch (stm_type) { - case StmType::DefFunc: - out = parseStmDefFunc(); - break; - case StmType::DefLocal: - out = parseStmDefLocal(); - break; - case StmType::Return: - out = parseStmReturn(); - break; - case StmType::Print: - out = parseStmPrint(); - break; - case StmType::If: - out = parseStmIf(); - break; - case StmType::While: - out = parseStmWhile(); - break; - case StmType::Copy: - out = parseStmCopy(); - break; - case StmType::Call: - out = parseStmCall(); - break; - case StmType::CLASS_DEF: - out = parseStmClassDef(); - break; - } - - if (out) { - break; - } - - tokSetCursor(crs); - if (mRes.err) { - errors.pushBack(mRes.err); - mRes.err = NULL; - } - } - - if (out) { - for (auto err : errors) { - delete err.data(); - } - return out; - } - - Error* error = NULL; - tp::alni max_advanced = 0; - for (auto err : errors) { - if (err.data()->mAdvanecedIdx && max_advanced < err.data()->mAdvanecedIdx) { - max_advanced = err.data()->mAdvanecedIdx; - error = err.data(); - } - } - - if (error) { - mRes.err = new Error(*error); - - for (auto err : errors) { - delete err.data(); - } - - return NULL; - } - - REQUIRE(0, "Exprected A Statement", {}); -} - -StatementScope* Parser::parseScope(bool aPushToScopeStack) { - CHECK(tokRead() == Token::SCOPE_IN, {}); - - auto out = new StatementScope({}, aPushToScopeStack); - List stms; - -READ_STM: - auto crs = tokGetCursor(); - auto tok = tokRead(); - - if (tok == Token::NO_TOKEN) { - delete out; - for (auto stm : stms) { - delete stm.data(); - } - REQUIRE(0, "Missing Scope Closing Bracket", {}); - } - - if (tok != Token::SCOPE_OUT) { - tokSetCursor(crs); - - auto stm = parseStm(); - CHECK_ERROR(stm, { - delete out; - for (auto stm : stms) { - delete stm.data(); - } - }); - - stms.pushBack(stm); - - goto READ_STM; - } - - out->mStatements.reserve(stms.length()); - - ualni idx = 0; - for (auto stm : stms) { - out->mStatements[idx] = stm.data(); - idx++; - } - - return out; -} - -Parser::Resault Parser::parse(const tp::String& oscript) { - mTok.bindSource(oscript.read()); - mTok.reset(); - - mRes.scope = new StatementScope({}, true); - - List stms; - do { - auto stm = parseStm(); - - if (mRes.err || !stm) { // catch - delete mRes.scope; - mRes.scope = NULL; - for (auto stm : stms) { - delete stm.data(); - } - - return mRes; - } - - stms.pushBack(stm); - - } while (tokInputLeft()); - - mRes.scope->mStatements.reserve(stms.length()); - - ualni idx = 0; - for (auto stm : stms) { - mRes.scope->mStatements[idx] = stm.data(); - idx++; - } - - return mRes; -} + +#include "List.hpp" +#include "Logging.hpp" + +#include "compiler/function.h" +#include "parser/parser.h" + +#include + +#define MAX_STREAM_LENGTH 1024 * 8 * 200 + +#define REQUIRE(expr, desc, on_catch) \ + DEBUG_BREAK(mRes.err); \ + if (!(expr)) { \ + mRes.err = new Error(desc, mTok.getCursorPrev().mAdvancedOffset); \ + on_catch; \ + return NULL; \ + } +#define CHECK(expr, on_catch) \ + if (!(expr)) { \ + on_catch; \ + return NULL; \ + } +#define CHECK_ERROR(value, on_catch) \ + if (mRes.err || !value) { \ + on_catch; \ + return NULL; \ + } + +using namespace tp; +using namespace obj; +using namespace BCgen; + +bool Parser::Token::isAriphm() { + switch (type) { + case Token::ADD: + case Token::SUB: + case Token::DIV: + case Token::MUL: return true; + default: return false; + } +} + +bool Parser::Token::isBoolean() { + switch (type) { + case Token::EQUAL: + case Token::NOT_EQUAL: + case Token::BOOL_AND: + case Token::BOOL_OR: + case Token::MORE: + case Token::LESS: + case Token::QE_OR_MORE: + case Token::QE_OR_LESS: return true; + default: return false; + } +} + +Parser::Parser() { + mTok.build({ + { "\n|\t| |\r", Token::SPACE }, + { "var", Token::VAR }, + { "class", Token::CLASS_DEF }, + { "self", Token::SELF }, + { "\\{", Token::SCOPE_IN }, + { "\\}", Token::SCOPE_OUT }, + { "=", Token::ASSIGN }, + { "def", Token::DEF_FUNC }, + { "<<", Token::PRINT }, + { "if", Token::IF }, + { "else", Token::ELSE }, + { "while", Token::WHILE }, + { "\\(", Token::BRACKET_IN }, + { "\\)", Token::BRACKET_OUT }, + { ",", Token::COMMA }, + { "new", Token::NEW }, + { "\\.", Token::CHILD }, + { "return", Token::RETURN }, + { "==", Token::EQUAL }, + { "!=", Token::NOT_EQUAL }, + { ">", Token::MORE }, + { "<", Token::LESS }, + { ">=", Token::QE_OR_MORE }, + { "<=", Token::QE_OR_LESS }, + { "!", Token::BOOL_NOT }, + { "&&", Token::BOOL_AND }, + { "\\|\\|", Token::BOOL_OR }, + { "\\+", Token::ADD }, + { "\\*", Token::MUL }, + { "\\-", Token::SUB }, + { "/", Token::DIV }, + { ";", Token::STM_END }, + { "true", Token::CONST_TRUE }, + { "false", Token::CONST_FALSE }, + { "((\\-)|(\\+))?[0-9]+i?", Token::CONST_INT }, + { R"(((\-)|(\+))?([0-9]+)(\.)([0-9]*)?f?)", Token::CONST_FLOAT }, + { R"((/\*){\*-\*}*(\*/))", Token::COMMENT_BLOCK }, + { R"("{"-"}*")", Token::CONST_STRING }, + + { "([a-z]|[A-Z]|_)+([a-z]|[A-Z]|[0-9]|_)*", Token::ID }, + }); +} + +tp::String to_string(const char* stream, tp::alni len) { + tp::String out; + out.resize(len); + tp::memCopy(out.write(), stream, len); + return out; +} + +Parser::Token Parser::tokRead() { + Token out; + + if (!tokInputLeft()) { + Token out; + out.type = Token::NO_TOKEN; + return out; + } + + auto crs_start = mTok.getCursor(); + out.type = mTok.readTok(); + out.token = to_string(crs_start.str(), mTok.lastTokLEn()); + + switch (out.type) { + case Token::CONST_FALSE: out.boolean = false; break; + case Token::CONST_TRUE: out.boolean = true; break; + case Token::CONST_INT: + { + char* p_end; + out.integer = std::strtol(out.token.read(), &p_end, 10); + DEBUG_ASSERT(out.token.read() != p_end); + break; + } + case Token::CONST_FLOAT: + { + char* p_end; + out.floating = std::strtod(out.token.read(), &p_end); + DEBUG_ASSERT(out.token.read() != p_end); + break; + } + case Token::CONST_STRING: + { + out.str = to_string(crs_start.str() + 1, mTok.lastTokLEn() - 2); + break; + } + } + + return out; +} + +Parser::Token Parser::tokLookup() { + auto crs = mTok.getCursor(); + auto out = tokRead(); + mTok.setCursor(crs); + return out; +} + +bool Parser::tokInputLeft() { + auto type = mTok.lookupTok(); + + while (mTok.isInputLeft() && type == Token::SPACE || (type >= Token::__END__ && type <= Token::__START__)) { + mTok.skipTok(); + type = mTok.lookupTok(); + } + + return type != Token::SOURCE_END_TOKEN; +} + +void Parser::tokSkip() { + if (!tokInputLeft()) { + return; + } + mTok.skipTok(); +} + +Parser::Tokenizer::Cursor Parser::tokGetCursor() { return mTok.getCursor(); } +void Parser::tokSetCursor(Tokenizer::Cursor crs) { mTok.setCursor(crs); } + +Expression* Parser::parseExprCompound() { + CHECK(tokRead() == Token::BRACKET_IN, {}); + auto ret = parseExpr(); + CHECK_ERROR(ret, {}); + REQUIRE(tokRead() == Token::BRACKET_OUT, "Expected Closing Bracket", {}); + return ret; +} + +Expression* Parser::parseExprNEW() { + CHECK(tokRead() == Token::NEW, {}); + auto name = tokRead(); + REQUIRE(name == Token::ID, "Expected Identifier", {}); + + REQUIRE(tokRead() == Token::BRACKET_IN, "Expected opening brackets", {}); + REQUIRE(tokRead() == Token::BRACKET_OUT, "Expected closing brackets", {}); + + return ExprNew(name.token); +} + +Expression* Parser::parseExprLOCAL() { + auto local_id_tok = tokRead(); + if (local_id_tok == Token::ID) { + return ExprLocal(local_id_tok.token); + } else if (local_id_tok == Token::SELF) { + return ExprSelf(); + } + return NULL; +} + +Expression* Parser::parseExprCONST() { + auto tok = tokRead(); + switch (tok) { + case Token::CONST_FALSE: return ExprConst(false); + case Token::CONST_TRUE: return ExprConst(true); + case Token::CONST_INT: return ExprConst(tok.integer); + case Token::CONST_FLOAT: return ExprConst(tok.floating); + case Token::CONST_STRING: return ExprConst(tok.str); + default: REQUIRE(0, "not a const Expr", {}); + } +} + +Expression* Parser::parseExprCHILD(Expression* prnt) { + CHECK(tokRead() == Token::CHILD, {}); + auto id = tokRead(); + REQUIRE(id == Token::ID, "Exprected Identifier", {}); + return prnt->ExprChild(id.str); +} + +Expression* Parser::parseExprCALL(Expression* prnt) { + CHECK(tokRead() == Token::BRACKET_IN, {}); + + List args; + +READ_ARG: + Expression* expr = NULL; + auto tok = tokLookup(); + REQUIRE(tok != Token::NO_TOKEN, "Missing Closing Bracket", {}); + + if (tok != Token::BRACKET_OUT) { + + expr = parseExpr(); + CHECK_ERROR(expr, { + for (auto arg : args) { + delete arg.data(); + } + }); + + args.pushBack(expr); + + tok = tokLookup(); + if (tok == Token::COMMA) { + tokSkip(); + goto READ_ARG; + } else if (tok != Token::BRACKET_OUT) { + for (auto arg : args) { + delete arg.data(); + } + REQUIRE(0, "Expected A Closing Bracket", {}); + } + } + tokSkip(); + + auto out = prnt->ExprCall({}); + out->mArgs.reserve(args.length()); + + ualni idx = 0; + for (auto arg : args) { + out->mArgs[idx] = arg.data(); + idx++; + } + + return out; +} + +Expression* Parser::parseExprAriphm() { + + tp::InitialierList expessions = { + ExprType::Compound, + ExprType::NEW, + ExprType::LOCAL, + ExprType::CONST, + }; + + Expression* left = parseExpr(expessions); + CHECK_ERROR(left, {}); + + Expression* ret = NULL; + +PARSE: + + Expression* right = NULL; + + auto tok = tokLookup(); + if (tok.isAriphm()) { + tokSkip(); + + right = parseExpr(expessions); + + if (mRes.err) { + if (ret) { + goto PRECEDENCE; + } + + delete left; + return NULL; + } + + } else { + CHECK(ret, { delete left; }); + goto PRECEDENCE; + } + + switch (tok) { + case Token::ADD: ret = ExprAriphm(left, right, OpCode::OBJ_ADD); break; + case Token::SUB: ret = ExprAriphm(left, right, OpCode::OBJ_SUB); break; + case Token::DIV: ret = ExprAriphm(left, right, OpCode::OBJ_DIV); break; + case Token::MUL: ret = ExprAriphm(left, right, OpCode::OBJ_MUL); + } + + left = ret; + goto PARSE; + +PRECEDENCE: + // FIXME: Not Implemented + + return ret; +} + +Expression* Parser::parseExprBOOLEAN() { + + tp::InitialierList expessions = { + ExprType::Compound, ExprType::NEW, ExprType::LOCAL, ExprType::CONST, ExprType::BOOLEAN_NOT, + }; + + Expression* left = parseExpr(expessions); + CHECK_ERROR(left, {}); + + Expression* ret = NULL; + +PARSE: + + Expression* right = NULL; + + auto tok = tokLookup(); + if (tok.isBoolean()) { + tokSkip(); + + right = parseExpr(expessions); + + if (mRes.err) { + if (ret) { + goto PRECEDENCE; + } + + delete left; + return NULL; + } + + } else { + CHECK(ret, { delete left; }); + goto PRECEDENCE; + } + + switch (tok) { + case Token::EQUAL: ret = ExprBool(left, right, OpCode::EQUAL); break; + case Token::NOT_EQUAL: ret = ExprBool(left, right, OpCode::NOT_EQUAL); break; + case Token::BOOL_AND: ret = ExprBool(left, right, OpCode::AND); break; + case Token::BOOL_OR: ret = ExprBool(left, right, OpCode::OR); break; + case Token::MORE: ret = ExprBool(left, right, OpCode::MORE); break; + case Token::LESS: ret = ExprBool(left, right, OpCode::LESS); break; + case Token::QE_OR_MORE: ret = ExprBool(left, right, OpCode::EQUAL_OR_MORE); break; + case Token::QE_OR_LESS: ret = ExprBool(left, right, OpCode::EQUAL_OR_LESS); + } + + left = ret; + goto PARSE; + +PRECEDENCE: + // FIXME: Not Implemented + + return ret; +} + +Expression* Parser::parseExprBOOLEAN_NOT() { + CHECK(tokRead() == Token::BOOL_NOT, {}); + + tp::InitialierList exprs = { + ExprType::Compound, ExprType::BOOLEAN, ExprType::Ariphm, ExprType::NEW, ExprType::LOCAL, ExprType::CONST, + }; + + auto out = parseExpr(exprs); + CHECK_ERROR(out, {}); + + return ExprBoolNot(out); +} + +Expression* Parser::parseExprFUNC() { + auto op_tok = tokRead(); + CHECK(op_tok == Token::ID, {}); + return ExprFunc(op_tok.token); +} + +// passed prnt isno longer responsability of callee +// suc : returns top level parent +// err : returns NULL +Expression* Parser::parseExprChain(Expression* prnt) { + +PARSE_CHAIN: + auto tok = tokLookup(); + + switch (tok) { + case Token::CHILD: + { + tokRead(); + + auto child_id = tokRead(); + REQUIRE(child_id == Token::ID, "expected an id", { delete prnt; }); + + prnt = prnt->ExprChild(child_id.token); + goto PARSE_CHAIN; + } + + case Token::BRACKET_IN: + { + + auto new_prnt = parseExprCALL(prnt); + CHECK_ERROR(new_prnt, { delete prnt; }); + + if (prnt->mType == Expression::Type::CHILD) { + ((ExpressionChild*) prnt)->mMethod = true; + } + + prnt = new_prnt; + goto PARSE_CHAIN; + } + } + + return prnt; +} + +Expression* Parser::parseExpr(tp::InitialierList expressions) { + + Expression* out = NULL; + + List errors; + + for (auto expr_type : expressions) { + auto crs = tokGetCursor(); + switch (expr_type) { + case Parser::ExprType::BOOLEAN_NOT: out = parseExprBOOLEAN_NOT(); break; + case Parser::ExprType::BOOLEAN: out = parseExprBOOLEAN(); break; + case Parser::ExprType::Ariphm: out = parseExprAriphm(); break; + case Parser::ExprType::NEW: out = parseExprNEW(); break; + case Parser::ExprType::LOCAL: out = parseExprLOCAL(); break; + case Parser::ExprType::CONST: out = parseExprCONST(); break; + case Parser::ExprType::Compound: out = parseExprCompound(); break; + } + + if (out) { + break; + } + + tokSetCursor(crs); + if (mRes.err) { + errors.pushBack(mRes.err); + mRes.err = NULL; + } + } + + if (out) { + // check for child expression and calls + out = parseExprChain(out); + + // check errors + if (mRes.err) { + errors.pushBack(mRes.err); + mRes.err = NULL; + goto ERRORS; + } + + for (auto err : errors) { + delete err.data(); + } + + return out; + } + +ERRORS: + Error* error = NULL; + tp::alni max_advanced = 0; + for (auto err : errors) { + if (err.data()->mAdvanecedIdx && err.data()->mAdvanecedIdx > max_advanced) { + max_advanced = err.data()->mAdvanecedIdx; + error = err.data(); + } + } + + if (error) { + mRes.err = new Error(*error); + + for (auto err : errors) { + delete err.data(); + } + + return NULL; + } + REQUIRE(0, "Expected and expression", {}); +} + +Statement* Parser::parseStmCall() { + + Expression* expr = parseExpr(); + CHECK_ERROR(expr, {}); + + REQUIRE(expr->mType == Expression::Type::CALL, "expression statement can only be function call", { delete expr; }); + + if (tokRead() != Token::STM_END) { + delete expr; + REQUIRE(0, "Expected End Of Statement", {}); + } + + return StmIgnore(expr); +} + +Statement* Parser::parseStmDefFunc() { + CHECK(tokRead() == Token::DEF_FUNC, {}); + List args; + auto name = tokRead(); + REQUIRE(name == Token::ID, "Expected an Identifier", {}); + + REQUIRE(tokRead() == Token::BRACKET_IN, "Expected Opening Bracket", {}); + +READ_ARG: + auto tok = tokLookup(); + + REQUIRE(tok != Token::NO_TOKEN, "Missing Closing Bracket", {}); + + if (tok == Token::ID) { + args.pushBack(tok.token); + tokSkip(); + tok = tokLookup(); + } + + if (tok == Token::COMMA) { + tokSkip(); + goto READ_ARG; + } + + REQUIRE(tok == Token::BRACKET_OUT, "Expected Closing Bracket", {}); + tokSkip(); + + auto func_def = StmDefFunc(name.token, {}, {}); + + func_def->mArgs.reserve(args.length()); + + ualni idx = 0; + for (auto iter : args) { + func_def->mArgs[idx] = iter.data(); + idx++; + } + + StatementScope* scope = parseScope(true); + CHECK_ERROR(scope, { delete func_def; }); + + func_def->mStatements.reserve(scope->mStatements.size()); + + idx = 0; + for (auto stm : scope->mStatements) { + func_def->mStatements[idx] = stm.data(); + idx++; + } + + delete scope; + return func_def; +} + +Statement* Parser::parseStmDefLocal() { + CHECK(tokRead() == Token::VAR, {}); + + auto tok = tokRead(); + REQUIRE(tok == Token::ID, "Expected an Identifier", {}); + REQUIRE(tokRead() == Token::ASSIGN, "Expected an assigment", {}); + + auto expr = parseExpr(); + CHECK_ERROR(expr, {}); + + if (tokRead() != Token::STM_END) { + delete expr; + REQUIRE(0, "Expected End Of Statement", {}); + } + + return StmDefLocal(tok.token, expr); +} + +Statement* Parser::parseStmReturn() { + CHECK(tokRead() == Token::RETURN, {}); + auto crs = tokGetCursor(); + + auto expr = parseExpr(); + if (mRes.err) { + tokSetCursor(crs); + delete mRes.err; + mRes.err = NULL; + } + + if (tokRead() != Token::STM_END) { + if (expr) delete expr; + REQUIRE(0, "Expected End Of Statement", {}); + } + + return expr ? StmReturn(expr) : StmReturn(); +} + +Statement* Parser::parseStmPrint() { + CHECK(tokRead() == Token::PRINT, {}); + auto expr = parseExpr(); + CHECK_ERROR(expr, {}); + + if (tokRead() != Token::STM_END) { + delete expr; + REQUIRE(0, "Expected End Of Statement", {}); + } + return StmPrint(expr); +} + +Statement* Parser::parseStmIf() { + CHECK(tokRead() == Token::IF, {}); + + // single if + REQUIRE(tokRead() == Token::BRACKET_IN, "Expected Opening Bracket", {}); + auto expr = parseExpr(); + CHECK_ERROR(expr, {}); + + if (tokRead() != Token::BRACKET_OUT) { + delete expr; + REQUIRE(0, "Expected Closing Bracket", {}); + } + + auto ontrue = parseScope(false); + CHECK_ERROR(ontrue, {}); + + // if-else + auto crs = tokGetCursor(); + if (tokRead() == Token::ELSE) { + StatementScope* onfalse = parseScope(false); + CHECK_ERROR(onfalse, { + delete ontrue; + delete expr; + }); + + return StmIf(expr, ontrue, onfalse); + } + tokSetCursor(crs); + + return StmIf(expr, ontrue, NULL); +} + +Statement* Parser::parseStmWhile() { + CHECK(tokRead() == Token::WHILE, {}); + + REQUIRE(tokRead() == Token::BRACKET_IN, "Expected Opening Bracket", {}); + auto expr = parseExpr(); + CHECK_ERROR(expr, {}); + + if (tokRead() != Token::BRACKET_OUT) { + delete expr; + REQUIRE(0, "Expected Closing Bracket", {}); + } + + auto scope = parseScope(false); + CHECK_ERROR(scope, {}); + + return StmWhile(expr, scope); +} + +Statement* Parser::parseStmCopy() { + auto left = parseExpr(); + CHECK_ERROR(left, {}); + + CHECK(tokRead() == Token::ASSIGN, {}); + + auto right = parseExpr(); + CHECK_ERROR(right, { delete left; }); + + if (tokRead() != Token::STM_END) { + delete left; + delete right; + REQUIRE(0, "Expected End Of Statement", {}); + } + + return StmCopy(left, right); +} + +Statement* Parser::parseStmClassDef() { + CHECK(tokRead() == Token::CLASS_DEF, {}); + + auto id = tokRead(); + REQUIRE(id == Token::ID, "Expected an Identifier", {}); + + auto scope = parseScope(true); + CHECK_ERROR(scope, {}); + + return StmClassDef(id.token, scope); +} + +Statement* Parser::parseStm(tp::InitialierList stm_types) { + Statement* out = NULL; + + List errors; + + for (auto stm_type : stm_types) { + auto crs = tokGetCursor(); + switch (stm_type) { + case StmType::DefFunc: out = parseStmDefFunc(); break; + case StmType::DefLocal: out = parseStmDefLocal(); break; + case StmType::Return: out = parseStmReturn(); break; + case StmType::Print: out = parseStmPrint(); break; + case StmType::If: out = parseStmIf(); break; + case StmType::While: out = parseStmWhile(); break; + case StmType::Copy: out = parseStmCopy(); break; + case StmType::Call: out = parseStmCall(); break; + case StmType::CLASS_DEF: out = parseStmClassDef(); break; + } + + if (out) { + break; + } + + tokSetCursor(crs); + if (mRes.err) { + errors.pushBack(mRes.err); + mRes.err = NULL; + } + } + + if (out) { + for (auto err : errors) { + delete err.data(); + } + return out; + } + + Error* error = NULL; + tp::alni max_advanced = 0; + for (auto err : errors) { + if (err.data()->mAdvanecedIdx && max_advanced < err.data()->mAdvanecedIdx) { + max_advanced = err.data()->mAdvanecedIdx; + error = err.data(); + } + } + + if (error) { + mRes.err = new Error(*error); + + for (auto err : errors) { + delete err.data(); + } + + return NULL; + } + + REQUIRE(0, "Exprected A Statement", {}); +} + +StatementScope* Parser::parseScope(bool aPushToScopeStack) { + CHECK(tokRead() == Token::SCOPE_IN, {}); + + auto out = new StatementScope({}, aPushToScopeStack); + List stms; + +READ_STM: + auto crs = tokGetCursor(); + auto tok = tokRead(); + + if (tok == Token::NO_TOKEN) { + delete out; + for (auto stm : stms) { + delete stm.data(); + } + REQUIRE(0, "Missing Scope Closing Bracket", {}); + } + + if (tok != Token::SCOPE_OUT) { + tokSetCursor(crs); + + auto stm = parseStm(); + CHECK_ERROR(stm, { + delete out; + for (auto stm : stms) { + delete stm.data(); + } + }); + + stms.pushBack(stm); + + goto READ_STM; + } + + out->mStatements.reserve(stms.length()); + + ualni idx = 0; + for (auto stm : stms) { + out->mStatements[idx] = stm.data(); + idx++; + } + + return out; +} + +Parser::Resault Parser::parse(const tp::String& oscript) { + mTok.bindSource(oscript.read()); + mTok.reset(); + + mRes.scope = new StatementScope({}, true); + + List stms; + do { + auto stm = parseStm(); + + if (mRes.err || !stm) { // catch + delete mRes.scope; + mRes.scope = NULL; + for (auto stm : stms) { + delete stm.data(); + } + + return mRes; + } + + stms.pushBack(stm); + + } while (tokInputLeft()); + + mRes.scope->mStatements.reserve(stms.length()); + + ualni idx = 0; + for (auto stm : stms) { + mRes.scope->mStatements[idx] = stm.data(); + idx++; + } + + return mRes; +} diff --git a/Objects/private/primitives/boolobject.cpp b/Objects/private/primitives/boolobject.cpp index f63f16f..72c8380 100644 --- a/Objects/private/primitives/boolobject.cpp +++ b/Objects/private/primitives/boolobject.cpp @@ -1,78 +1,56 @@ - - -#include "NewPlacement.hpp" -#include "primitives/boolobject.h" - -using namespace obj; -using namespace tp; - -void BoolObject::constructor(BoolObject* self) { - self->val = false; -} - -void BoolObject::copy(BoolObject* self, const BoolObject* in) { - self->val = in->val; -} - -BoolObject* BoolObject::create(bool in) { - NDO_CASTV(BoolObject, NDO->create("bool"), out)->val = alni(in); - return out; -} - -void BoolObject::from_int(BoolObject* self, alni in) { - self->val = in; -} - -void BoolObject::from_float(BoolObject* self, alnf in) { - self->val = alni(bool(in)); -} - -void BoolObject::from_string(BoolObject* self, String in) { - self->val = alni(bool(in)); -} - -String BoolObject::to_string(BoolObject* self) { - return String(bool(self->val)); -} - -alni BoolObject::to_int(BoolObject* self) { - return self->val; -} - -alnf BoolObject::to_float(BoolObject* self) { - return alnf(bool(self->val)); -} - -static alni save_size(BoolObject* self) { - return sizeof(alni); -} - -static void save(BoolObject* self, ArchiverOut& file_self) { - file_self << self->val; -} - -static void load(ArchiverIn& file_self, BoolObject* self) { - file_self >> self->val; -} - -struct ObjectTypeConversions BoolObjectTypeConversions = { - .from_int = (object_from_int) BoolObject::from_int, - .from_float = (object_from_float) BoolObject::from_float, - .from_string = (object_from_string) BoolObject::from_string, - .to_string = (object_to_string) BoolObject::to_string, - .to_int = (object_to_int) BoolObject::to_int, - .to_float = (object_to_float) BoolObject::to_float, -}; - -struct obj::ObjectType obj::BoolObject::TypeData = { - .base = NULL, - .constructor = (object_constructor) BoolObject::constructor, - .destructor = NULL, - .copy = (object_copy) BoolObject::copy, - .size = sizeof(BoolObject), - .name = "bool", - .convesions = &BoolObjectTypeConversions, - .save_size = (object_save_size)save_size, - .save = (object_save)save, - .load = (object_load)load, + + +#include "primitives/boolobject.h" +#include "NewPlacement.hpp" + +using namespace obj; +using namespace tp; + +void BoolObject::constructor(BoolObject* self) { self->val = false; } + +void BoolObject::copy(BoolObject* self, const BoolObject* in) { self->val = in->val; } + +BoolObject* BoolObject::create(bool in) { + NDO_CASTV(BoolObject, NDO->create("bool"), out)->val = alni(in); + return out; +} + +void BoolObject::from_int(BoolObject* self, alni in) { self->val = in; } + +void BoolObject::from_float(BoolObject* self, alnf in) { self->val = alni(bool(in)); } + +void BoolObject::from_string(BoolObject* self, String in) { self->val = alni(bool(in)); } + +String BoolObject::to_string(BoolObject* self) { return String(bool(self->val)); } + +alni BoolObject::to_int(BoolObject* self) { return self->val; } + +alnf BoolObject::to_float(BoolObject* self) { return alnf(bool(self->val)); } + +static alni save_size(BoolObject* self) { return sizeof(alni); } + +static void save(BoolObject* self, ArchiverOut& file_self) { file_self << self->val; } + +static void load(ArchiverIn& file_self, BoolObject* self) { file_self >> self->val; } + +struct ObjectTypeConversions BoolObjectTypeConversions = { + .from_int = (object_from_int) BoolObject::from_int, + .from_float = (object_from_float) BoolObject::from_float, + .from_string = (object_from_string) BoolObject::from_string, + .to_string = (object_to_string) BoolObject::to_string, + .to_int = (object_to_int) BoolObject::to_int, + .to_float = (object_to_float) BoolObject::to_float, +}; + +struct obj::ObjectType obj::BoolObject::TypeData = { + .base = NULL, + .constructor = (object_constructor) BoolObject::constructor, + .destructor = NULL, + .copy = (object_copy) BoolObject::copy, + .size = sizeof(BoolObject), + .name = "bool", + .convesions = &BoolObjectTypeConversions, + .save_size = (object_save_size) save_size, + .save = (object_save) save, + .load = (object_load) load, }; \ No newline at end of file diff --git a/Objects/private/primitives/classobject.cpp b/Objects/private/primitives/classobject.cpp index 5131504..d755046 100644 --- a/Objects/private/primitives/classobject.cpp +++ b/Objects/private/primitives/classobject.cpp @@ -1,82 +1,72 @@ -#pragma once - -#include "NewPlacement.hpp" - -#include "primitives/classobject.h" -#include "primitives/dictobject.h" -#include "primitives/nullobject.h" - -using namespace obj; -using namespace tp; - -void ClassObject::constructor(ClassObject* self) { - self->members = NDO_CAST(DictObject, NDO->create("dict")); - - self->addMember(NDO_NULL, "__init__"); - self->addMember(NDO_NULL, "__del__"); -} - -void ClassObject::copy(ClassObject* self, const ClassObject* blueprint) { - NDO->copy(self->members, blueprint->members); -} - -void ClassObject::destructor(ClassObject* self) { - NDO->destroy(self->members); -} - -void ClassObject::addMember(Object* obj, tp::String id) { - members->put(id, obj); -} - -void ClassObject::createMember(tp::String type, tp::String id) { - auto newo = NDO->create(type); - members->put(id, newo); -} - -alni ClassObject::save_size(ClassObject* self) { - return sizeof(alni); // dict object adress -} - -void ClassObject::save(ClassObject* self, ArchiverOut& file_self) { - // save dictobject - alni ndo_object_adress = NDO->save(file_self, self->members); - file_self << ndo_object_adress; -} - -void ClassObject::load(ArchiverIn& file_self, ClassObject* self) { - alni ndo_object_adress; - file_self >> ndo_object_adress; - self->members = NDO_CAST(DictObject, NDO->load(file_self, ndo_object_adress)); - NDO->refinc(self->members); -} - -tp::Buffer childs_retrival(ClassObject* self) { - tp::Buffer out; - out.append(self->members); - return out; -} - -alni allocated_size(ClassObject* self) { - return sizeof(DictObject*); -} - -alni allocated_size_recursive(ClassObject* self) { - alni out = sizeof(DictObject*); - out += NDO->objsize_ram_recursive_util(self->members, self->members->type); - return out; -} - -struct ObjectType ClassObject::TypeData = { - .base = NULL, - .constructor = (object_constructor) ClassObject::constructor, - .destructor = (object_destructor) ClassObject::destructor, - .copy = (object_copy) ClassObject::copy, - .size = sizeof(ClassObject), - .name = "class", - .save_size = (object_save_size)save_size, - .save = (object_save)save, - .load = (object_load)load, - .childs_retrival = (object_debug_all_childs_retrival) childs_retrival, - .allocated_size = (object_allocated_size) allocated_size, - .allocated_size_recursive = (object_allocated_size_recursive) allocated_size_recursive -}; +#pragma once + +#include "NewPlacement.hpp" + +#include "primitives/classobject.h" +#include "primitives/dictobject.h" +#include "primitives/nullobject.h" + +using namespace obj; +using namespace tp; + +void ClassObject::constructor(ClassObject* self) { + self->members = NDO_CAST(DictObject, NDO->create("dict")); + + self->addMember(NDO_NULL, "__init__"); + self->addMember(NDO_NULL, "__del__"); +} + +void ClassObject::copy(ClassObject* self, const ClassObject* blueprint) { NDO->copy(self->members, blueprint->members); } + +void ClassObject::destructor(ClassObject* self) { NDO->destroy(self->members); } + +void ClassObject::addMember(Object* obj, tp::String id) { members->put(id, obj); } + +void ClassObject::createMember(tp::String type, tp::String id) { + auto newo = NDO->create(type); + members->put(id, newo); +} + +alni ClassObject::save_size(ClassObject* self) { + return sizeof(alni); // dict object adress +} + +void ClassObject::save(ClassObject* self, ArchiverOut& file_self) { + // save dictobject + alni ndo_object_adress = NDO->save(file_self, self->members); + file_self << ndo_object_adress; +} + +void ClassObject::load(ArchiverIn& file_self, ClassObject* self) { + alni ndo_object_adress; + file_self >> ndo_object_adress; + self->members = NDO_CAST(DictObject, NDO->load(file_self, ndo_object_adress)); + NDO->refinc(self->members); +} + +tp::Buffer childs_retrival(ClassObject* self) { + tp::Buffer out; + out.append(self->members); + return out; +} + +alni allocated_size(ClassObject* self) { return sizeof(DictObject*); } + +alni allocated_size_recursive(ClassObject* self) { + alni out = sizeof(DictObject*); + out += NDO->objsize_ram_recursive_util(self->members, self->members->type); + return out; +} + +struct ObjectType ClassObject::TypeData = { .base = NULL, + .constructor = (object_constructor) ClassObject::constructor, + .destructor = (object_destructor) ClassObject::destructor, + .copy = (object_copy) ClassObject::copy, + .size = sizeof(ClassObject), + .name = "class", + .save_size = (object_save_size) save_size, + .save = (object_save) save, + .load = (object_load) load, + .childs_retrival = (object_debug_all_childs_retrival) childs_retrival, + .allocated_size = (object_allocated_size) allocated_size, + .allocated_size_recursive = (object_allocated_size_recursive) allocated_size_recursive }; diff --git a/Objects/private/primitives/colorobject.cpp b/Objects/private/primitives/colorobject.cpp index 6419878..e315542 100644 --- a/Objects/private/primitives/colorobject.cpp +++ b/Objects/private/primitives/colorobject.cpp @@ -1,84 +1,66 @@ - -#include "NewPlacement.hpp" -#include "primitives/colorobject.h" - -using namespace obj; -using namespace tp; - -void ColorObject::constructor(Object* self) { - NDO_CAST(ColorObject, self)->mCol = tp::RGBA(1.f); -} - -void ColorObject::copy(ColorObject* self, const ColorObject* in) { - self->mCol = in->mCol; -} - -ColorObject* ColorObject::create(tp::RGBA in) { - NDO_CASTV(ColorObject, NDO->create("RGBA"), out)->mCol = in; - return out; -} - -void ColorObject::from_int(ColorObject* self, alni in) { - self->mCol = tp::RGBA((tp::halnf)tp::clamp(in, (tp::alni) 0, (tp::alni) 1)); -} - -void ColorObject::from_float(ColorObject* self, alnf in) { - NDO_CAST(ColorObject, self)->mCol = tp::RGBA(tp::clamp((tp::halnf)in, 0.f, 1.f)); -} - -String ColorObject::to_string(ColorObject* self) { - // auto &col = NDO_CAST(ColorObject, self)->mCol; - // return tp::sfmt("%i:%i:%i:%i", (tp::alni) (col.r * 255), (tp::alni)(col.g * 255), (tp::alni)(col.b * 255), (tp::alni)(col.a * 255)); - // TODO : implement - return {}; -} - -static alni save_size(ColorObject* self) { - return sizeof(tp::RGBA); -} - -static void save(ColorObject* self, ArchiverOut& file_self) { - file_self << self->mCol; -} - -static void load(ArchiverIn& file_self, ColorObject* self) { - file_self >> self->mCol; -} - -struct ObjectTypeConversions ColorObjectTypeConversions = { - .from_int = (object_from_int) ColorObject::from_int, - .from_float = (object_from_float) ColorObject::from_float, - .from_string = NULL, - .to_string = (object_to_string) ColorObject::to_string, - .to_int = NULL, - .to_float = NULL, -}; - -void sub(ColorObject* self, ColorObject* in) { - self->mCol = in->mCol - self->mCol; -} - -void add(ColorObject* self, ColorObject* in) { - self->mCol = in->mCol + self->mCol; -} - -struct ObjectTypeAriphmetics ColorObject::TypeAriphm = { - .add = (object_add) add, - .sub = (object_sub) sub, - .mul = (object_mul) NULL, - .div = (object_div) NULL, -}; - -struct obj::ObjectType obj::ColorObject::TypeData = { - .base = NULL, - .constructor = ColorObject::constructor, - .destructor = NULL, - .copy = (object_copy) ColorObject::copy, - .size = sizeof(ColorObject), - .name = "RGBA", - .convesions = &ColorObjectTypeConversions, - .ariphmetics = &ColorObject::TypeAriphm, - .save_size = (object_save_size)save_size, - .save = (object_save)save, - .load = (object_load)load, + +#include "primitives/colorobject.h" +#include "NewPlacement.hpp" + +using namespace obj; +using namespace tp; + +void ColorObject::constructor(Object* self) { NDO_CAST(ColorObject, self)->mCol = tp::RGBA(1.f); } + +void ColorObject::copy(ColorObject* self, const ColorObject* in) { self->mCol = in->mCol; } + +ColorObject* ColorObject::create(tp::RGBA in) { + NDO_CASTV(ColorObject, NDO->create("RGBA"), out)->mCol = in; + return out; +} + +void ColorObject::from_int(ColorObject* self, alni in) { self->mCol = tp::RGBA((tp::halnf) tp::clamp(in, (tp::alni) 0, (tp::alni) 1)); } + +void ColorObject::from_float(ColorObject* self, alnf in) { NDO_CAST(ColorObject, self)->mCol = tp::RGBA(tp::clamp((tp::halnf) in, 0.f, 1.f)); } + +String ColorObject::to_string(ColorObject* self) { + // auto &col = NDO_CAST(ColorObject, self)->mCol; + // return tp::sfmt("%i:%i:%i:%i", (tp::alni) (col.r * 255), (tp::alni)(col.g * 255), (tp::alni)(col.b * 255), (tp::alni)(col.a * 255)); + // TODO : implement + return {}; +} + +static alni save_size(ColorObject* self) { return sizeof(tp::RGBA); } + +static void save(ColorObject* self, ArchiverOut& file_self) { file_self << self->mCol; } + +static void load(ArchiverIn& file_self, ColorObject* self) { file_self >> self->mCol; } + +struct ObjectTypeConversions ColorObjectTypeConversions = { + .from_int = (object_from_int) ColorObject::from_int, + .from_float = (object_from_float) ColorObject::from_float, + .from_string = NULL, + .to_string = (object_to_string) ColorObject::to_string, + .to_int = NULL, + .to_float = NULL, +}; + +void sub(ColorObject* self, ColorObject* in) { self->mCol = in->mCol - self->mCol; } + +void add(ColorObject* self, ColorObject* in) { self->mCol = in->mCol + self->mCol; } + +struct ObjectTypeAriphmetics ColorObject::TypeAriphm = { + .add = (object_add) add, + .sub = (object_sub) sub, + .mul = (object_mul) NULL, + .div = (object_div) NULL, +}; + +struct obj::ObjectType obj::ColorObject::TypeData = { + .base = NULL, + .constructor = ColorObject::constructor, + .destructor = NULL, + .copy = (object_copy) ColorObject::copy, + .size = sizeof(ColorObject), + .name = "RGBA", + .convesions = &ColorObjectTypeConversions, + .ariphmetics = &ColorObject::TypeAriphm, + .save_size = (object_save_size) save_size, + .save = (object_save) save, + .load = (object_load) load, }; \ No newline at end of file diff --git a/Objects/private/primitives/dictobject.cpp b/Objects/private/primitives/dictobject.cpp index db4f6dd..f91b012 100644 --- a/Objects/private/primitives/dictobject.cpp +++ b/Objects/private/primitives/dictobject.cpp @@ -1,234 +1,217 @@ -#pragma once - -#include "NewPlacement.hpp" - -#include "primitives/dictobject.h" -#include "primitives/stringobject.h" - -using namespace obj; -using namespace tp; - -void DictObject::constructor(Object* self) { - NDO_CASTV(DictObject, self, dict); - - new (&dict->items) Map(); -} - -void DictObject::copy(Object* in, const Object* target) { - NDO_CASTV(DictObject, in, self); - NDO_CASTV(DictObject, target, src); - - destructor(self); - constructor(self); - - for (auto item : src->items) { - auto instance = NDO->instatiate(item->val); - self->items.put(item->key, instance); - } -} - -void DictObject::destructor(Object* self) { - NDO_CASTV(DictObject, self, dict); - for (auto item : dict->items) { - NDO->destroy(item->val); - } - dict->items.~Map(); -} - -alni DictObject::save_size(DictObject* self) { - // calculate size needed - alni save_size = 0; - - // number on entries - save_size += sizeof(alni); - - for (auto item : self->items) { - // string length - save_size += tp::SaveSizeCounter::calc(item->key); - - // object file adress - save_size += sizeof(alni); - } - - return save_size; -} - -void DictObject::save(DictObject* self, ArchiverOut& file_self) { - - // write size - alni len = self->items.size(); - file_self << len; - - // save hashmap pairs - for (auto item : self->items) { - // item val - alni ndo_object_adress = NDO->save(file_self, item->val); - file_self << ndo_object_adress; - - // item key - file_self << item->key; - } -} - -void DictObject::load(ArchiverIn& file_self, DictObject* self) { - new (&self->items) tp::Map(); - - alni len; - file_self >> len; - - for (alni i = 0; i < len; i++) { - - // read val - alni ndo_object_adress; - file_self >> ndo_object_adress; - Object* val = NDO->load(file_self, ndo_object_adress); - - // read key value - String key; - file_self >> key; - - // add to dictinary - self->put(key, val); - } -} - -tp::Buffer DictObject::childs_retrival(DictObject* self) { - tp::Buffer out; - out.reserve(self->items.size()); - ualni i = 0; - for (auto item : self->items) { - out[i] = item->val; - i++; - } - return out; -} - -alni DictObject::allocated_size(DictObject* self) { - ASSERT(false) - // alni out = self->items.sizeAllocatedMem(); - for (auto item : self->items) { - // out += item->key.sizeAllocatedMem(); - } - // return out; - return 0; -} - -alni DictObject::allocated_size_recursive(DictObject* self) { - alni out = allocated_size(self); - for (auto item : self->items) { - out += NDO->objsize_ram_recursive_util(item->val, item->val->type); - } - return out; -} - -void DictObject::put(tp::String str, Object* obj) { - DEBUG_ASSERT(obj); - NDO->refinc(obj); - items.put(str, obj); -} - -void DictObject::remove(tp::String str) { - auto idx = items.presents(str); - if (idx) { - NDO->destroy(items.getSlotVal(idx)); - items.remove(str); - } -} - -Object* DictObject::get(tp::String str) { - return items.get(str); -} - -tp::Map::Idx DictObject::presents(tp::String str) { - return items.presents(str); -} - -Object* DictObject::getSlotVal(tp::Map::Idx idx) { - return items.getSlotVal(idx); -} - -const tp::Map& DictObject::getItems() const { - return items; -} - -static auto tm_get = TypeMethod{ - .nameid = "get", - .descr = "gets the object", - .args = { - { "str key", NULL } - }, - .exec = [](const TypeMethod* tm) { - auto const self = (DictObject*)tm->self; - auto str_key = tm->args[0].obj; - - NDO_CASTV(StringObject, str_key, key); - ASSERT(key); - - auto idx = self->presents(key->val); - if (idx) { - tm->ret.obj = self->getSlotVal(idx); - } - }, - .ret = { "object", NULL } -}; - -static auto tm_put = TypeMethod{ - .nameid = "put", - .descr = "puts the object into the dictinary", - .args = { - { "key", NULL }, - { "object", NULL } - }, - .exec = [](const TypeMethod* tm) { - auto const self = (DictObject*)tm->self; - - auto str_key = tm->args[0].obj; - auto obj = tm->args[1].obj; - - NDO_CASTV(StringObject, str_key, key); - ASSERT(key); - - self->put(key->val, obj); - }, -}; - -static auto tm_remove = TypeMethod{ - .nameid = "remove", - .descr = "remove the object from the dictinary", - .args = { - { "key", NULL }, - }, - .exec = [](const TypeMethod* tm) { - auto const self = (DictObject*)tm->self; - - auto str_key = tm->args[0].obj; - - NDO_CASTV(StringObject, str_key, key); - ASSERT(key); - - self->remove(key->val); - }, -}; - -struct obj::ObjectType DictObject::TypeData = { - .base = NULL, - .constructor = DictObject::constructor, - .destructor = DictObject::destructor, - .copy = DictObject::copy, - .size = sizeof(DictObject), - .name = "dict", - .save_size = (object_save_size)DictObject::save_size, - .save = (object_save)DictObject::save, - .load = (object_load)DictObject::load, - .childs_retrival = (object_debug_all_childs_retrival)DictObject::childs_retrival, - .allocated_size = (object_allocated_size)DictObject::allocated_size, - .allocated_size_recursive = (object_allocated_size_recursive)DictObject::allocated_size_recursive, - - .type_methods = { - .methods = { - &tm_put, - &tm_remove, - &tm_get, - } - } -}; +#pragma once + +#include "NewPlacement.hpp" + +#include "primitives/dictobject.h" +#include "primitives/stringobject.h" + +using namespace obj; +using namespace tp; + +void DictObject::constructor(Object* self) { + NDO_CASTV(DictObject, self, dict); + + new (&dict->items) Map(); +} + +void DictObject::copy(Object* in, const Object* target) { + NDO_CASTV(DictObject, in, self); + NDO_CASTV(DictObject, target, src); + + destructor(self); + constructor(self); + + for (auto item : src->items) { + auto instance = NDO->instatiate(item->val); + self->items.put(item->key, instance); + } +} + +void DictObject::destructor(Object* self) { + NDO_CASTV(DictObject, self, dict); + for (auto item : dict->items) { + NDO->destroy(item->val); + } + dict->items.~Map(); +} + +alni DictObject::save_size(DictObject* self) { + // calculate size needed + alni save_size = 0; + + // number on entries + save_size += sizeof(alni); + + for (auto item : self->items) { + // string length + save_size += tp::SaveSizeCounter::calc(item->key); + + // object file adress + save_size += sizeof(alni); + } + + return save_size; +} + +void DictObject::save(DictObject* self, ArchiverOut& file_self) { + + // write size + alni len = self->items.size(); + file_self << len; + + // save hashmap pairs + for (auto item : self->items) { + // item val + alni ndo_object_adress = NDO->save(file_self, item->val); + file_self << ndo_object_adress; + + // item key + file_self << item->key; + } +} + +void DictObject::load(ArchiverIn& file_self, DictObject* self) { + new (&self->items) tp::Map(); + + alni len; + file_self >> len; + + for (alni i = 0; i < len; i++) { + + // read val + alni ndo_object_adress; + file_self >> ndo_object_adress; + Object* val = NDO->load(file_self, ndo_object_adress); + + // read key value + String key; + file_self >> key; + + // add to dictinary + self->put(key, val); + } +} + +tp::Buffer DictObject::childs_retrival(DictObject* self) { + tp::Buffer out; + out.reserve(self->items.size()); + ualni i = 0; + for (auto item : self->items) { + out[i] = item->val; + i++; + } + return out; +} + +alni DictObject::allocated_size(DictObject* self) { + ASSERT(false) + // alni out = self->items.sizeAllocatedMem(); + for (auto item : self->items) { + // out += item->key.sizeAllocatedMem(); + } + // return out; + return 0; +} + +alni DictObject::allocated_size_recursive(DictObject* self) { + alni out = allocated_size(self); + for (auto item : self->items) { + out += NDO->objsize_ram_recursive_util(item->val, item->val->type); + } + return out; +} + +void DictObject::put(tp::String str, Object* obj) { + DEBUG_ASSERT(obj); + NDO->refinc(obj); + items.put(str, obj); +} + +void DictObject::remove(tp::String str) { + auto idx = items.presents(str); + if (idx) { + NDO->destroy(items.getSlotVal(idx)); + items.remove(str); + } +} + +Object* DictObject::get(tp::String str) { return items.get(str); } + +tp::Map::Idx DictObject::presents(tp::String str) { return items.presents(str); } + +Object* DictObject::getSlotVal(tp::Map::Idx idx) { return items.getSlotVal(idx); } + +const tp::Map& DictObject::getItems() const { return items; } + +static auto tm_get = TypeMethod{ .nameid = "get", + .descr = "gets the object", + .args = { { "str key", NULL } }, + .exec = + [](const TypeMethod* tm) { + auto const self = (DictObject*) tm->self; + auto str_key = tm->args[0].obj; + + NDO_CASTV(StringObject, str_key, key); + ASSERT(key); + + auto idx = self->presents(key->val); + if (idx) { + tm->ret.obj = self->getSlotVal(idx); + } + }, + .ret = { "object", NULL } }; + +static auto tm_put = TypeMethod{ + .nameid = "put", + .descr = "puts the object into the dictinary", + .args = { { "key", NULL }, { "object", NULL } }, + .exec = + [](const TypeMethod* tm) { + auto const self = (DictObject*) tm->self; + + auto str_key = tm->args[0].obj; + auto obj = tm->args[1].obj; + + NDO_CASTV(StringObject, str_key, key); + ASSERT(key); + + self->put(key->val, obj); + }, +}; + +static auto tm_remove = TypeMethod{ + .nameid = "remove", + .descr = "remove the object from the dictinary", + .args = { + { "key", NULL }, + }, + .exec = [](const TypeMethod* tm) { + auto const self = (DictObject*)tm->self; + + auto str_key = tm->args[0].obj; + + NDO_CASTV(StringObject, str_key, key); + ASSERT(key); + + self->remove(key->val); + }, +}; + +struct obj::ObjectType DictObject::TypeData = { .base = NULL, + .constructor = DictObject::constructor, + .destructor = DictObject::destructor, + .copy = DictObject::copy, + .size = sizeof(DictObject), + .name = "dict", + .save_size = (object_save_size) DictObject::save_size, + .save = (object_save) DictObject::save, + .load = (object_load) DictObject::load, + .childs_retrival = (object_debug_all_childs_retrival) DictObject::childs_retrival, + .allocated_size = (object_allocated_size) DictObject::allocated_size, + .allocated_size_recursive = (object_allocated_size_recursive) DictObject::allocated_size_recursive, + + .type_methods = { .methods = { + &tm_put, + &tm_remove, + &tm_get, + } } }; diff --git a/Objects/private/primitives/enumobject.cpp b/Objects/private/primitives/enumobject.cpp index 67eacb3..cc22388 100644 --- a/Objects/private/primitives/enumobject.cpp +++ b/Objects/private/primitives/enumobject.cpp @@ -1,182 +1,177 @@ - -#pragma once - -#include "NewPlacement.hpp" -#include "primitives/enumobject.h" - -#include - -using namespace obj; -using namespace tp; - -void EnumObject::constructor(EnumObject* self) { - self->active = 0; - self->nentries = 0; - self->entries = NULL; -} - -void obj::EnumObject::destructor(EnumObject* self) { - if (self->entries) free(self->entries); -} - -void EnumObject::copy(EnumObject* self, const EnumObject* in) { - if (self->entries) free(self->entries); - self->active = in->active; - self->nentries = in->nentries; - - self->entries = (alni*)malloc(self->nentries * ENV_ALNI_SIZE_B); - tp::memCopy(self->entries, in->entries, self->nentries * ENV_ALNI_SIZE_B); -} - -void obj::EnumObject::init(tp::InitialierList list) { - - if (entries) free(entries); - - active = 0; - nentries = (uhalni) list.size(); - entries = (alni*) malloc(nentries * ENV_ALNI_SIZE_B); - tp::memSetVal(entries, nentries * ENV_ALNI_SIZE_B, 0); - - alni* entry = entries; - for (auto elem : list) { - - alni len = tp::String::Logic::calcLength(elem); - if (len > ENV_ALNI_SIZE_B - 1) len = ENV_ALNI_SIZE_B - 1; - - tp::memCopy(entry, elem, len); - - for (alni* chech_entry = entries; chech_entry != entry; chech_entry++) { - DEBUG_ASSERT(tp::memCompare(chech_entry, entry, ENV_ALNI_SIZE_B) != 0); - } - - entry++; - } -} - -const char* obj::EnumObject::getActiveName() { - return getItemName(active); -} - -const char* obj::EnumObject::getItemName(tp::uhalni idx) { - DEBUG_ASSERT(entries && idx >= 0 && idx < nentries); - return (const char*) (entries + idx); -} - - -void EnumObject::from_int(EnumObject* self, alni in) { - if (self->entries && in >= 0 && in < self->nentries) { - self->active = uhalni(in); - } -} - -void EnumObject::from_float(EnumObject* self, alnf in) { - if (self->entries && in >= 0 && in < self->nentries) { - self->active = uhalni(in); - } -} - -void EnumObject::from_string(EnumObject* self, String in) { - if (self->entries) { - alni* entry = self->entries; - for (uhalni i = 0; i < self->nentries; i++) { - if (tp::String::Logic::isEqualLogic((const char*)entry, in.read())) { - self->active = i; - } - entry += 1; - } - } -} - -String EnumObject::to_string(EnumObject* self) { - if (!self->entries) { - return tp::String(); - } - auto val = (const char*)(&self->entries[self->active]); - return String(val); -} - -alni EnumObject::to_int(EnumObject* self) { - if (!self->entries) { - return -1; - } - return alni(self->active); -} - -alnf EnumObject::to_float(EnumObject* self) { - if (!self->entries) { - return -1; - } - return alnf(self->active); -} - -static alni save_size(EnumObject* self) { - if (!self->entries) { - return sizeof(uhalni); - } - return sizeof(uhalni) + sizeof(uhalni) + sizeof(alni) * self->nentries; -} - -static void save(EnumObject* self, ArchiverOut& file_self) { - if (!self->entries) { - uhalni empty_code = -1; - file_self << empty_code; - return; - } - file_self << self->active; - file_self << self->nentries; - file_self.writeBytes((tp::int1*) self->entries, self->nentries * ENV_ALNI_SIZE_B); -} - -static void load(ArchiverIn& file_self, EnumObject* self) { - file_self >> self->active; - if (self->active == -1) { - self->nentries = 0; - self->entries = NULL; - return; - } - file_self >> self->nentries; - self->entries = (alni*) malloc(self->nentries * ENV_ALNI_SIZE_B); - file_self.readBytes((tp::int1*) self->entries, self->nentries * ENV_ALNI_SIZE_B); -} - -bool obj::EnumObject::compare(EnumObject* first, EnumObject* second) { - return first->entries != NULL && second->entries != NULL && first->active == second->active; -} - -EnumObject* obj::EnumObject::create(tp::InitialierList list) { - auto enum_object = (EnumObject*)obj::NDO->create("enum"); - enum_object->init(list); - return enum_object; -} - -alni allocated_size(EnumObject* self) { - alni out = sizeof(uhalni) * 2 + sizeof(tp::alni*); - if (self->entries) { - out += self->nentries * sizeof(alni) * 2; - } - return out; -} - -struct ObjectTypeConversions EnumObjectTypeConversions = { - .from_int = (object_from_int) EnumObject::from_int, - .from_float = (object_from_float) EnumObject::from_float, - .from_string = (object_from_string) EnumObject::from_string, - .to_string = (object_to_string) EnumObject::to_string, - .to_int = (object_to_int) EnumObject::to_int, - .to_float = (object_to_float) EnumObject::to_float, -}; - -struct obj::ObjectType obj::EnumObject::TypeData = { - .base = NULL, - .constructor = (object_constructor) EnumObject::constructor, - .destructor = (object_destructor) EnumObject::destructor, - .copy = (object_copy) EnumObject::copy, - .size = sizeof(EnumObject), - .name = "enum", - .convesions = &EnumObjectTypeConversions, - .save_size = (object_save_size)save_size, - .save = (object_save)save, - .load = (object_load)load, - .comparison = (object_compare) EnumObject::compare, - .allocated_size = (object_allocated_size) allocated_size, + +#pragma once + +#include "primitives/enumobject.h" +#include "NewPlacement.hpp" + +#include + +using namespace obj; +using namespace tp; + +void EnumObject::constructor(EnumObject* self) { + self->active = 0; + self->nentries = 0; + self->entries = NULL; +} + +void obj::EnumObject::destructor(EnumObject* self) { + if (self->entries) free(self->entries); +} + +void EnumObject::copy(EnumObject* self, const EnumObject* in) { + if (self->entries) free(self->entries); + self->active = in->active; + self->nentries = in->nentries; + + self->entries = (alni*) malloc(self->nentries * ENV_ALNI_SIZE_B); + tp::memCopy(self->entries, in->entries, self->nentries * ENV_ALNI_SIZE_B); +} + +void obj::EnumObject::init(tp::InitialierList list) { + + if (entries) free(entries); + + active = 0; + nentries = (uhalni) list.size(); + entries = (alni*) malloc(nentries * ENV_ALNI_SIZE_B); + tp::memSetVal(entries, nentries * ENV_ALNI_SIZE_B, 0); + + alni* entry = entries; + for (auto elem : list) { + + alni len = tp::String::Logic::calcLength(elem); + if (len > ENV_ALNI_SIZE_B - 1) len = ENV_ALNI_SIZE_B - 1; + + tp::memCopy(entry, elem, len); + + for (alni* chech_entry = entries; chech_entry != entry; chech_entry++) { + DEBUG_ASSERT(tp::memCompare(chech_entry, entry, ENV_ALNI_SIZE_B) != 0); + } + + entry++; + } +} + +const char* obj::EnumObject::getActiveName() { return getItemName(active); } + +const char* obj::EnumObject::getItemName(tp::uhalni idx) { + DEBUG_ASSERT(entries && idx >= 0 && idx < nentries); + return (const char*) (entries + idx); +} + +void EnumObject::from_int(EnumObject* self, alni in) { + if (self->entries && in >= 0 && in < self->nentries) { + self->active = uhalni(in); + } +} + +void EnumObject::from_float(EnumObject* self, alnf in) { + if (self->entries && in >= 0 && in < self->nentries) { + self->active = uhalni(in); + } +} + +void EnumObject::from_string(EnumObject* self, String in) { + if (self->entries) { + alni* entry = self->entries; + for (uhalni i = 0; i < self->nentries; i++) { + if (tp::String::Logic::isEqualLogic((const char*) entry, in.read())) { + self->active = i; + } + entry += 1; + } + } +} + +String EnumObject::to_string(EnumObject* self) { + if (!self->entries) { + return tp::String(); + } + auto val = (const char*) (&self->entries[self->active]); + return String(val); +} + +alni EnumObject::to_int(EnumObject* self) { + if (!self->entries) { + return -1; + } + return alni(self->active); +} + +alnf EnumObject::to_float(EnumObject* self) { + if (!self->entries) { + return -1; + } + return alnf(self->active); +} + +static alni save_size(EnumObject* self) { + if (!self->entries) { + return sizeof(uhalni); + } + return sizeof(uhalni) + sizeof(uhalni) + sizeof(alni) * self->nentries; +} + +static void save(EnumObject* self, ArchiverOut& file_self) { + if (!self->entries) { + uhalni empty_code = -1; + file_self << empty_code; + return; + } + file_self << self->active; + file_self << self->nentries; + file_self.writeBytes((tp::int1*) self->entries, self->nentries * ENV_ALNI_SIZE_B); +} + +static void load(ArchiverIn& file_self, EnumObject* self) { + file_self >> self->active; + if (self->active == -1) { + self->nentries = 0; + self->entries = NULL; + return; + } + file_self >> self->nentries; + self->entries = (alni*) malloc(self->nentries * ENV_ALNI_SIZE_B); + file_self.readBytes((tp::int1*) self->entries, self->nentries * ENV_ALNI_SIZE_B); +} + +bool obj::EnumObject::compare(EnumObject* first, EnumObject* second) { return first->entries != NULL && second->entries != NULL && first->active == second->active; } + +EnumObject* obj::EnumObject::create(tp::InitialierList list) { + auto enum_object = (EnumObject*) obj::NDO->create("enum"); + enum_object->init(list); + return enum_object; +} + +alni allocated_size(EnumObject* self) { + alni out = sizeof(uhalni) * 2 + sizeof(tp::alni*); + if (self->entries) { + out += self->nentries * sizeof(alni) * 2; + } + return out; +} + +struct ObjectTypeConversions EnumObjectTypeConversions = { + .from_int = (object_from_int) EnumObject::from_int, + .from_float = (object_from_float) EnumObject::from_float, + .from_string = (object_from_string) EnumObject::from_string, + .to_string = (object_to_string) EnumObject::to_string, + .to_int = (object_to_int) EnumObject::to_int, + .to_float = (object_to_float) EnumObject::to_float, +}; + +struct obj::ObjectType obj::EnumObject::TypeData = { + .base = NULL, + .constructor = (object_constructor) EnumObject::constructor, + .destructor = (object_destructor) EnumObject::destructor, + .copy = (object_copy) EnumObject::copy, + .size = sizeof(EnumObject), + .name = "enum", + .convesions = &EnumObjectTypeConversions, + .save_size = (object_save_size) save_size, + .save = (object_save) save, + .load = (object_load) load, + .comparison = (object_compare) EnumObject::compare, + .allocated_size = (object_allocated_size) allocated_size, }; \ No newline at end of file diff --git a/Objects/private/primitives/floatobject.cpp b/Objects/private/primitives/floatobject.cpp index 019fd66..8428ab4 100644 --- a/Objects/private/primitives/floatobject.cpp +++ b/Objects/private/primitives/floatobject.cpp @@ -1,102 +1,72 @@ -#pragma once - -#include "NewPlacement.hpp" -#include "primitives/floatobject.h" - -using namespace obj; -using namespace tp; - -void FloatObject::constructor(FloatObject* self) { - self->val = 0; -} - -void FloatObject::copy(FloatObject* self, const FloatObject* in) { - self->val = in->val; -} - -FloatObject* FloatObject::create(alnf in) { - NDO_CASTV(FloatObject, NDO->create("float"), out)->val = alnf(in); - return out; -} - -void FloatObject::from_int(FloatObject* self, alni in) { - self->val = alnf(in); -} - -void FloatObject::from_float(FloatObject* self, alnf in) { - self->val = in; -} - -void FloatObject::from_string(FloatObject* self, String in) { - self->val = alnf(in); -} - -String FloatObject::to_string(FloatObject* self) { - return String(self->val); -} - -alni FloatObject::to_int(FloatObject* self) { - return alni(self->val); -} - -alnf FloatObject::to_float(FloatObject* self) { - return self->val; -} - -static alni save_size(FloatObject* self) { - return sizeof(alnf); -} - -static void save(FloatObject* self, ArchiverOut& file_self) { - file_self << self->val; -} - -static void load(ArchiverIn& file_self, FloatObject* self) { - file_self >> self->val; -} - -struct ObjectTypeConversions FloatObjectTypeConversions = { - .from_int = (object_from_int) FloatObject::from_int, - .from_float = (object_from_float) FloatObject::from_float, - .from_string = (object_from_string) FloatObject::from_string, - .to_string = (object_to_string) FloatObject::to_string, - .to_int = (object_to_int) FloatObject::to_int, - .to_float = (object_to_float) FloatObject::to_float, -}; - -static void mul(FloatObject* self, FloatObject* in) { - self->val *= in->val; -} - -static void sub(FloatObject* self, FloatObject* in) { - self->val -= in->val; -} - -static void add(FloatObject* self, FloatObject* in) { - self->val += in->val; -} - -static void divide(FloatObject* self, FloatObject* in) { - self->val /= in->val; -} - -struct ObjectTypeAriphmetics FloatObject::TypeAriphm = { - .add = (object_add)add, - .sub = (object_sub)sub, - .mul = (object_mul)mul, - .div = (object_div)divide, -}; - -struct obj::ObjectType obj::FloatObject::TypeData = { - .base = NULL, - .constructor = (object_constructor) FloatObject::constructor, - .destructor = NULL, - .copy = (object_copy) FloatObject::copy, - .size = sizeof(FloatObject), - .name = "float", - .convesions = &FloatObjectTypeConversions, - .ariphmetics = &FloatObject::TypeAriphm, - .save_size = (object_save_size) save_size, - .save = (object_save) save, - .load = (object_load) load, +#pragma once + +#include "primitives/floatobject.h" +#include "NewPlacement.hpp" + +using namespace obj; +using namespace tp; + +void FloatObject::constructor(FloatObject* self) { self->val = 0; } + +void FloatObject::copy(FloatObject* self, const FloatObject* in) { self->val = in->val; } + +FloatObject* FloatObject::create(alnf in) { + NDO_CASTV(FloatObject, NDO->create("float"), out)->val = alnf(in); + return out; +} + +void FloatObject::from_int(FloatObject* self, alni in) { self->val = alnf(in); } + +void FloatObject::from_float(FloatObject* self, alnf in) { self->val = in; } + +void FloatObject::from_string(FloatObject* self, String in) { self->val = alnf(in); } + +String FloatObject::to_string(FloatObject* self) { return String(self->val); } + +alni FloatObject::to_int(FloatObject* self) { return alni(self->val); } + +alnf FloatObject::to_float(FloatObject* self) { return self->val; } + +static alni save_size(FloatObject* self) { return sizeof(alnf); } + +static void save(FloatObject* self, ArchiverOut& file_self) { file_self << self->val; } + +static void load(ArchiverIn& file_self, FloatObject* self) { file_self >> self->val; } + +struct ObjectTypeConversions FloatObjectTypeConversions = { + .from_int = (object_from_int) FloatObject::from_int, + .from_float = (object_from_float) FloatObject::from_float, + .from_string = (object_from_string) FloatObject::from_string, + .to_string = (object_to_string) FloatObject::to_string, + .to_int = (object_to_int) FloatObject::to_int, + .to_float = (object_to_float) FloatObject::to_float, +}; + +static void mul(FloatObject* self, FloatObject* in) { self->val *= in->val; } + +static void sub(FloatObject* self, FloatObject* in) { self->val -= in->val; } + +static void add(FloatObject* self, FloatObject* in) { self->val += in->val; } + +static void divide(FloatObject* self, FloatObject* in) { self->val /= in->val; } + +struct ObjectTypeAriphmetics FloatObject::TypeAriphm = { + .add = (object_add) add, + .sub = (object_sub) sub, + .mul = (object_mul) mul, + .div = (object_div) divide, +}; + +struct obj::ObjectType obj::FloatObject::TypeData = { + .base = NULL, + .constructor = (object_constructor) FloatObject::constructor, + .destructor = NULL, + .copy = (object_copy) FloatObject::copy, + .size = sizeof(FloatObject), + .name = "float", + .convesions = &FloatObjectTypeConversions, + .ariphmetics = &FloatObject::TypeAriphm, + .save_size = (object_save_size) save_size, + .save = (object_save) save, + .load = (object_load) load, }; \ No newline at end of file diff --git a/Objects/private/primitives/interpreterobject.cpp b/Objects/private/primitives/interpreterobject.cpp index 55a15b9..4d2518b 100644 --- a/Objects/private/primitives/interpreterobject.cpp +++ b/Objects/private/primitives/interpreterobject.cpp @@ -1,82 +1,78 @@ - -#include "NewPlacement.hpp" - -#include "primitives/interpreterobject.h" -#include "primitives/linkobject.h" -#include "primitives/methodobject.h" - -using namespace obj; -using namespace tp; - -void InterpreterObject::constructor(InterpreterObject* self) { - new (&self->mInterpreter) Interpreter(); - - self->createMember("dict", "globals"); - self->createMember("link", "target method"); -} - -void InterpreterObject::destructor(InterpreterObject* self) { - self->mInterpreter.~Interpreter(); -} - -void InterpreterObject::load(ArchiverIn& file_self, InterpreterObject* self) { - new (&self->mInterpreter) Interpreter(); -} - -bool InterpreterObject::running() { return !mInterpreter.finished(); } - -void InterpreterObject::exec(obj::ClassObject* self, tp::InitialierList globals) { - - if (running()) { - return; - } - - auto link_target = getMember("target method"); - if (!link_target) { - return; - } - - auto target = link_target->getLink(); - if (!target) { - return; - } - - NDO_CASTV(obj::MethodObject, target, method); - if (!method || !method->mScript->mBytecode.mInstructions.size()) { - return; - } - - mInterpreter.execAll(method, self, getMember("globals"), globals); -} - -void InterpreterObject::debug() { - if (running()) { - return; - } - - auto link_target = getMember("target method"); - if (!link_target) { - return; - } - - auto target = link_target->getLink(); - if (!target) { - return; - } - - NDO_CASTV(obj::MethodObject, target, method); - if (!method || !method->mScript->mBytecode.mInstructions.size()) { - return; - } - - mInterpreter.exec(method, this, getMember("globals")); -} - -struct obj::ObjectType InterpreterObject::TypeData = { - .base = &ClassObject::TypeData, - .constructor = (object_constructor)InterpreterObject::constructor, - .destructor = (object_destructor)InterpreterObject::destructor, - .size = sizeof(InterpreterObject), - .name = "interpreter", - .load = (object_load)InterpreterObject::load, + +#include "NewPlacement.hpp" + +#include "primitives/interpreterobject.h" +#include "primitives/linkobject.h" +#include "primitives/methodobject.h" + +using namespace obj; +using namespace tp; + +void InterpreterObject::constructor(InterpreterObject* self) { + new (&self->mInterpreter) Interpreter(); + + self->createMember("dict", "globals"); + self->createMember("link", "target method"); +} + +void InterpreterObject::destructor(InterpreterObject* self) { self->mInterpreter.~Interpreter(); } + +void InterpreterObject::load(ArchiverIn& file_self, InterpreterObject* self) { new (&self->mInterpreter) Interpreter(); } + +bool InterpreterObject::running() { return !mInterpreter.finished(); } + +void InterpreterObject::exec(obj::ClassObject* self, tp::InitialierList globals) { + + if (running()) { + return; + } + + auto link_target = getMember("target method"); + if (!link_target) { + return; + } + + auto target = link_target->getLink(); + if (!target) { + return; + } + + NDO_CASTV(obj::MethodObject, target, method); + if (!method || !method->mScript->mBytecode.mInstructions.size()) { + return; + } + + mInterpreter.execAll(method, self, getMember("globals"), globals); +} + +void InterpreterObject::debug() { + if (running()) { + return; + } + + auto link_target = getMember("target method"); + if (!link_target) { + return; + } + + auto target = link_target->getLink(); + if (!target) { + return; + } + + NDO_CASTV(obj::MethodObject, target, method); + if (!method || !method->mScript->mBytecode.mInstructions.size()) { + return; + } + + mInterpreter.exec(method, this, getMember("globals")); +} + +struct obj::ObjectType InterpreterObject::TypeData = { + .base = &ClassObject::TypeData, + .constructor = (object_constructor) InterpreterObject::constructor, + .destructor = (object_destructor) InterpreterObject::destructor, + .size = sizeof(InterpreterObject), + .name = "interpreter", + .load = (object_load) InterpreterObject::load, }; \ No newline at end of file diff --git a/Objects/private/primitives/intobject.cpp b/Objects/private/primitives/intobject.cpp index 9aa004e..5956b2b 100644 --- a/Objects/private/primitives/intobject.cpp +++ b/Objects/private/primitives/intobject.cpp @@ -1,104 +1,74 @@ - -#pragma once - -#include "NewPlacement.hpp" - -#include "primitives/intobject.h" - -using namespace obj; -using namespace tp; - -void IntObject::constructor(Object* self) { - NDO_CAST(IntObject, self)->val = 0; -} - -void IntObject::copy(IntObject* self, const IntObject* in) { - self->val = in->val; -} - -IntObject* IntObject::create(alni in) { - NDO_CASTV(IntObject, NDO->create("int"), out)->val = in; - return out; -} - -void IntObject::from_int(Object* self, alni in) { - NDO_CAST(IntObject, self)->val = in; -} - -void IntObject::from_float(Object* self, alnf in) { - NDO_CAST(IntObject, self)->val = (alni)in; -} - -void IntObject::from_string(Object* self, String in) { - NDO_CAST(IntObject, self)->val = alni(in); -} - -String IntObject::to_string(Object* self) { - return String(NDO_CAST(IntObject, self)->val); -} - -alni IntObject::to_int(Object* self) { - return alni(NDO_CAST(IntObject, self)->val); -} - -alnf IntObject::to_float(Object* self) { - return alnf(NDO_CAST(IntObject, self)->val); -} - -static alni save_size(IntObject* self) { - return sizeof(alni); -} - -static void save(IntObject* self, ArchiverOut& file_self) { - file_self << self->val; -} - -static void load(ArchiverIn& file_self, IntObject* self) { - file_self >> self->val; -} - -struct ObjectTypeConversions IntObjectTypeConversions = { - .from_int = IntObject::from_int, - .from_float = IntObject::from_float, - .from_string = IntObject::from_string, - .to_string = IntObject::to_string, - .to_int = IntObject::to_int, - .to_float = IntObject::to_float, -}; - -void divide(IntObject* self, IntObject* in) { - self->val /= in->val; -} - -void mul(IntObject* self, IntObject* in) { - self->val *= in->val; -} - -void sub(IntObject* self, IntObject* in) { - self->val -= in->val; -} - -void add(IntObject* self, IntObject* in) { - self->val += in->val; -} - -struct ObjectTypeAriphmetics IntObject::TypeAriphm = { - .add = (object_add) add, - .sub = (object_sub) sub, - .mul = (object_mul) mul, - .div = (object_div) divide, -}; - -struct obj::ObjectType obj::IntObject::TypeData = { - .base = NULL, - .constructor = IntObject::constructor, - .destructor = NULL, - .copy = (object_copy) IntObject::copy, - .size = sizeof(IntObject), - .name = "int", - .convesions = &IntObjectTypeConversions, - .ariphmetics = &IntObject::TypeAriphm, - .save_size = (object_save_size)save_size, - .save = (object_save)save, - .load = (object_load)load, + +#pragma once + +#include "NewPlacement.hpp" + +#include "primitives/intobject.h" + +using namespace obj; +using namespace tp; + +void IntObject::constructor(Object* self) { NDO_CAST(IntObject, self)->val = 0; } + +void IntObject::copy(IntObject* self, const IntObject* in) { self->val = in->val; } + +IntObject* IntObject::create(alni in) { + NDO_CASTV(IntObject, NDO->create("int"), out)->val = in; + return out; +} + +void IntObject::from_int(Object* self, alni in) { NDO_CAST(IntObject, self)->val = in; } + +void IntObject::from_float(Object* self, alnf in) { NDO_CAST(IntObject, self)->val = (alni) in; } + +void IntObject::from_string(Object* self, String in) { NDO_CAST(IntObject, self)->val = alni(in); } + +String IntObject::to_string(Object* self) { return String(NDO_CAST(IntObject, self)->val); } + +alni IntObject::to_int(Object* self) { return alni(NDO_CAST(IntObject, self)->val); } + +alnf IntObject::to_float(Object* self) { return alnf(NDO_CAST(IntObject, self)->val); } + +static alni save_size(IntObject* self) { return sizeof(alni); } + +static void save(IntObject* self, ArchiverOut& file_self) { file_self << self->val; } + +static void load(ArchiverIn& file_self, IntObject* self) { file_self >> self->val; } + +struct ObjectTypeConversions IntObjectTypeConversions = { + .from_int = IntObject::from_int, + .from_float = IntObject::from_float, + .from_string = IntObject::from_string, + .to_string = IntObject::to_string, + .to_int = IntObject::to_int, + .to_float = IntObject::to_float, +}; + +void divide(IntObject* self, IntObject* in) { self->val /= in->val; } + +void mul(IntObject* self, IntObject* in) { self->val *= in->val; } + +void sub(IntObject* self, IntObject* in) { self->val -= in->val; } + +void add(IntObject* self, IntObject* in) { self->val += in->val; } + +struct ObjectTypeAriphmetics IntObject::TypeAriphm = { + .add = (object_add) add, + .sub = (object_sub) sub, + .mul = (object_mul) mul, + .div = (object_div) divide, +}; + +struct obj::ObjectType obj::IntObject::TypeData = { + .base = NULL, + .constructor = IntObject::constructor, + .destructor = NULL, + .copy = (object_copy) IntObject::copy, + .size = sizeof(IntObject), + .name = "int", + .convesions = &IntObjectTypeConversions, + .ariphmetics = &IntObject::TypeAriphm, + .save_size = (object_save_size) save_size, + .save = (object_save) save, + .load = (object_load) load, }; \ No newline at end of file diff --git a/Objects/private/primitives/linkobject.cpp b/Objects/private/primitives/linkobject.cpp index 610156e..7c51e11 100644 --- a/Objects/private/primitives/linkobject.cpp +++ b/Objects/private/primitives/linkobject.cpp @@ -1,133 +1,109 @@ - -#pragma once - -#include "NewPlacement.hpp" -#include "primitives/linkobject.h" - -using namespace obj; -using namespace tp; - -void LinkObject::constructor(Object* self) { - NDO_CAST(LinkObject, self)->link = 0; -} - -void LinkObject::destructor(LinkObject* self) { - if (self->link) NDO->destroy(self->link); -} - -void LinkObject::copy(Object* self, const Object* in) { - NDO_CAST(LinkObject, self)->setLink(NDO_CAST(LinkObject, in)->link); -} - -LinkObject* LinkObject::create(Object* in) { - NDO_CASTV(LinkObject, NDO->create("link"), out)->link = in; - return out; -} - -alni LinkObject::save_size(LinkObject* self) { - return sizeof(alni); -} - -void LinkObject::save(LinkObject* self, ArchiverOut& file_self) { - if (self->link != NULL) { - alni link_object_save_adress = NDO->save(file_self, self->link); - file_self << link_object_save_adress; - } - else { - alni null = -1; - file_self << null; - } -} - -void LinkObject::load(ArchiverIn& file_self, LinkObject* self) { - - alni saved_object_adress; - file_self >> saved_object_adress; - - if (saved_object_adress == -1) { - self->link = NULL; - } - else { - self->link = NDO->load(file_self, saved_object_adress); - NDO->refinc(self->link); - } -} - -tp::Buffer LinkObject::childs_retrival(LinkObject* self) { - tp::Buffer out; - if (self->link) out.append(self->link); - return out; -} - -alni LinkObject::allocated_size(LinkObject* self) { - return sizeof(Object*); -} - -alni LinkObject::allocated_size_recursive(LinkObject* self) { - alni out = sizeof(Object*); - if (self->link) { - out += NDO->objsize_ram_recursive_util(self->link, self->link->type); - } - return out; -} - -Object* LinkObject::getLink() { - return link; -} - -void LinkObject::setLink(Object* obj) { -#ifdef OBJECT_REF_COUNT - if (link) NDO->destroy(link); - if (obj) NDO->refinc(obj); -#endif // OBJECT_REF_COUNT - link = obj; -} - -static auto tm_set = TypeMethod{ - .nameid = "set", - .descr = "sets the link", - .args = { - { "target", NULL } - }, - .exec = [](const TypeMethod* tm) { - auto const self = (LinkObject*)tm->self; - auto const target = tm->args[0].obj; - self->setLink(target); - } -}; - -static auto tm_get = TypeMethod{ - .nameid = "get", - .descr = "gets the link", - .exec = [](const TypeMethod* tm) { - auto const self = (LinkObject*)tm->self; - auto link = self->getLink(); - if (link) { - tm->ret.obj = link; - } - }, - .ret = { "the link", NULL } -}; - -struct obj::ObjectType LinkObject::TypeData = { - .base = NULL, - .constructor = LinkObject::constructor, - .destructor = (object_destructor)LinkObject::destructor, - .copy = LinkObject::copy, - .size = sizeof(LinkObject), - .name = "link", - .convesions = NULL, - .save_size = (object_save_size)LinkObject::save_size, - .save = (object_save)LinkObject::save, - .load = (object_load)LinkObject::load, - .childs_retrival = (object_debug_all_childs_retrival)LinkObject::childs_retrival, - .allocated_size = (object_allocated_size)LinkObject::allocated_size, - .allocated_size_recursive = (object_allocated_size_recursive)LinkObject::allocated_size_recursive, - - .type_methods = { - .methods = { - &tm_set, - &tm_get, - } - } -}; \ No newline at end of file + +#pragma once + +#include "primitives/linkobject.h" +#include "NewPlacement.hpp" + +using namespace obj; +using namespace tp; + +void LinkObject::constructor(Object* self) { NDO_CAST(LinkObject, self)->link = 0; } + +void LinkObject::destructor(LinkObject* self) { + if (self->link) NDO->destroy(self->link); +} + +void LinkObject::copy(Object* self, const Object* in) { NDO_CAST(LinkObject, self)->setLink(NDO_CAST(LinkObject, in)->link); } + +LinkObject* LinkObject::create(Object* in) { + NDO_CASTV(LinkObject, NDO->create("link"), out)->link = in; + return out; +} + +alni LinkObject::save_size(LinkObject* self) { return sizeof(alni); } + +void LinkObject::save(LinkObject* self, ArchiverOut& file_self) { + if (self->link != NULL) { + alni link_object_save_adress = NDO->save(file_self, self->link); + file_self << link_object_save_adress; + } else { + alni null = -1; + file_self << null; + } +} + +void LinkObject::load(ArchiverIn& file_self, LinkObject* self) { + + alni saved_object_adress; + file_self >> saved_object_adress; + + if (saved_object_adress == -1) { + self->link = NULL; + } else { + self->link = NDO->load(file_self, saved_object_adress); + NDO->refinc(self->link); + } +} + +tp::Buffer LinkObject::childs_retrival(LinkObject* self) { + tp::Buffer out; + if (self->link) out.append(self->link); + return out; +} + +alni LinkObject::allocated_size(LinkObject* self) { return sizeof(Object*); } + +alni LinkObject::allocated_size_recursive(LinkObject* self) { + alni out = sizeof(Object*); + if (self->link) { + out += NDO->objsize_ram_recursive_util(self->link, self->link->type); + } + return out; +} + +Object* LinkObject::getLink() { return link; } + +void LinkObject::setLink(Object* obj) { +#ifdef OBJECT_REF_COUNT + if (link) NDO->destroy(link); + if (obj) NDO->refinc(obj); +#endif // OBJECT_REF_COUNT + link = obj; +} + +static auto tm_set = TypeMethod{ .nameid = "set", .descr = "sets the link", .args = { { "target", NULL } }, .exec = [](const TypeMethod* tm) { + auto const self = (LinkObject*) tm->self; + auto const target = tm->args[0].obj; + self->setLink(target); + } }; + +static auto tm_get = TypeMethod{ .nameid = "get", + .descr = "gets the link", + .exec = + [](const TypeMethod* tm) { + auto const self = (LinkObject*) tm->self; + auto link = self->getLink(); + if (link) { + tm->ret.obj = link; + } + }, + .ret = { "the link", NULL } }; + +struct obj::ObjectType LinkObject::TypeData = { .base = NULL, + .constructor = LinkObject::constructor, + .destructor = (object_destructor) LinkObject::destructor, + .copy = LinkObject::copy, + .size = sizeof(LinkObject), + .name = "link", + .convesions = NULL, + .save_size = (object_save_size) LinkObject::save_size, + .save = (object_save) LinkObject::save, + .load = (object_load) LinkObject::load, + .childs_retrival = (object_debug_all_childs_retrival) LinkObject::childs_retrival, + .allocated_size = (object_allocated_size) LinkObject::allocated_size, + .allocated_size_recursive = (object_allocated_size_recursive) LinkObject::allocated_size_recursive, + + .type_methods = { .methods = { + &tm_set, + &tm_get, + } } }; \ No newline at end of file diff --git a/Objects/private/primitives/listobject.cpp b/Objects/private/primitives/listobject.cpp index 7d4b1d8..8e5869c 100644 --- a/Objects/private/primitives/listobject.cpp +++ b/Objects/private/primitives/listobject.cpp @@ -1,137 +1,133 @@ - -#pragma once - -#include "NewPlacement.hpp" - -#include "primitives/listobject.h" -#include "primitives/intobject.h" - -using namespace obj; -using namespace tp; - -void ListObject::constructor(Object* in) { - NDO_CASTV(ListObject, in, self); - new (&self->items) List(); -} - -void ListObject::copy(Object* in, const Object* target) { - NDO_CASTV(ListObject, in, self); - NDO_CASTV(ListObject, target, src); - - destructor(in); - - for (auto item : src->items) { - self->pushBack(NDO->instatiate(item.data())); - } -} - -void ListObject::destructor(Object* in) { - NDO_CASTV(ListObject, in, self); - for (auto item : self->items) { - NDO->destroy(item.data()); - } - self->items.removeAll(); -} - -alni ListObject::save_size(ListObject* self) { - alni len = self->items.length(); - return (len + 1) * sizeof(alni); -} - -void ListObject::save(ListObject* self, ArchiverOut& file_self) { - alni len = self->items.length(); - file_self << len; - - for (auto item : self->items) { - alni ndo_object_adress = NDO->save(file_self, item.data()); - file_self << ndo_object_adress; - } -} - -void ListObject::load(ArchiverIn& file_self, ListObject* self) { - new (&self->items) tp::List(); - - alni len; - file_self >> len; - - for (alni i = 0; i < len; i++) { - alni ndo_object_adress; - file_self >> ndo_object_adress; - self->pushBack(NDO->load(file_self, ndo_object_adress)); - } -} - -tp::Buffer ListObject::childs_retrival(ListObject* self) { - tp::Buffer out; - out.reserve(self->items.length()); - ualni i = 0; - for (auto item : self->items) { - out[i] = item.data(); - i++; - } - return out; -} - -alni ListObject::allocated_size(ListObject* self) { - // return self->items.sizeAllocatedMem(); - return {}; -} - -alni ListObject::allocated_size_recursive(ListObject* self) { - ASSERT(false) - //alni out = self->items.sizeAllocatedMem(); - for (auto item : self->items) { - //out += NDO->objsize_ram_recursive_util(item.data(), item->type); - } - // return out; - return 0; -} - -void ListObject::pushBack(Object* obj) { -#ifdef OBJECT_REF_COUNT - obj::NDO->refinc(obj); -#endif // OBJECT_REF_COUNT - items.pushBack(obj); -} - -void ListObject::pushFront(Object* obj) { -#ifdef OBJECT_REF_COUNT - obj::NDO->refinc(obj); -#endif // OBJECT_REF_COUNT - items.pushFront(obj); -} - -void ListObject::delNode(tp::List::Node* node) { -#ifdef OBJECT_REF_COUNT - obj::NDO->destroy(node->data); -#endif // OBJECT_REF_COUNT - items.deleteNode(node); -} - -void ListObject::popBack() { -#ifdef OBJECT_REF_COUNT - auto obj = items.last(); - if (obj) obj::NDO->destroy(obj->data); -#endif // OBJECT_REF_COUNT - items.popBack(); -} - -const tp::List& ListObject::getItems() const { - return items; -} - -struct obj::ObjectType obj::ListObject::TypeData = { - .base = NULL, - .constructor = ListObject::constructor, - .destructor = ListObject::destructor, - .copy = ListObject::copy, - .size = sizeof(ListObject), - .name = "list", - .convesions = NULL, - .save_size = (object_save_size)save_size, - .save = (object_save)save, - .load = (object_load)load, - .childs_retrival = (object_debug_all_childs_retrival) childs_retrival, - .allocated_size = (object_allocated_size) allocated_size, - .allocated_size_recursive = (object_allocated_size_recursive) allocated_size_recursive -}; \ No newline at end of file + +#pragma once + +#include "NewPlacement.hpp" + +#include "primitives/intobject.h" +#include "primitives/listobject.h" + +using namespace obj; +using namespace tp; + +void ListObject::constructor(Object* in) { + NDO_CASTV(ListObject, in, self); + new (&self->items) List(); +} + +void ListObject::copy(Object* in, const Object* target) { + NDO_CASTV(ListObject, in, self); + NDO_CASTV(ListObject, target, src); + + destructor(in); + + for (auto item : src->items) { + self->pushBack(NDO->instatiate(item.data())); + } +} + +void ListObject::destructor(Object* in) { + NDO_CASTV(ListObject, in, self); + for (auto item : self->items) { + NDO->destroy(item.data()); + } + self->items.removeAll(); +} + +alni ListObject::save_size(ListObject* self) { + alni len = self->items.length(); + return (len + 1) * sizeof(alni); +} + +void ListObject::save(ListObject* self, ArchiverOut& file_self) { + alni len = self->items.length(); + file_self << len; + + for (auto item : self->items) { + alni ndo_object_adress = NDO->save(file_self, item.data()); + file_self << ndo_object_adress; + } +} + +void ListObject::load(ArchiverIn& file_self, ListObject* self) { + new (&self->items) tp::List(); + + alni len; + file_self >> len; + + for (alni i = 0; i < len; i++) { + alni ndo_object_adress; + file_self >> ndo_object_adress; + self->pushBack(NDO->load(file_self, ndo_object_adress)); + } +} + +tp::Buffer ListObject::childs_retrival(ListObject* self) { + tp::Buffer out; + out.reserve(self->items.length()); + ualni i = 0; + for (auto item : self->items) { + out[i] = item.data(); + i++; + } + return out; +} + +alni ListObject::allocated_size(ListObject* self) { + // return self->items.sizeAllocatedMem(); + return {}; +} + +alni ListObject::allocated_size_recursive(ListObject* self) { + ASSERT(false) + // alni out = self->items.sizeAllocatedMem(); + for (auto item : self->items) { + // out += NDO->objsize_ram_recursive_util(item.data(), item->type); + } + // return out; + return 0; +} + +void ListObject::pushBack(Object* obj) { +#ifdef OBJECT_REF_COUNT + obj::NDO->refinc(obj); +#endif // OBJECT_REF_COUNT + items.pushBack(obj); +} + +void ListObject::pushFront(Object* obj) { +#ifdef OBJECT_REF_COUNT + obj::NDO->refinc(obj); +#endif // OBJECT_REF_COUNT + items.pushFront(obj); +} + +void ListObject::delNode(tp::List::Node* node) { +#ifdef OBJECT_REF_COUNT + obj::NDO->destroy(node->data); +#endif // OBJECT_REF_COUNT + items.deleteNode(node); +} + +void ListObject::popBack() { +#ifdef OBJECT_REF_COUNT + auto obj = items.last(); + if (obj) obj::NDO->destroy(obj->data); +#endif // OBJECT_REF_COUNT + items.popBack(); +} + +const tp::List& ListObject::getItems() const { return items; } + +struct obj::ObjectType obj::ListObject::TypeData = { .base = NULL, + .constructor = ListObject::constructor, + .destructor = ListObject::destructor, + .copy = ListObject::copy, + .size = sizeof(ListObject), + .name = "list", + .convesions = NULL, + .save_size = (object_save_size) save_size, + .save = (object_save) save, + .load = (object_load) load, + .childs_retrival = (object_debug_all_childs_retrival) childs_retrival, + .allocated_size = (object_allocated_size) allocated_size, + .allocated_size_recursive = (object_allocated_size_recursive) allocated_size_recursive }; \ No newline at end of file diff --git a/Objects/private/primitives/methodobject.cpp b/Objects/private/primitives/methodobject.cpp index 7a7f375..e0af945 100644 --- a/Objects/private/primitives/methodobject.cpp +++ b/Objects/private/primitives/methodobject.cpp @@ -1,76 +1,65 @@ -#pragma once - -#include "NewPlacement.hpp" - -#include "primitives/methodobject.h" -#include "core/scriptsection.h" -#include "compiler/function.h" - -using namespace obj; - -struct ObjectType MethodObject::TypeData = { - .base = NULL, - .constructor = (object_constructor)MethodObject::constructor, - .destructor = (object_destructor)MethodObject::destructor, - .copy = (object_copy)MethodObject::copy, - .size = sizeof(MethodObject), - .name = "method", - .convesions = NULL, - .save_size = (object_save_size)MethodObject::save_size, - .save = (object_save)MethodObject::save, - .load = (object_load)MethodObject::load, -}; - -void MethodObject::constructor(MethodObject* self) { - self->mScript = obj::ScriptSection::globalHandle()->createScript(); -} - -void MethodObject::copy(MethodObject* self, MethodObject* in) { - obj::ScriptSection::globalHandle()->changeScript(&self->mScript, &in->mScript); -} - -void MethodObject::destructor(MethodObject* self) { - obj::ScriptSection::globalHandle()->abandonScript(self->mScript); -} - -tp::alni MethodObject::save_size(MethodObject* self) { - // script_table_file_address & script string object address - return sizeof(tp::alni); -} - -void MethodObject::save(MethodObject* self, ArchiverOut& file_self) { - auto script_section = obj::ScriptSection::globalHandle(); - // script_table_file_address - tp::alni script_table_file_address = script_section->get_script_file_adress(self->mScript); - file_self << script_table_file_address; -} - -void MethodObject::load(ArchiverIn& file_self, obj::MethodObject* self) { - auto script_section = obj::ScriptSection::globalHandle(); - // script_table_file_address - tp::alni script_table_file_address; - file_self >> script_table_file_address; - self->mScript = script_section->get_scritp_from_file_adress(script_table_file_address); -} - - -void MethodObject::Initialize() { - obj::ScriptSection::initialize(); - NDO->define(&MethodObject::TypeData); - obj::NDO->type_groups.addType(&MethodObject::TypeData, { "Primitives" }); -} - -void MethodObject::UnInitialize() { - obj::ScriptSection::uninitialize(); -} - -void MethodObject::compile() { - BCgen::Compile(this); -} - -MethodObject* MethodObject::create(tp::String script) { - auto out = (MethodObject*)NDO->create(MethodObject::TypeData.name); - out->mScript->mReadable->val = script; - out->compile(); - return out; +#pragma once + +#include "NewPlacement.hpp" + +#include "compiler/function.h" +#include "core/scriptsection.h" +#include "primitives/methodobject.h" + +using namespace obj; + +struct ObjectType MethodObject::TypeData = { + .base = NULL, + .constructor = (object_constructor) MethodObject::constructor, + .destructor = (object_destructor) MethodObject::destructor, + .copy = (object_copy) MethodObject::copy, + .size = sizeof(MethodObject), + .name = "method", + .convesions = NULL, + .save_size = (object_save_size) MethodObject::save_size, + .save = (object_save) MethodObject::save, + .load = (object_load) MethodObject::load, +}; + +void MethodObject::constructor(MethodObject* self) { self->mScript = obj::ScriptSection::globalHandle()->createScript(); } + +void MethodObject::copy(MethodObject* self, MethodObject* in) { obj::ScriptSection::globalHandle()->changeScript(&self->mScript, &in->mScript); } + +void MethodObject::destructor(MethodObject* self) { obj::ScriptSection::globalHandle()->abandonScript(self->mScript); } + +tp::alni MethodObject::save_size(MethodObject* self) { + // script_table_file_address & script string object address + return sizeof(tp::alni); +} + +void MethodObject::save(MethodObject* self, ArchiverOut& file_self) { + auto script_section = obj::ScriptSection::globalHandle(); + // script_table_file_address + tp::alni script_table_file_address = script_section->get_script_file_adress(self->mScript); + file_self << script_table_file_address; +} + +void MethodObject::load(ArchiverIn& file_self, obj::MethodObject* self) { + auto script_section = obj::ScriptSection::globalHandle(); + // script_table_file_address + tp::alni script_table_file_address; + file_self >> script_table_file_address; + self->mScript = script_section->get_scritp_from_file_adress(script_table_file_address); +} + +void MethodObject::Initialize() { + obj::ScriptSection::initialize(); + NDO->define(&MethodObject::TypeData); + obj::NDO->type_groups.addType(&MethodObject::TypeData, { "Primitives" }); +} + +void MethodObject::UnInitialize() { obj::ScriptSection::uninitialize(); } + +void MethodObject::compile() { BCgen::Compile(this); } + +MethodObject* MethodObject::create(tp::String script) { + auto out = (MethodObject*) NDO->create(MethodObject::TypeData.name); + out->mScript->mReadable->val = script; + out->compile(); + return out; } \ No newline at end of file diff --git a/Objects/private/primitives/nullobject.cpp b/Objects/private/primitives/nullobject.cpp index 846c842..d1f09c6 100644 --- a/Objects/private/primitives/nullobject.cpp +++ b/Objects/private/primitives/nullobject.cpp @@ -1,60 +1,50 @@ - -#pragma once - -#include "NewPlacement.hpp" - -#include "primitives/nullobject.h" - -using namespace obj; -using namespace tp; - -obj::NullObject* obj::NdoNull_globalInstance = NULL; -bool uninit_flag = false; - -void NullObject::uninit() { - uninit_flag = true; - NDO->destroy(NdoNull_globalInstance); -} - -void NullObject::destructor(Object* self) { - DEBUG_ASSERT(uninit_flag && "Only one the instance of NullObject exists and thus it can't be destroyed"); -} - - -String to_string(NullObject* self) { - return "NULL"; -} - -alni to_int(NullObject* self) { - return 0; -} - -alnf to_float(NullObject* self) { - return 0; -} - -obj::TypeMethods* tm_construct() { - auto out = new obj::TypeMethods(); - - return out; -} - -struct ObjectTypeConversions NullObjectTypeConversions = { - .from_int = NULL, - .from_float = NULL, - .from_string = NULL, - .to_string = (object_to_string) to_string, - .to_int = (object_to_int) to_int, - .to_float = (object_to_float) to_float, -}; - - -struct ObjectType NullObject::TypeData = { - .base = NULL, - .constructor = NULL, - .destructor = NullObject::destructor, - .copy = NULL, - .size = sizeof(NullObject), - .name = "null", - .convesions = &NullObjectTypeConversions, + +#pragma once + +#include "NewPlacement.hpp" + +#include "primitives/nullobject.h" + +using namespace obj; +using namespace tp; + +obj::NullObject* obj::NdoNull_globalInstance = NULL; +bool uninit_flag = false; + +void NullObject::uninit() { + uninit_flag = true; + NDO->destroy(NdoNull_globalInstance); +} + +void NullObject::destructor(Object* self) { DEBUG_ASSERT(uninit_flag && "Only one the instance of NullObject exists and thus it can't be destroyed"); } + +String to_string(NullObject* self) { return "NULL"; } + +alni to_int(NullObject* self) { return 0; } + +alnf to_float(NullObject* self) { return 0; } + +obj::TypeMethods* tm_construct() { + auto out = new obj::TypeMethods(); + + return out; +} + +struct ObjectTypeConversions NullObjectTypeConversions = { + .from_int = NULL, + .from_float = NULL, + .from_string = NULL, + .to_string = (object_to_string) to_string, + .to_int = (object_to_int) to_int, + .to_float = (object_to_float) to_float, +}; + +struct ObjectType NullObject::TypeData = { + .base = NULL, + .constructor = NULL, + .destructor = NullObject::destructor, + .copy = NULL, + .size = sizeof(NullObject), + .name = "null", + .convesions = &NullObjectTypeConversions, }; \ No newline at end of file diff --git a/Objects/private/primitives/stringobject.cpp b/Objects/private/primitives/stringobject.cpp index 3c44b49..941506a 100644 --- a/Objects/private/primitives/stringobject.cpp +++ b/Objects/private/primitives/stringobject.cpp @@ -1,96 +1,78 @@ - -#pragma once - -#include "NewPlacement.hpp" - -#include "primitives/stringobject.h" - -using namespace obj; -using namespace tp; - -void StringObject::constructor(Object* self) { - new (&NDO_CAST(StringObject, self)->val) String(); -} - -void StringObject::destructor(StringObject* self) { - self->val.~String(); -} - -void StringObject::copy(Object* self, const Object* in) { - NDO_CAST(StringObject, self)->val = NDO_CAST(StringObject, in)->val; -} - -StringObject* StringObject::create(String in) { - NDO_CASTV(StringObject, NDO->create("str"), out)->val = in; - return out; -} - -void StringObject::from_int(StringObject* self, alni in) { - // self->val = in; -} - -void StringObject::from_float(StringObject* self, alnf in) { - // self->val = in; -} - -void StringObject::from_string(StringObject* self, String in) { - // self->val = in; -} - -String StringObject::to_string(StringObject* self) { - return self->val; -} - -alni StringObject::to_int(StringObject* self) { - return alni(self->val); -} - -alnf StringObject::to_float(StringObject* self) { - return alnf(self->val); -} - -static alni save_size(StringObject* self) { - return tp::SaveSizeCounter::calc(self->val); -} - -static void save(StringObject* self, ArchiverOut& file_self) { - file_self << self->val; -} - -static void load(ArchiverIn& file_self, StringObject* self) { - new (&self->val) tp::String(); - file_self >> self->val; -} - -alni allocated_size(StringObject* self) { - // return self->val.sizeAllocatedMem(); - return 0; -} - -static bool compare_strings(StringObject* left, StringObject* right) { - return left->val == right->val; -} - -struct ObjectTypeConversions StringObjectTypeConversions = { - .from_int = (object_from_int)StringObject::from_int, - .from_float = (object_from_float)StringObject::from_float, - .from_string = (object_from_string)StringObject::from_string, - .to_string = (object_to_string)StringObject::to_string, - .to_int = (object_to_int)StringObject::to_int, - .to_float = (object_to_float)StringObject::to_float, -}; - -struct obj::ObjectType StringObject::TypeData = { - .base = NULL, - .constructor = StringObject::constructor, - .destructor = (object_destructor)StringObject::destructor, - .copy = StringObject::copy, - .size = sizeof(StringObject), - .name = "str", - .convesions = &StringObjectTypeConversions, - .save_size = (object_save_size)save_size, - .save = (object_save)save, - .load = (object_load)load, - .comparison = (object_compare) compare_strings, - .allocated_size = (object_allocated_size) allocated_size, + +#pragma once + +#include "NewPlacement.hpp" + +#include "primitives/stringobject.h" + +using namespace obj; +using namespace tp; + +void StringObject::constructor(Object* self) { new (&NDO_CAST(StringObject, self)->val) String(); } + +void StringObject::destructor(StringObject* self) { self->val.~String(); } + +void StringObject::copy(Object* self, const Object* in) { NDO_CAST(StringObject, self)->val = NDO_CAST(StringObject, in)->val; } + +StringObject* StringObject::create(String in) { + NDO_CASTV(StringObject, NDO->create("str"), out)->val = in; + return out; +} + +void StringObject::from_int(StringObject* self, alni in) { + // self->val = in; +} + +void StringObject::from_float(StringObject* self, alnf in) { + // self->val = in; +} + +void StringObject::from_string(StringObject* self, String in) { + // self->val = in; +} + +String StringObject::to_string(StringObject* self) { return self->val; } + +alni StringObject::to_int(StringObject* self) { return alni(self->val); } + +alnf StringObject::to_float(StringObject* self) { return alnf(self->val); } + +static alni save_size(StringObject* self) { return tp::SaveSizeCounter::calc(self->val); } + +static void save(StringObject* self, ArchiverOut& file_self) { file_self << self->val; } + +static void load(ArchiverIn& file_self, StringObject* self) { + new (&self->val) tp::String(); + file_self >> self->val; +} + +alni allocated_size(StringObject* self) { + // return self->val.sizeAllocatedMem(); + return 0; +} + +static bool compare_strings(StringObject* left, StringObject* right) { return left->val == right->val; } + +struct ObjectTypeConversions StringObjectTypeConversions = { + .from_int = (object_from_int) StringObject::from_int, + .from_float = (object_from_float) StringObject::from_float, + .from_string = (object_from_string) StringObject::from_string, + .to_string = (object_to_string) StringObject::to_string, + .to_int = (object_to_int) StringObject::to_int, + .to_float = (object_to_float) StringObject::to_float, +}; + +struct obj::ObjectType StringObject::TypeData = { + .base = NULL, + .constructor = StringObject::constructor, + .destructor = (object_destructor) StringObject::destructor, + .copy = StringObject::copy, + .size = sizeof(StringObject), + .name = "str", + .convesions = &StringObjectTypeConversions, + .save_size = (object_save_size) save_size, + .save = (object_save) save, + .load = (object_load) load, + .comparison = (object_compare) compare_strings, + .allocated_size = (object_allocated_size) allocated_size, }; \ No newline at end of file diff --git a/Objects/private/primitives/typeobject.cpp b/Objects/private/primitives/typeobject.cpp index 7e5288f..9e84fe5 100644 --- a/Objects/private/primitives/typeobject.cpp +++ b/Objects/private/primitives/typeobject.cpp @@ -1,80 +1,72 @@ - -#pragma once - -#include "NewPlacement.hpp" -#include "primitives/typeobject.h" -#include "primitives/nullobject.h" - -using namespace obj; -using namespace tp; - -TypeObject* TypeObject::create(const ObjectType* type) { - NDO_CASTV(TypeObject, NDO->create("typeobject"), out); - out->mTypeRef = type; - return out; -} - -static alni save_size(TypeObject* self) { - tp::String const nameid(self->mTypeRef->name); - return nameid.size() + sizeof(nameid.size()); -} - -static void save(TypeObject* self, ArchiverOut& file_self) { - tp::String const nameid(self->mTypeRef->name); - file_self << nameid; -} - -static void load(ArchiverIn& file_self, TypeObject* self) { - tp::String nameid; - file_self >> nameid; - - auto idx = NDO->types.presents(nameid); - - if (idx) { - self->mTypeRef = NDO->types.getSlotVal(idx); - } - else { - self->mTypeRef = &NullObject::TypeData; - } -} - -static alni allocated_size(TypeObject* self) { - return sizeof(alni); -} - -static void from_string(TypeObject* self, tp::String in) { - auto idx = NDO->types.presents(in); - - if (idx) { - self->mTypeRef = NDO->types.getSlotVal(idx); - } - else { - self->mTypeRef = &NullObject::TypeData; - } -} - -static String to_string(TypeObject* self) { - return self->mTypeRef->name; -} - -bool comparator(TypeObject* left, TypeObject* right) { - return left->mTypeRef == right->mTypeRef; -} - -static struct ObjectTypeConversions conversions = { - .from_string = (object_from_string) from_string, - .to_string = (object_to_string) to_string, -}; - -struct obj::ObjectType TypeObject::TypeData = { - .base = NULL, - //.constructor = (object_constructor) TypeObject::constructor, - .size = sizeof(TypeObject), - .name = "typeobject", - .convesions = &conversions, - .save_size = (object_save_size) save_size, - .save = (object_save) save, - .load = (object_load) load, - .comparison = (object_compare) comparator, - .allocated_size = (object_allocated_size) allocated_size, + +#pragma once + +#include "primitives/typeobject.h" +#include "NewPlacement.hpp" +#include "primitives/nullobject.h" + +using namespace obj; +using namespace tp; + +TypeObject* TypeObject::create(const ObjectType* type) { + NDO_CASTV(TypeObject, NDO->create("typeobject"), out); + out->mTypeRef = type; + return out; +} + +static alni save_size(TypeObject* self) { + tp::String const nameid(self->mTypeRef->name); + return nameid.size() + sizeof(nameid.size()); +} + +static void save(TypeObject* self, ArchiverOut& file_self) { + tp::String const nameid(self->mTypeRef->name); + file_self << nameid; +} + +static void load(ArchiverIn& file_self, TypeObject* self) { + tp::String nameid; + file_self >> nameid; + + auto idx = NDO->types.presents(nameid); + + if (idx) { + self->mTypeRef = NDO->types.getSlotVal(idx); + } else { + self->mTypeRef = &NullObject::TypeData; + } +} + +static alni allocated_size(TypeObject* self) { return sizeof(alni); } + +static void from_string(TypeObject* self, tp::String in) { + auto idx = NDO->types.presents(in); + + if (idx) { + self->mTypeRef = NDO->types.getSlotVal(idx); + } else { + self->mTypeRef = &NullObject::TypeData; + } +} + +static String to_string(TypeObject* self) { return self->mTypeRef->name; } + +bool comparator(TypeObject* left, TypeObject* right) { return left->mTypeRef == right->mTypeRef; } + +static struct ObjectTypeConversions conversions = { + .from_string = (object_from_string) from_string, + .to_string = (object_to_string) to_string, +}; + +struct obj::ObjectType TypeObject::TypeData = { + .base = NULL, + //.constructor = (object_constructor) TypeObject::constructor, + .size = sizeof(TypeObject), + .name = "typeobject", + .convesions = &conversions, + .save_size = (object_save_size) save_size, + .save = (object_save) save, + .load = (object_load) load, + .comparison = (object_compare) comparator, + .allocated_size = (object_allocated_size) allocated_size, }; \ No newline at end of file diff --git a/Objects/tests/Tests.cpp b/Objects/tests/Tests.cpp index 90728d7..e5e07bb 100644 --- a/Objects/tests/Tests.cpp +++ b/Objects/tests/Tests.cpp @@ -7,7 +7,6 @@ using namespace tp; using namespace obj; - void testCore(); void testPrimitives(); void testInterpreter(); diff --git a/Objects/tests/core/TestCore.cpp b/Objects/tests/core/TestCore.cpp index 9166570..7816e62 100644 --- a/Objects/tests/core/TestCore.cpp +++ b/Objects/tests/core/TestCore.cpp @@ -26,11 +26,8 @@ TEST_DEF_STATIC(BasicAPI) { TEST(NDO_CAST(IntObject, savedInt)); TEST(integer->val == NDO_CAST(IntObject, savedInt)->val); - NDO->destroy(integer); NDO->destroy(savedInt); } -TEST_DEF(Core) { - testBasicAPI(); -} \ No newline at end of file +TEST_DEF(Core) { testBasicAPI(); } \ No newline at end of file diff --git a/Objects/tests/interpreter/TestInterpreter.cpp b/Objects/tests/interpreter/TestInterpreter.cpp index 9a0c592..c23929e 100644 --- a/Objects/tests/interpreter/TestInterpreter.cpp +++ b/Objects/tests/interpreter/TestInterpreter.cpp @@ -3,12 +3,12 @@ #include "Testing.hpp" +#include "compiler/function.h" #include "core/object.h" -#include "primitives/methodobject.h" +#include "interpreter/interpreter.h" #include "primitives/interpreterobject.h" #include "primitives/linkobject.h" -#include "compiler/function.h" -#include "interpreter/interpreter.h" +#include "primitives/methodobject.h" using namespace tp; using namespace obj; @@ -57,7 +57,6 @@ TEST_DEF_STATIC(Complex) { interpreter->exec(); - NDO->destroy(interpreter); } @@ -84,5 +83,5 @@ TEST_DEF_STATIC(Simple) { TEST_DEF(Interpreter) { testSimple(); - //testComplex(); + // testComplex(); } \ No newline at end of file diff --git a/Objects/tests/primitives/TestPrimitives.cpp b/Objects/tests/primitives/TestPrimitives.cpp index 4e7d01b..1eacf6e 100644 --- a/Objects/tests/primitives/TestPrimitives.cpp +++ b/Objects/tests/primitives/TestPrimitives.cpp @@ -30,6 +30,4 @@ TEST_DEF_STATIC(Dict) { NDO->destroy(dictLoaded); } -TEST_DEF(Primitives) { - testDict(); -} \ No newline at end of file +TEST_DEF(Primitives) { testDict(); } \ No newline at end of file diff --git a/Parser/applications/Cfg.cpp b/Parser/applications/Cfg.cpp index c7e467a..2aca37b 100644 --- a/Parser/applications/Cfg.cpp +++ b/Parser/applications/Cfg.cpp @@ -1,8 +1,8 @@ #include "NewPlacement.hpp" -#include "Parser.hpp" #include "CommandLine.hpp" +#include "Parser.hpp" using namespace tp; @@ -29,7 +29,8 @@ void run(const String& source) { grammar.generateSentences(sentences); printf("Example sentences formed from grammar: \n"); - for (auto sentence : sentences) tp::CfGrammar::printSentence(sentence.data()); + for (auto sentence : sentences) + tp::CfGrammar::printSentence(sentence.data()); CfGrammar::deinitializeCfGrammarParser(state); } @@ -50,7 +51,7 @@ int main(int argc, const char* argv[]) { printf("\n"); CommandLine cmd = { - { "grammar", CommandLine::Arg::STR }, + { "grammar", CommandLine::Arg::STR }, }; if (!cmd.parse((char) argc, argv, true, 1)) { @@ -73,7 +74,6 @@ int main(int argc, const char* argv[]) { grammar.resize((String::Index) size); file.readBytes(grammar.write(), size); - run(grammar); file.disconnect(); diff --git a/Parser/private/CLR.cpp b/Parser/private/CLR.cpp index 673693f..7625b8b 100644 --- a/Parser/private/CLR.cpp +++ b/Parser/private/CLR.cpp @@ -13,14 +13,8 @@ void CLR::setGrammar(const tp::CfGrammar& grammar) { mState = ParserState::FAILED; } -void CLR::setTerminal(const String& name, TerminalStream::TerminalID id) { +void CLR::setTerminal(const String& name, TerminalStream::TerminalID id) {} -} +void CLR::build() {} -void CLR::build() { - -} - -void CLR::parse(TerminalStream* source, List& out, ASTNode** root) { - *root = nullptr; -} \ No newline at end of file +void CLR::parse(TerminalStream* source, List& out, ASTNode** root) { *root = nullptr; } \ No newline at end of file diff --git a/Parser/private/CfGrammar.cpp b/Parser/private/CfGrammar.cpp index cd925ad..bfc3d64 100644 --- a/Parser/private/CfGrammar.cpp +++ b/Parser/private/CfGrammar.cpp @@ -1,6 +1,6 @@ -#include "NewPlacement.hpp" #include "CfGrammar.hpp" +#include "NewPlacement.hpp" #include "Timing.hpp" @@ -16,10 +16,10 @@ void CfGrammar::generateSentences(List& out) { // add start production Sentence start; - start.terms.pushBack( { startTerminal, false } ); + start.terms.pushBack({ startTerminal, false }); queue.pushBack(start); - PASS: +PASS: auto const sentential = &queue.first()->data; bool isSentence = true; diff --git a/Parser/private/CfGrammarParser.cpp b/Parser/private/CfGrammarParser.cpp index 3502a2f..04d5c00 100644 --- a/Parser/private/CfGrammarParser.cpp +++ b/Parser/private/CfGrammarParser.cpp @@ -43,16 +43,16 @@ typedef Buffer Automata; void initializeTokenizer(CFGTokenizer* tok) { tok->build({ - { CFGTokenizer::tTokenizer::etherRE, Token::IGNORED }, - { "Start", Token::START }, - { ":", Token::EQUAL }, - { "\\[", Token::TERMINAL_START }, - { "\\]", Token::TERMINAL_END }, - { "\\|", Token::ALTERNATION }, - { ";", Token::RULE_END }, - { "&", Token::EPSILON }, - { CFGTokenizer::tTokenizer::idRE, Token::ID }, - { CFGTokenizer::tTokenizer::commentBlockRE, Token::COMMENT }, + { CFGTokenizer::tTokenizer::etherRE, Token::IGNORED }, + { "Start", Token::START }, + { ":", Token::EQUAL }, + { "\\[", Token::TERMINAL_START }, + { "\\]", Token::TERMINAL_END }, + { "\\|", Token::ALTERNATION }, + { ";", Token::RULE_END }, + { "&", Token::EPSILON }, + { CFGTokenizer::tTokenizer::idRE, Token::ID }, + { CFGTokenizer::tTokenizer::commentBlockRE, Token::COMMENT }, }); ASSERT(tok->isBuild()) @@ -71,54 +71,54 @@ void initAutomata(Automata& automata) { auto terminalEnd = states; root->transitions = { - { Token::END, end }, - { Token::START, start }, - { Token::ID, rule, [](CfGrammar* grammar, const String& tok) { - grammar->rules.pushBack({ tok, {} }); - } - }, + { Token::END, end }, + { Token::START, start }, + { Token::ID, + rule, + [](CfGrammar* grammar, const String& tok) { + grammar->rules.pushBack({ tok, {} }); + } }, }; start->transitions = { - { Token::ID, - root, - [](CfGrammar* grammar, const String& tok) { - grammar->startTerminal = tok; - } - }, + { Token::ID, root, [](CfGrammar* grammar, const String& tok) { grammar->startTerminal = tok; } }, }; rule->transitions = { - { Token::EQUAL, rhs }, + { Token::EQUAL, rhs }, }; rhs->transitions = { - { Token::ALTERNATION, rhs, [](CfGrammar* grammar, const String& tok) { - auto const& id = grammar->rules.last()->data.id; - grammar->rules.pushBack({ id, {} }); - } - }, - { Token::ID, rhs, [](CfGrammar* grammar, const String& tok) { - grammar->rules.last()->data.args.pushBack({ tok, false, false }); - } - }, - { Token::EPSILON, rhs, [](CfGrammar* grammar, const String& tok) { - grammar->rules.last()->data.args.pushBack({ tok, false, true }); - } - }, - { Token::TERMINAL_START, terminalStart }, - { Token::RULE_END, root }, + { Token::ALTERNATION, + rhs, + [](CfGrammar* grammar, const String& tok) { + auto const& id = grammar->rules.last()->data.id; + grammar->rules.pushBack({ id, {} }); + } }, + { Token::ID, + rhs, + [](CfGrammar* grammar, const String& tok) { + grammar->rules.last()->data.args.pushBack({ tok, false, false }); + } }, + { Token::EPSILON, + rhs, + [](CfGrammar* grammar, const String& tok) { + grammar->rules.last()->data.args.pushBack({ tok, false, true }); + } }, + { Token::TERMINAL_START, terminalStart }, + { Token::RULE_END, root }, }; terminalStart->transitions = { - { Token::ID, terminalEnd, [](CfGrammar* grammar, const String& tok) { - grammar->rules.last()->data.args.pushBack({ tok, true, false }); - } - }, + { Token::ID, + terminalEnd, + [](CfGrammar* grammar, const String& tok) { + grammar->rules.last()->data.args.pushBack({ tok, true, false }); + } }, }; terminalEnd->transitions = { - { Token::TERMINAL_END, rhs }, + { Token::TERMINAL_END, rhs }, }; auto idError = "Expected an identifier"; @@ -196,14 +196,8 @@ CfGrammarParserState* CfGrammar::initializeCfGrammarParser() { return state; } -void CfGrammar::deinitializeCfGrammarParser(CfGrammarParserState* state) { - delete state; -} +void CfGrammar::deinitializeCfGrammarParser(CfGrammarParserState* state) { delete state; } -bool CfGrammar::parse(CfGrammarParserState* context, const String& source) { - return ::parse(source.read(), &context->automata, &context->tokenizer, this); -} +bool CfGrammar::parse(CfGrammarParserState* context, const String& source) { return ::parse(source.read(), &context->automata, &context->tokenizer, this); } -bool CfGrammar::isLooped() const { - return mIsLooped; -} +bool CfGrammar::isLooped() const { return mIsLooped; } diff --git a/Parser/private/Parser.cpp b/Parser/private/Parser.cpp index 61d09bb..e292312 100644 --- a/Parser/private/Parser.cpp +++ b/Parser/private/Parser.cpp @@ -1,5 +1,5 @@ -#include "NewPlacement.hpp" #include "Parser.hpp" +#include "NewPlacement.hpp" #include "Tokenizer.hpp" diff --git a/Parser/public/CLR.hpp b/Parser/public/CLR.hpp index 5d9d8ff..d38de44 100644 --- a/Parser/public/CLR.hpp +++ b/Parser/public/CLR.hpp @@ -12,14 +12,13 @@ namespace tp { class Automation { public: - class State { - - }; + class State {}; }; class TerminalStream { public: typedef ualni TerminalID; + public: TerminalStream() = default; virtual TerminalID getNextTerminal() = 0; @@ -36,9 +35,7 @@ namespace tp { }; private: - class SententialStack { - - }; + class SententialStack {}; public: CLR() = default; diff --git a/Parser/public/CfGrammar.hpp b/Parser/public/CfGrammar.hpp index c99ce55..90b7195 100644 --- a/Parser/public/CfGrammar.hpp +++ b/Parser/public/CfGrammar.hpp @@ -1,8 +1,8 @@ #pragma once -#include "Strings.hpp" #include "List.hpp" #include "Map.hpp" +#include "Strings.hpp" namespace tp { @@ -13,17 +13,13 @@ namespace tp { bool isTerminal = false; bool isEpsilon = false; - bool operator==(const Arg& in) const { - return (id == in.id) && (isEpsilon == in.isEpsilon) && (isTerminal == in.isTerminal); - } + bool operator==(const Arg& in) const { return (id == in.id) && (isEpsilon == in.isEpsilon) && (isTerminal == in.isTerminal); } }; String id; List args; - bool operator==(const Rule& in) const { - return (id == in.id) && (args == in.args); - } + bool operator==(const Rule& in) const { return (id == in.id) && (args == in.args); } [[nodiscard]] bool isProductive() const { for (auto arg : args) { @@ -37,9 +33,7 @@ namespace tp { struct Term { String id; bool terminal; - bool operator==(const Term& in) const { - return (id == in.id) && (terminal == in.terminal); - } + bool operator==(const Term& in) const { return (id == in.id) && (terminal == in.terminal); } }; List terms; }; diff --git a/Parser/tests/CLRTests.cpp b/Parser/tests/CLRTests.cpp index b774572..60708a8 100644 --- a/Parser/tests/CLRTests.cpp +++ b/Parser/tests/CLRTests.cpp @@ -1,10 +1,10 @@ #include "NewPlacement.hpp" -#include "Testing.hpp" #include "Parser.hpp" +#include "Testing.hpp" using namespace tp; TEST_DEF(CLR) { - //TEST(false); + // TEST(false); } \ No newline at end of file diff --git a/Parser/tests/GrammarTests.cpp b/Parser/tests/GrammarTests.cpp index 28697f5..f45e670 100644 --- a/Parser/tests/GrammarTests.cpp +++ b/Parser/tests/GrammarTests.cpp @@ -1,7 +1,7 @@ #include "NewPlacement.hpp" -#include "Testing.hpp" #include "Parser.hpp" +#include "Testing.hpp" using namespace tp; @@ -40,9 +40,10 @@ List : [ LIST ]; TEST_ASSERT(sentences.first()->data.terms.length() == 1); TEST_ASSERT(sentences.last()->data.terms.length() == 1); - TEST(sentences.first()->data.terms.first()->data.id == "Function"); + TEST(sentences.first()->data.terms.first()->data.id == "Function"); TEST(sentences.last()->data.terms.first()->data.id == "LIST"); printf("Example sentences formed from grammar: \n"); - for (auto sentence : sentences) tp::CfGrammar::printSentence(sentence.data()); + for (auto sentence : sentences) + tp::CfGrammar::printSentence(sentence.data()); } \ No newline at end of file diff --git a/Parser/tests/Tests.cpp b/Parser/tests/Tests.cpp index fb2fd04..90a03e9 100644 --- a/Parser/tests/Tests.cpp +++ b/Parser/tests/Tests.cpp @@ -1,7 +1,7 @@ #include "NewPlacement.hpp" -#include "Testing.hpp" #include "Parser.hpp" +#include "Testing.hpp" using namespace tp; diff --git a/RayTracer/applications/Rayt.cpp b/RayTracer/applications/Rayt.cpp index 96dab57..2516035 100644 --- a/RayTracer/applications/Rayt.cpp +++ b/RayTracer/applications/Rayt.cpp @@ -12,89 +12,89 @@ using namespace tp; void writeImage(const RayTracer::RenderBuffer& output, const char* name) { - // Save the data to a PNG file - struct urgb { - uint1 r, g, b, a; - }; + // Save the data to a PNG file + struct urgb { + uint1 r, g, b, a; + }; - Buffer2D converted; - converted.reserve(output.size()); + Buffer2D converted; + converted.reserve(output.size()); - for (RayTracer::RenderBuffer::Index i = 0; i < output.size().x; i++) { - for (RayTracer::RenderBuffer::Index j = 0; j < output.size().y; j++) { - converted.get({i, j}).r = uint1(output.get({i, j}).r * 255); - converted.get({i, j}).g = uint1(output.get({i, j}).g * 255); - converted.get({i, j}).b = uint1(output.get({i, j}).b * 255); - converted.get({i, j}).a = uint1(output.get({i, j}).a * 255); - } - } + for (RayTracer::RenderBuffer::Index i = 0; i < output.size().x; i++) { + for (RayTracer::RenderBuffer::Index j = 0; j < output.size().y; j++) { + converted.get({ i, j }).r = uint1(output.get({ i, j }).r * 255); + converted.get({ i, j }).g = uint1(output.get({ i, j }).g * 255); + converted.get({ i, j }).b = uint1(output.get({ i, j }).b * 255); + converted.get({ i, j }).a = uint1(output.get({ i, j }).a * 255); + } + } - if (stbi_write_png(name, converted.size().x, converted.size().y, 4, converted.getBuff(), converted.size().x * 4) != 0) { - // Image saved successfully - printf("Image saved successfully.\n"); - } else { - printf("Error saving the image.\n"); - } + if (stbi_write_png(name, converted.size().x, converted.size().y, 4, converted.getBuff(), converted.size().x * 4) != 0) { + // Image saved successfully + printf("Image saved successfully.\n"); + } else { + printf("Error saving the image.\n"); + } } static void* printStatus(void* arg) { - auto percentage = (const halnf*) arg; - auto old = *percentage; - while (*percentage < 0.99f) { - sleep(500); - if (old != *percentage && (*percentage - old) > 0.01) { - printf("Progress - %f\n", (*percentage) * 100); - old = *percentage; - } - } - pthread_exit(NULL); + auto percentage = (const halnf*) arg; + auto old = *percentage; + while (*percentage < 0.99f) { + sleep(500); + if (old != *percentage && (*percentage - old) > 0.01) { + printf("Progress - %f\n", (*percentage) * 100); + old = *percentage; + } + } + pthread_exit(NULL); } void renderCommand(const String& scenePath) { - Scene scene; + Scene scene; - RayTracer::RenderSettings settings; + RayTracer::RenderSettings settings; - loadScene(scene, scenePath, settings); + loadScene(scene, scenePath, settings); - RayTracer::OutputBuffers output; - RayTracer rayt; + RayTracer::OutputBuffers output; + RayTracer rayt; - pthread_t my_thread; - int ret; + pthread_t my_thread; + int ret; - printf("\nStarting Render:\n\n"); + printf("\nStarting Render:\n\n"); - ret = pthread_create(&my_thread, NULL, &printStatus, &rayt.mProgress.percentage); - if (ret != 0) { - printf("Error: pthread_create() failed\n"); - exit(EXIT_FAILURE); - } + ret = pthread_create(&my_thread, NULL, &printStatus, &rayt.mProgress.percentage); + if (ret != 0) { + printf("Error: pthread_create() failed\n"); + exit(EXIT_FAILURE); + } - auto start = get_time(); + auto start = get_time(); - rayt.render(scene, output, settings); + rayt.render(scene, output, settings); - auto end = get_time(); + auto end = get_time(); - pthread_join(my_thread, NULL); + pthread_join(my_thread, NULL); - printf("\nRender finished with average render time per sample - %i (ms)\n", end - start); + printf("\nRender finished with average render time per sample - %i (ms)\n", end - start); - writeImage(output.normals, "normals.png"); - writeImage(output.color, "color.png"); - writeImage(output.depth, "depth.png"); + writeImage(output.normals, "normals.png"); + writeImage(output.color, "color.png"); + writeImage(output.depth, "depth.png"); } int main(int argc, const char** argv) { - tp::ModuleManifest* deps[] = {&gModuleRayTracer, nullptr}; - tp::ModuleManifest module("Rayt", nullptr, nullptr, deps); + tp::ModuleManifest* deps[] = { &gModuleRayTracer, nullptr }; + tp::ModuleManifest module("Rayt", nullptr, nullptr, deps); - if (module.initialize()) { - renderCommand("scene.lua"); + if (module.initialize()) { + renderCommand("scene.lua"); - module.deinitialize(); - } + module.deinitialize(); + } - return 0; + return 0; } diff --git a/RayTracer/applications/SceneLoad.cpp b/RayTracer/applications/SceneLoad.cpp index 18e7918..6b31e6d 100644 --- a/RayTracer/applications/SceneLoad.cpp +++ b/RayTracer/applications/SceneLoad.cpp @@ -9,238 +9,238 @@ extern "C" { #include "OBJ_Loader.h" bool loadMeshes(tp::Scene& scene, const tp::String& objetsPath) { - using namespace tp; + using namespace tp; - objl::Loader Loader; + objl::Loader Loader; - if (!Loader.LoadFile(objetsPath.read())) { - std::cout << "Failed to Load File. May have failed to find it or it was not an .obj file.\n"; - return false; - } + if (!Loader.LoadFile(objetsPath.read())) { + std::cout << "Failed to Load File. May have failed to find it or it was not an .obj file.\n"; + return false; + } - for (auto& curMesh : Loader.LoadedMeshes) { - scene.mObjects.append(Object()); + for (auto& curMesh : Loader.LoadedMeshes) { + scene.mObjects.append(Object()); - auto object = &scene.mObjects.last(); + auto object = &scene.mObjects.last(); - for (auto& vertex : curMesh.Vertices) { - // printf("{ %f, %f, %f }, \n", vertex.Position.X, vertex.Position.Y, vertex.Position.Z); - object->mTopology.Points.append(Vec3F {vertex.Position.X, vertex.Position.Y, vertex.Position.Z}); - object->mTopology.Normals.append(Vec3F {vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z}); - } + for (auto& vertex : curMesh.Vertices) { + // printf("{ %f, %f, %f }, \n", vertex.Position.X, vertex.Position.Y, vertex.Position.Z); + object->mTopology.Points.append(Vec3F{ vertex.Position.X, vertex.Position.Y, vertex.Position.Z }); + object->mTopology.Normals.append(Vec3F{ vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z }); + } - for (int j = 0; j < curMesh.Indices.size(); j += 3) { - int idx1 = (int) curMesh.Indices[j]; - int idx2 = (int) curMesh.Indices[j + 1]; - int idx3 = (int) curMesh.Indices[j + 2]; - // printf("{ %i, %i, %i },\n", idx1, idx2, idx3); - object->mTopology.Indexes.append(Vec3I {idx1, idx2, idx3}); - } + for (int j = 0; j < curMesh.Indices.size(); j += 3) { + int idx1 = (int) curMesh.Indices[j]; + int idx2 = (int) curMesh.Indices[j + 1]; + int idx3 = (int) curMesh.Indices[j + 2]; + // printf("{ %i, %i, %i },\n", idx1, idx2, idx3); + object->mTopology.Indexes.append(Vec3I{ idx1, idx2, idx3 }); + } - if (object->mTopology.Normals.size() != object->mTopology.Points.size()) { - printf("Logic error loading normals\n"); - } + if (object->mTopology.Normals.size() != object->mTopology.Points.size()) { + printf("Logic error loading normals\n"); + } - object->mCache.Source = &object->mTopology; - object->mCache.updateCache(); - } + object->mCache.Source = &object->mTopology; + object->mCache.updateCache(); + } - return scene.mObjects.size(); + return scene.mObjects.size(); } // Function to read a Lua table representing RenderSettings int readRenderSettings(lua_State* L, tp::RayTracer::RenderSettings& settings) { - lua_getglobal(L, "RenderSettings"); - if (!lua_istable(L, -1)) { - printf("RenderSettings is not a table.\n"); - return 0; // Error - } + lua_getglobal(L, "RenderSettings"); + if (!lua_istable(L, -1)) { + printf("RenderSettings is not a table.\n"); + return 0; // Error + } - // Read depth field - lua_getfield(L, -1, "depth"); - if (lua_isnumber(L, -1)) { - settings.depth = (int) lua_tonumber(L, -1); - } else { - printf("RenderSettings 'depth' field is missing or not a number.\n"); - lua_pop(L, 1); // Pop the 'depth' field - return 0; // Error - } - lua_pop(L, 1); // Pop the 'depth' field + // Read depth field + lua_getfield(L, -1, "depth"); + if (lua_isnumber(L, -1)) { + settings.depth = (int) lua_tonumber(L, -1); + } else { + printf("RenderSettings 'depth' field is missing or not a number.\n"); + lua_pop(L, 1); // Pop the 'depth' field + return 0; // Error + } + lua_pop(L, 1); // Pop the 'depth' field - // Read spray field - lua_getfield(L, -1, "spray"); - if (lua_isnumber(L, -1)) { - settings.spray = (int) lua_tonumber(L, -1); - } else { - printf("RenderSettings 'spray' field is missing or not a number.\n"); - lua_pop(L, 1); // Pop the 'spray' field - return 0; // Error - } - lua_pop(L, 1); // Pop the 'spray' field + // Read spray field + lua_getfield(L, -1, "spray"); + if (lua_isnumber(L, -1)) { + settings.spray = (int) lua_tonumber(L, -1); + } else { + printf("RenderSettings 'spray' field is missing or not a number.\n"); + lua_pop(L, 1); // Pop the 'spray' field + return 0; // Error + } + lua_pop(L, 1); // Pop the 'spray' field - // Read depth field - lua_getfield(L, -1, "multisampling"); - if (lua_isnumber(L, -1)) { - settings.multisampling = (int) lua_tonumber(L, -1); - } else { - printf("RenderSettings 'depth' field is missing or not a number.\n"); - lua_pop(L, 1); // Pop the 'depth' field - return 0; // Error - } - lua_pop(L, 1); // Pop the 'depth' field + // Read depth field + lua_getfield(L, -1, "multisampling"); + if (lua_isnumber(L, -1)) { + settings.multisampling = (int) lua_tonumber(L, -1); + } else { + printf("RenderSettings 'depth' field is missing or not a number.\n"); + lua_pop(L, 1); // Pop the 'depth' field + return 0; // Error + } + lua_pop(L, 1); // Pop the 'depth' field - return 1; // Success + return 1; // Success } // Function to read a Lua table representing a light int readLight(lua_State* L, tp::PointLight* light) { - lua_getfield(L, -1, "pos"); // Get the "pos" field from the light table - if (!lua_istable(L, -1)) { - printf("Light is missing the 'pos' table.\n"); - return 0; // Error - } - for (int i = 0; i < 3; i++) { - lua_rawgeti(L, -1, i + 1); // Index is 1-based in Lua - if (!lua_isnumber(L, -1)) { - printf("Light 'pos' field is not a number at index %d.\n", i); - lua_pop(L, 2); // Pop both the number and the 'pos' table - return 0; // Error - } - light->pos[i] = lua_tonumber(L, -1); - lua_pop(L, 1); // Pop the number - } - lua_pop(L, 1); // Pop the 'pos' table + lua_getfield(L, -1, "pos"); // Get the "pos" field from the light table + if (!lua_istable(L, -1)) { + printf("Light is missing the 'pos' table.\n"); + return 0; // Error + } + for (int i = 0; i < 3; i++) { + lua_rawgeti(L, -1, i + 1); // Index is 1-based in Lua + if (!lua_isnumber(L, -1)) { + printf("Light 'pos' field is not a number at index %d.\n", i); + lua_pop(L, 2); // Pop both the number and the 'pos' table + return 0; // Error + } + light->pos[i] = lua_tonumber(L, -1); + lua_pop(L, 1); // Pop the number + } + lua_pop(L, 1); // Pop the 'pos' table - lua_getfield(L, -1, "intensity"); // Get the "intensity" field from the light table - if (!lua_isnumber(L, -1)) { - printf("Light is missing the 'intensity' field or it's not a number.\n"); - lua_pop(L, 1); // Pop the 'intensity' field - return 0; // Error - } - light->intensity = lua_tonumber(L, -1); - lua_pop(L, 1); // Pop the 'intensity' field + lua_getfield(L, -1, "intensity"); // Get the "intensity" field from the light table + if (!lua_isnumber(L, -1)) { + printf("Light is missing the 'intensity' field or it's not a number.\n"); + lua_pop(L, 1); // Pop the 'intensity' field + return 0; // Error + } + light->intensity = lua_tonumber(L, -1); + lua_pop(L, 1); // Pop the 'intensity' field - return 1; // Success + return 1; // Success } void loadScene(tp::Scene& scene, const tp::String& scenePath, tp::RayTracer::RenderSettings& settings) { - lua_State* L = luaL_newstate(); - luaL_openlibs(L); + lua_State* L = luaL_newstate(); + luaL_openlibs(L); - if (luaL_dofile(L, "script.lua") != 0) { - lua_close(L); - printf("Cant open scene script.\n"); - return; - } + if (luaL_dofile(L, "script.lua") != 0) { + lua_close(L); + printf("Cant open scene script.\n"); + return; + } - lua_getglobal(L, "Meshes"); + lua_getglobal(L, "Meshes"); - if (lua_isstring(L, -1)) { - tp::String meshesPath = lua_tostring(L, -1); + if (lua_isstring(L, -1)) { + tp::String meshesPath = lua_tostring(L, -1); - if (!loadMeshes(scene, meshesPath)) { - printf("No 'meshes' loaded - check ur .obj path and validate content of .obj .\n"); - return; - } + if (!loadMeshes(scene, meshesPath)) { + printf("No 'meshes' loaded - check ur .obj path and validate content of .obj .\n"); + return; + } - } else { - printf("No 'meshes' path given.\n"); - return; - } + } else { + printf("No 'meshes' path given.\n"); + return; + } - // --- camera + // --- camera - // Access Camera table - lua_getglobal(L, "Camera"); - if (!lua_istable(L, -1)) { - printf("Camera is not a table.\n"); - lua_close(L); - return; - } + // Access Camera table + lua_getglobal(L, "Camera"); + if (!lua_istable(L, -1)) { + printf("Camera is not a table.\n"); + lua_close(L); + return; + } - // Verify you are inside the "Camera" table - int cameraTableIndex = lua_gettop(L); // Get the index of the "Camera" table + // Verify you are inside the "Camera" table + int cameraTableIndex = lua_gettop(L); // Get the index of the "Camera" table - // Access the "pos" field and validate it - lua_getfield(L, cameraTableIndex, "pos"); - if (!lua_istable(L, -1) || lua_rawlen(L, -1) != 3) { - printf("Invalid 'pos' field in Camera table.\n"); - lua_close(L); - return; - } + // Access the "pos" field and validate it + lua_getfield(L, cameraTableIndex, "pos"); + if (!lua_istable(L, -1) || lua_rawlen(L, -1) != 3) { + printf("Invalid 'pos' field in Camera table.\n"); + lua_close(L); + return; + } - // Read the values from the table - float pos[3]; - for (int i = 0; i < 3; i++) { - lua_rawgeti(L, -1, i + 1); - if (lua_isnumber(L, -1)) { - pos[i] = lua_tonumber(L, -1); - } else { - printf("Invalid 'pos' field value at index %d.\n", i + 1); - lua_close(L); - return; - } - lua_pop(L, 1); - } + // Read the values from the table + float pos[3]; + for (int i = 0; i < 3; i++) { + lua_rawgeti(L, -1, i + 1); + if (lua_isnumber(L, -1)) { + pos[i] = lua_tonumber(L, -1); + } else { + printf("Invalid 'pos' field value at index %d.\n", i + 1); + lua_close(L); + return; + } + lua_pop(L, 1); + } - // Access the "size_x" field and validate it - lua_getfield(L, cameraTableIndex, "size_x"); - if (!lua_isnumber(L, -1)) { - printf("Invalid or missing 'size_x' field in Camera table.\n"); - lua_close(L); - return; - } - int size_x = lua_tointeger(L, -1); - lua_pop(L, 1); // Pop the 'size_x' value from the stack + // Access the "size_x" field and validate it + lua_getfield(L, cameraTableIndex, "size_x"); + if (!lua_isnumber(L, -1)) { + printf("Invalid or missing 'size_x' field in Camera table.\n"); + lua_close(L); + return; + } + int size_x = lua_tointeger(L, -1); + lua_pop(L, 1); // Pop the 'size_x' value from the stack - // Access the "size_y" field and validate it - lua_getfield(L, cameraTableIndex, "size_y"); - if (!lua_isnumber(L, -1)) { - printf("Invalid or missing 'size_y' field in Camera table.\n"); - lua_close(L); - return; - } - int size_y = lua_tointeger(L, -1); + // Access the "size_y" field and validate it + lua_getfield(L, cameraTableIndex, "size_y"); + if (!lua_isnumber(L, -1)) { + printf("Invalid or missing 'size_y' field in Camera table.\n"); + lua_close(L); + return; + } + int size_y = lua_tointeger(L, -1); - settings.size = {(tp::halnf) size_x, (tp::halnf) size_y}; + settings.size = { (tp::halnf) size_x, (tp::halnf) size_y }; - scene.mCamera.lookAtPoint({0, 0, 0}, {pos[0], pos[1], pos[2]}, {0, 0, 1}); - scene.mCamera.setFOV(3.14 / 4); - scene.mCamera.setFar(100); - scene.mCamera.setRatio((tp::halnf) size_y / (tp::halnf) size_x); + scene.mCamera.lookAtPoint({ 0, 0, 0 }, { pos[0], pos[1], pos[2] }, { 0, 0, 1 }); + scene.mCamera.setFOV(3.14 / 4); + scene.mCamera.setFar(100); + scene.mCamera.setRatio((tp::halnf) size_y / (tp::halnf) size_x); - // ---------- LIGHTS - { - lua_getglobal(L, "Lights"); - if (!lua_istable(L, -1)) { - printf("Lights is not a table.\n"); - lua_close(L); - return; // Error - } + // ---------- LIGHTS + { + lua_getglobal(L, "Lights"); + if (!lua_istable(L, -1)) { + printf("Lights is not a table.\n"); + lua_close(L); + return; // Error + } - // Read and process each light in the "Lights" table - int numLights = lua_rawlen(L, -1); // Get the number of lights in the table - for (int i = 1; i <= numLights; i++) { - lua_rawgeti(L, -1, i); // Get the i-th element (light) from the table - if (lua_istable(L, -1)) { - tp::PointLight light; - if (!readLight(L, &light)) { - printf("Cant read lights data\n"); - lua_close(L); - return; // Error - } - scene.mLights.append(light); - } - lua_pop(L, 1); // Pop the i-th light table - } - } + // Read and process each light in the "Lights" table + int numLights = lua_rawlen(L, -1); // Get the number of lights in the table + for (int i = 1; i <= numLights; i++) { + lua_rawgeti(L, -1, i); // Get the i-th element (light) from the table + if (lua_istable(L, -1)) { + tp::PointLight light; + if (!readLight(L, &light)) { + printf("Cant read lights data\n"); + lua_close(L); + return; // Error + } + scene.mLights.append(light); + } + lua_pop(L, 1); // Pop the i-th light table + } + } - // ----------- settings -------------- - if (!readRenderSettings(L, settings)) { - printf("Cant Read Render Settings"); - lua_close(L); - return; // Error - } + // ----------- settings -------------- + if (!readRenderSettings(L, settings)) { + printf("Cant Read Render Settings"); + lua_close(L); + return; // Error + } - lua_close(L); + lua_close(L); } diff --git a/RayTracer/private/RayTracer.cpp b/RayTracer/private/RayTracer.cpp index 0964dcf..f1a4a40 100644 --- a/RayTracer/private/RayTracer.cpp +++ b/RayTracer/private/RayTracer.cpp @@ -44,198 +44,195 @@ normal = n1 * barycentric.x + n2 * barycentric.y + n3 * barycentric.z; using namespace tp; -ModuleManifest* sDependencies[] = {&gModuleMath, &gModuleCommandLine, &gModuleConnection, nullptr}; +ModuleManifest* sDependencies[] = { &gModuleMath, &gModuleCommandLine, &gModuleConnection, nullptr }; ModuleManifest tp::gModuleRayTracer = ModuleManifest("RayTracer", nullptr, nullptr, sDependencies); void RayTracer::castRay(const Ray& ray, RayCastData& out, alnf far) { - out.hit = false; + out.hit = false; - far *= far; + far *= far; - for (auto obj : mScene->mObjects) { - for (auto trig : obj->mCache.TrigCaches) { - if (trig->castRay(ray)) { - // printf("Hit\n"); + for (auto obj : mScene->mObjects) { + for (auto trig : obj->mCache.TrigCaches) { + if (trig->castRay(ray)) { + // printf("Hit\n"); - auto dist = (trig->getHitPos() - ray.pos).length2(); + auto dist = (trig->getHitPos() - ray.pos).length2(); - if (far > dist && dist > EPSILON) { - out.trig = &trig.data(); - out.hitPos = trig->getHitPos(); - out.obj = &obj.data(); - out.hit = true; + if (far > dist && dist > EPSILON) { + out.trig = &trig.data(); + out.hitPos = trig->getHitPos(); + out.obj = &obj.data(); + out.hit = true; - far = dist; - } - } - } - } + far = dist; + } + } + } + } } void RayTracer::cycle(const RayCastData& castData, LightData& out, uhalni depth) { - if (depth) { - depth--; + if (depth) { + depth--; - Vec3F normal = castData.trig->getNormal(); - normal.normalize(); + Vec3F normal = castData.trig->getNormal(); + normal.normalize(); - const auto delta1 = castData.trig->mEdgeP1P2.unitV(); - const auto delta2 = normal.cross(delta1); + const auto delta1 = castData.trig->mEdgeP1P2.unitV(); + const auto delta2 = normal.cross(delta1); - for (auto idx : Range(mSettings.spray)) { - RayCastData materialCastData; - LightData lightData; + for (auto idx : Range(mSettings.spray)) { + RayCastData materialCastData; + LightData lightData; - auto d1 = ((halnf) randomFloat() - 0.5f) * 2; - auto d2 = ((halnf) randomFloat() - 0.5f) * 2; + auto d1 = ((halnf) randomFloat() - 0.5f) * 2; + auto d2 = ((halnf) randomFloat() - 0.5f) * 2; - auto sprayNormal = (normal + delta1 * d1 + delta2 * d2).normalize(); + auto sprayNormal = (normal + delta1 * d1 + delta2 * d2).normalize(); - castRay({sprayNormal, castData.hitPos}, materialCastData, mScene->mCamera.getFar()); - if (materialCastData.hit) { - cycle(materialCastData, lightData, depth); - out.intensity += lightData.intensity * 0.2; - } - } - } + castRay({ sprayNormal, castData.hitPos }, materialCastData, mScene->mCamera.getFar()); + if (materialCastData.hit) { + cycle(materialCastData, lightData, depth); + out.intensity += lightData.intensity * 0.2; + } + } + } - // cast for light - for (auto light : mScene->mLights) { - RayCastData lightCastData; - auto dir = light->pos - castData.hitPos; - auto length = (halnf) dir.length(); + // cast for light + for (auto light : mScene->mLights) { + RayCastData lightCastData; + auto dir = light->pos - castData.hitPos; + auto length = (halnf) dir.length(); - Ray lightRay = {dir.unitV(), castData.hitPos}; + Ray lightRay = { dir.unitV(), castData.hitPos }; - if (lightRay.dir.dot(castData.trig->mNormal) < 0) { - continue; - } - castRay(lightRay, lightCastData, length); + if (lightRay.dir.dot(castData.trig->mNormal) < 0) { + continue; + } + castRay(lightRay, lightCastData, length); - if (lightCastData.hit) { - continue; - } + if (lightCastData.hit) { + continue; + } - out.intensity += light->intensity / (length * length); - } + out.intensity += light->intensity / (length * length); + } } void RayTracer::render(const Scene& scene, OutputBuffers& out, const RenderSettings& settings) { - out.color.reserve({settings.size.x, settings.size.y}); - out.normals.reserve({settings.size.x, settings.size.y}); - out.depth.reserve({settings.size.x, settings.size.y}); + out.color.reserve({ settings.size.x, settings.size.y }); + out.normals.reserve({ settings.size.x, settings.size.y }); + out.depth.reserve({ settings.size.x, settings.size.y }); - mScene = &scene; - mSettings = settings; + mScene = &scene; + mSettings = settings; - auto pos = mScene->mCamera.getPos(); - auto fov = mScene->mCamera.getFOV(); - auto height = sqrt(mScene->mCamera.getRatio()); - auto width = 1.f / height; - auto forward = mScene->mCamera.getForward(); - auto up = mScene->mCamera.getUp(); - auto right = forward.cross(up); - auto planeCenter = pos + (forward * halnf(width / (2.f * tan(fov / 2.f)))); - auto planeCenterOffset = (up * (halnf) height / 2.f) - (right * (halnf) width / 2.f); + auto pos = mScene->mCamera.getPos(); + auto fov = mScene->mCamera.getFOV(); + auto height = sqrt(mScene->mCamera.getRatio()); + auto width = 1.f / height; + auto forward = mScene->mCamera.getForward(); + auto up = mScene->mCamera.getUp(); + auto right = forward.cross(up); + auto planeCenter = pos + (forward * halnf(width / (2.f * tan(fov / 2.f)))); + auto planeCenterOffset = (up * (halnf) height / 2.f) - (right * (halnf) width / 2.f); - auto planeLeftTop = planeCenter + planeCenterOffset; + auto planeLeftTop = planeCenter + planeCenterOffset; - RayCastData castData; + RayCastData castData; - Ray ray = { - {0, 0, 0}, - pos - }; + Ray ray = { { 0, 0, 0 }, pos }; - Vec3F iterPoint = {0, 0, 0}; - Vec3F deltaX = right * halnf(width / (alnf) mSettings.size.x); - Vec3F deltaY = up * halnf(-height / (alnf) mSettings.size.y); + Vec3F iterPoint = { 0, 0, 0 }; + Vec3F deltaX = right * halnf(width / (alnf) mSettings.size.x); + Vec3F deltaY = up * halnf(-height / (alnf) mSettings.size.y); - ualni maxIterations = mSettings.size.x * mSettings.size.y; - ualni currIter = 0; + ualni maxIterations = mSettings.size.x * mSettings.size.y; + ualni currIter = 0; - halnf maxDepth = 0; - halnf minDepth = mScene->mCamera.getFar() * mSettings.multisampling; + halnf maxDepth = 0; + halnf minDepth = mScene->mCamera.getFar() * mSettings.multisampling; - auto accumulateColor = [](RGBA& col, const RGBA& in) { - col.r += in.r; - col.g += in.g; - col.b += in.b; - col.a = 1; - }; + auto accumulateColor = [](RGBA& col, const RGBA& in) { + col.r += in.r; + col.g += in.g; + col.b += in.b; + col.a = 1; + }; - auto divideColor = [](RGBA& col, const halnf num) { - col.r /= num; - col.g /= num; - col.b /= num; - }; + auto divideColor = [](RGBA& col, const halnf num) { + col.r /= num; + col.g /= num; + col.b /= num; + }; - for (auto i = 0; i < mSettings.size.x; i++) { - for (auto j = 0; j < mSettings.size.y; j++) { - for (auto sample = 0; sample < mSettings.multisampling; sample++) { - auto randX = randomFloat(); - auto randY = randomFloat(); + for (auto i = 0; i < mSettings.size.x; i++) { + for (auto j = 0; j < mSettings.size.y; j++) { + for (auto sample = 0; sample < mSettings.multisampling; sample++) { + auto randX = randomFloat(); + auto randY = randomFloat(); - iterPoint = planeLeftTop + ((deltaX * (halnf) (i + randX)) + (deltaY * (halnf) (j + randY))); - ray.dir = (iterPoint - pos).unitV(); + iterPoint = planeLeftTop + ((deltaX * (halnf) (i + randX)) + (deltaY * (halnf) (j + randY))); + ray.dir = (iterPoint - pos).unitV(); - castRay(ray, castData, mScene->mCamera.getFar()); + castRay(ray, castData, mScene->mCamera.getFar()); - if (castData.hit) { - LightData lightData; - cycle(castData, lightData, mSettings.depth); + if (castData.hit) { + LightData lightData; + cycle(castData, lightData, mSettings.depth); - const auto normal = castData.trig->getNormal(); - const auto depth = (halnf) (castData.hitPos - ray.pos).length(); + const auto normal = castData.trig->getNormal(); + const auto depth = (halnf) (castData.hitPos - ray.pos).length(); - lightData.intensity = clamp(lightData.intensity, 0.f, 1.f); - RGBA col = {lightData.intensity, lightData.intensity, lightData.intensity, 1.f}; + lightData.intensity = clamp(lightData.intensity, 0.f, 1.f); + RGBA col = { lightData.intensity, lightData.intensity, lightData.intensity, 1.f }; - accumulateColor(out.color.get({i, j}), col); - accumulateColor(out.normals.get({i, j}), {normal.x * 0.5f + 0.5f, normal.y * 0.5f + 0.5f, normal.z * 0.5f + 0.5f, 1.f}); - accumulateColor(out.depth.get({i, j}), {depth, depth, depth, 1.f}); + accumulateColor(out.color.get({ i, j }), col); + accumulateColor(out.normals.get({ i, j }), { normal.x * 0.5f + 0.5f, normal.y * 0.5f + 0.5f, normal.z * 0.5f + 0.5f, 1.f }); + accumulateColor(out.depth.get({ i, j }), { depth, depth, depth, 1.f }); - } else { - out.color.set({i, j}, 0.f); - out.normals.set({i, j}, 0.f); - out.depth.set({i, j}, 0.f); - } + } else { + out.color.set({ i, j }, 0.f); + out.normals.set({ i, j }, 0.f); + out.depth.set({ i, j }, 0.f); + } - // auto tmp = buff.get({i, j}); - // printf(" %f, %f, %f, %f, ", tmp.r, tmp.g, tmp.b, tmp.a); - } + // auto tmp = buff.get({i, j}); + // printf(" %f, %f, %f, %f, ", tmp.r, tmp.g, tmp.b, tmp.a); + } - mProgress.percentage = (halnf) currIter / (halnf) maxIterations; - currIter++; - } - } + mProgress.percentage = (halnf) currIter / (halnf) maxIterations; + currIter++; + } + } - for (auto i = 0; i < mSettings.size.x * mSettings.size.y; i++) { - divideColor(out.color.getBuff()[i], (halnf) mSettings.multisampling); - divideColor(out.normals.getBuff()[i], (halnf) mSettings.multisampling); - divideColor(out.depth.getBuff()[i], (halnf) mSettings.multisampling); - } + for (auto i = 0; i < mSettings.size.x * mSettings.size.y; i++) { + divideColor(out.color.getBuff()[i], (halnf) mSettings.multisampling); + divideColor(out.normals.getBuff()[i], (halnf) mSettings.multisampling); + divideColor(out.depth.getBuff()[i], (halnf) mSettings.multisampling); + } - for (auto i = 0; i < mSettings.size.x * mSettings.size.y; i++) { - if (!out.depth.getBuff()[i].a) { - continue; - } - const auto depth = out.depth.getBuff()[i].r; - if (maxDepth < depth) { - maxDepth = depth; - } - if (minDepth > depth) { - minDepth = depth; - } - } + for (auto i = 0; i < mSettings.size.x * mSettings.size.y; i++) { + if (!out.depth.getBuff()[i].a) { + continue; + } + const auto depth = out.depth.getBuff()[i].r; + if (maxDepth < depth) { + maxDepth = depth; + } + if (minDepth > depth) { + minDepth = depth; + } + } - for (auto i = 0; i < mSettings.size.x * mSettings.size.y; i++) { - auto& col = out.depth.getBuff()[i]; - if (col.a == 1.f) { - col.r = (col.r - minDepth) / (maxDepth - minDepth); - col.g = col.r; - col.b = col.r; - } - } + for (auto i = 0; i < mSettings.size.x * mSettings.size.y; i++) { + auto& col = out.depth.getBuff()[i]; + if (col.a == 1.f) { + col.r = (col.r - minDepth) / (maxDepth - minDepth); + col.g = col.r; + col.b = col.r; + } + } } diff --git a/RayTracer/public/RayTracer.hpp b/RayTracer/public/RayTracer.hpp index 3af6e81..555fa9e 100644 --- a/RayTracer/public/RayTracer.hpp +++ b/RayTracer/public/RayTracer.hpp @@ -10,77 +10,77 @@ namespace tp { - extern ModuleManifest gModuleRayTracer; + extern ModuleManifest gModuleRayTracer; - class Object { - public: - Object() = default; + class Object { + public: + Object() = default; - public: - Topology mTopology; - TopologyCache mCache; - }; + public: + Topology mTopology; + TopologyCache mCache; + }; - struct PointLight { - Vec3F pos; - halnf fallOut = 1.f; - halnf intensity = 1.f; - }; + struct PointLight { + Vec3F pos; + halnf fallOut = 1.f; + halnf intensity = 1.f; + }; - class Scene { - public: - Scene() = default; + class Scene { + public: + Scene() = default; - public: - Buffer mObjects; - Buffer mLights; - Camera mCamera; - }; + public: + Buffer mObjects; + Buffer mLights; + Camera mCamera; + }; - class RayTracer { - public: - typedef Buffer2D RenderBuffer; + class RayTracer { + public: + typedef Buffer2D RenderBuffer; - struct Progress { - halnf percentage = 0.f; - } mProgress; + struct Progress { + halnf percentage = 0.f; + } mProgress; - struct RenderSettings { - uhalni depth = 2; - uhalni spray = 1; - ualni multisampling = 1; - Vec2I size; - }; + struct RenderSettings { + uhalni depth = 2; + uhalni spray = 1; + ualni multisampling = 1; + Vec2I size; + }; - struct OutputBuffers { - RenderBuffer normals; - RenderBuffer color; - RenderBuffer depth; - // albedo, reflectance ... - }; + struct OutputBuffers { + RenderBuffer normals; + RenderBuffer color; + RenderBuffer depth; + // albedo, reflectance ... + }; - public: - RayTracer() = default; - void render(const Scene& scene, OutputBuffers& out, const RenderSettings& settings); + public: + RayTracer() = default; + void render(const Scene& scene, OutputBuffers& out, const RenderSettings& settings); - private: - struct RayCastData { - const Object* obj = nullptr; - TrigCache* trig = nullptr; - Vec3F hitPos = {0, 0, 0}; - bool hit = false; - }; + private: + struct RayCastData { + const Object* obj = nullptr; + TrigCache* trig = nullptr; + Vec3F hitPos = { 0, 0, 0 }; + bool hit = false; + }; - struct LightData { - halnf intensity = 0; - }; + struct LightData { + halnf intensity = 0; + }; - private: - void castRay(const Ray& ray, RayCastData& out, alnf far); - void cycle(const RayCastData& ray, LightData& out, uhalni depth); + private: + void castRay(const Ray& ray, RayCastData& out, alnf far); + void cycle(const RayCastData& ray, LightData& out, uhalni depth); - private: - RenderSettings mSettings; - const Scene* mScene = nullptr; - }; + private: + RenderSettings mSettings; + const Scene* mScene = nullptr; + }; } diff --git a/RayTracer/tests/Test.cpp b/RayTracer/tests/Test.cpp index ff8521d..2c2ad78 100644 --- a/RayTracer/tests/Test.cpp +++ b/RayTracer/tests/Test.cpp @@ -10,117 +10,114 @@ using namespace tp; void writeImage(const RayTracer::RenderBuffer& output) { - // Save the data to a PNG file - struct urgb { - uint1 r, g, b, a; - }; + // Save the data to a PNG file + struct urgb { + uint1 r, g, b, a; + }; - Buffer2D converted; - converted.reserve(output.size()); + Buffer2D converted; + converted.reserve(output.size()); - for (RayTracer::RenderBuffer::Index i = 0; i < output.size().x; i++) { - for (RayTracer::RenderBuffer::Index j = 0; j < output.size().y; j++) { - converted.get({i, j}).r = uint1(output.get({i, j}).r * 255); - converted.get({i, j}).g = uint1(output.get({i, j}).g * 255); - converted.get({i, j}).b = uint1(output.get({i, j}).b * 255); - converted.get({i, j}).a = uint1(output.get({i, j}).a * 255); - } - } + for (RayTracer::RenderBuffer::Index i = 0; i < output.size().x; i++) { + for (RayTracer::RenderBuffer::Index j = 0; j < output.size().y; j++) { + converted.get({ i, j }).r = uint1(output.get({ i, j }).r * 255); + converted.get({ i, j }).g = uint1(output.get({ i, j }).g * 255); + converted.get({ i, j }).b = uint1(output.get({ i, j }).b * 255); + converted.get({ i, j }).a = uint1(output.get({ i, j }).a * 255); + } + } - stbi_write_png("output.png", converted.size().x, converted.size().y, 4, converted.getBuff(), converted.size().x * 4); + stbi_write_png("output.png", converted.size().x, converted.size().y, 4, converted.getBuff(), converted.size().x * 4); } bool compareCols(const RGBA& l, const RGBA& r) { - auto small = 0.0001f; - if ((l.r - r.r) > small) { - return false; - } - if ((l.g - r.g) > small) { - return false; - } - if ((l.b - r.b) > small) { - return false; - } - if ((l.a - r.a) > small) { - return false; - } - return true; + auto small = 0.0001f; + if ((l.r - r.r) > small) { + return false; + } + if ((l.g - r.g) > small) { + return false; + } + if ((l.b - r.b) > small) { + return false; + } + if ((l.a - r.a) > small) { + return false; + } + return true; } void testRT() { - using namespace tp; + using namespace tp; - Scene scene; + Scene scene; - scene.mCamera.lookAtPoint({0, 0, 0}, {2, 2, 2}, {0, 0, 1}); - scene.mCamera.setFOV(3.14 / 4); + scene.mCamera.lookAtPoint({ 0, 0, 0 }, { 2, 2, 2 }, { 0, 0, 1 }); + scene.mCamera.setFOV(3.14 / 4); - scene.mLights.append({ - {0, 0, 1.1f}, - 1.f, 0.3f - }); + scene.mLights.append({ { 0, 0, 1.1f }, 1.f, 0.3f }); - scene.mObjects.append(Object()); - auto& object = scene.mObjects.last(); + scene.mObjects.append(Object()); + auto& object = scene.mObjects.last(); - object.mTopology.Points = { - {1.000000, 0.000000, 0.000000}, - {0.000000, 1.000000, 0.000000}, - {0.000000, 0.000000, 1.000000}, - }; + object.mTopology.Points = { + { 1.000000, 0.000000, 0.000000 }, + { 0.000000, 1.000000, 0.000000 }, + { 0.000000, 0.000000, 1.000000 }, + }; - object.mTopology.Normals = { - {1.000000, 1.000000, 1.000000}, - {1.000000, 1.000000, 1.000000}, - {1.000000, 1.000000, 1.000000}, - }; + object.mTopology.Normals = { + { 1.000000, 1.000000, 1.000000 }, + { 1.000000, 1.000000, 1.000000 }, + { 1.000000, 1.000000, 1.000000 }, + }; - object.mTopology.Indexes = { - {0, 1, 2}, - }; + object.mTopology.Indexes = { + { 0, 1, 2 }, + }; - object.mCache.Source = &object.mTopology; - object.mCache.updateCache(); + object.mCache.Source = &object.mTopology; + object.mCache.updateCache(); - RayTracer::RenderSettings settings = { - 0, - 0, - 1, - {10, 10}, - }; + RayTracer::RenderSettings settings = { + 0, + 0, + 1, + { 10, 10 }, + }; - RayTracer::OutputBuffers output; - // output.reserve(RayTracer::RenderBuffer::Index2D(settings.size.x, settings.size.y)); + RayTracer::OutputBuffers output; + // output.reserve(RayTracer::RenderBuffer::Index2D(settings.size.x, settings.size.y)); - RayTracer rt; - rt.render(scene, output, settings); + RayTracer rt; + rt.render(scene, output, settings); - TEST(compareCols(output.color.get({6, 4}), RGBA {0.560100f, 0.560100f, 0.560100f, 1.000000f})); - TEST(compareCols(output.color.get({6, 5}), RGBA {0.353739f, 0.353739f, 0.353739f, 1.000000f})); - TEST(compareCols(output.color.get({6, 6}), RGBA {0.242577f, 0.242577f, 0.242577f, 1.000000f})); - TEST(compareCols(output.color.get({6, 7}), RGBA {0.176313f, 0.176313f, 0.176313f, 1.000000f})); - TEST(compareCols(output.color.get({6, 8}), RGBA {0.000000f, 0.000000f, 0.000000f, 0.000000f})); + TEST(compareCols(output.color.get({ 6, 4 }), RGBA{ 0.560100f, 0.560100f, 0.560100f, 1.000000f })); + TEST(compareCols(output.color.get({ 6, 5 }), RGBA{ 0.353739f, 0.353739f, 0.353739f, 1.000000f })); + TEST(compareCols(output.color.get({ 6, 6 }), RGBA{ 0.242577f, 0.242577f, 0.242577f, 1.000000f })); + TEST(compareCols(output.color.get({ 6, 7 }), RGBA{ 0.176313f, 0.176313f, 0.176313f, 1.000000f })); + TEST(compareCols(output.color.get({ 6, 8 }), RGBA{ 0.000000f, 0.000000f, 0.000000f, 0.000000f })); - if (0) { - writeImage(output.color); - for (auto i = 0; i < output.color.size().x; i++) { - for (auto j = 0; j < output.color.size().y; j++) { - auto tmp = output.color.get({i, j}); - printf("TEST(compareCols(output.get({%i, %i}), RGBA{ %ff, %ff, %ff, %ff }));\n", i, j, tmp.r, tmp.g, tmp.b, tmp.a); - } - } - } + if (0) { + writeImage(output.color); + for (auto i = 0; i < output.color.size().x; i++) { + for (auto j = 0; j < output.color.size().y; j++) { + auto tmp = output.color.get({ i, j }); + printf("TEST(compareCols(output.get({%i, %i}), RGBA{ %ff, %ff, %ff, %ff }));\n", i, j, tmp.r, tmp.g, tmp.b, tmp.a); + } + } + } } int main(int argc, char* argv[]) { - tp::ModuleManifest* ModuleDependencies[] = {&tp::gModuleRayTracer, nullptr}; - tp::ModuleManifest TestModule("TokenizerTest", nullptr, nullptr, ModuleDependencies); + tp::ModuleManifest* ModuleDependencies[] = { &tp::gModuleRayTracer, nullptr }; + tp::ModuleManifest TestModule("TokenizerTest", nullptr, nullptr, ModuleDependencies); - if (!TestModule.initialize()) { - return 1; - } + if (!TestModule.initialize()) { + return 1; + } - testRT(); + testRT(); - TestModule.deinitialize(); + TestModule.deinitialize(); } diff --git a/Strings/private/Logging.cpp b/Strings/private/Logging.cpp index 4ef468d..e77be62 100644 --- a/Strings/private/Logging.cpp +++ b/Strings/private/Logging.cpp @@ -1,59 +1,54 @@ -#include "NewPlacement.hpp" - -#include "Logging.hpp" - -#include - -namespace tp { - - Logger* gLogger = nullptr; - - ualni Logger::Report::getLineCount() const { - return (ualni)(mLineOffsets.size() - 1); - } - - String Logger::Report::getString() const { - return mData; - } - - void Logger::Report::calcLineCount() { - mData.calcLineOffsets(mLineOffsets); - } - - Logger::Report::Report() { - mData = " - "; - } - - Logger::Report::Report(const String& text) : mData(text) { - calcLineCount(); - } - - Logger::Report::Report(const String& text, Type type) : mType(type), mData(text) { - calcLineCount(); - } - - void Logger::write(const String& in, bool post, Report::Type type) { - mBuff.pushBack(Report(in, type)); - mLineCount += mBuff.last()->data.getLineCount(); - if (!mCursor) mCursor = mBuff.last(); - if (post) printf("%s", in.read()); - } - - String Logger::read() { - if (!mCursor) return {}; - const Report& out = mCursor->data; - mCursor = mCursor->next; - return out.getString(); - } - - void Logger::initializeGlobal() { - DEBUG_ASSERT(!gLogger) - gLogger = new Logger(); - } - - void Logger::deinitializeGlobal() { - DEBUG_ASSERT(gLogger) - delete gLogger; - gLogger = nullptr; - } +#include "NewPlacement.hpp" + +#include "Logging.hpp" + +#include + +namespace tp { + + Logger* gLogger = nullptr; + + ualni Logger::Report::getLineCount() const { return (ualni) (mLineOffsets.size() - 1); } + + String Logger::Report::getString() const { return mData; } + + void Logger::Report::calcLineCount() { mData.calcLineOffsets(mLineOffsets); } + + Logger::Report::Report() { mData = " - "; } + + Logger::Report::Report(const String& text) : + mData(text) { + calcLineCount(); + } + + Logger::Report::Report(const String& text, Type type) : + mType(type), + mData(text) { + calcLineCount(); + } + + void Logger::write(const String& in, bool post, Report::Type type) { + mBuff.pushBack(Report(in, type)); + mLineCount += mBuff.last()->data.getLineCount(); + if (!mCursor) mCursor = mBuff.last(); + if (post) printf("%s", in.read()); + } + + String Logger::read() { + if (!mCursor) return {}; + const Report& out = mCursor->data; + mCursor = mCursor->next; + return out.getString(); + } + + void Logger::initializeGlobal() { + DEBUG_ASSERT(!gLogger) + gLogger = new Logger(); + } + + void Logger::deinitializeGlobal() { + DEBUG_ASSERT(gLogger) + delete gLogger; + gLogger = nullptr; + } } \ No newline at end of file diff --git a/Strings/private/Strings.cpp b/Strings/private/Strings.cpp index 2e21690..760d413 100644 --- a/Strings/private/Strings.cpp +++ b/Strings/private/Strings.cpp @@ -1,23 +1,17 @@ - -#include "Strings.hpp" -#include "Allocators.hpp" -#include "Logging.hpp" - -using namespace tp; - -bool initialize(const ModuleManifest*) { - Logger::initializeGlobal(); - return true; -} - -void deinitialize(const ModuleManifest*) { - Logger::deinitializeGlobal(); -} - -static tp::ModuleManifest* sModuleDependencies[] = { - &tp::gModuleContainers, - &tp::gModuleAllocators, - nullptr -}; - + +#include "Strings.hpp" +#include "Allocators.hpp" +#include "Logging.hpp" + +using namespace tp; + +bool initialize(const ModuleManifest*) { + Logger::initializeGlobal(); + return true; +} + +void deinitialize(const ModuleManifest*) { Logger::deinitializeGlobal(); } + +static tp::ModuleManifest* sModuleDependencies[] = { &tp::gModuleContainers, &tp::gModuleAllocators, nullptr }; + ModuleManifest tp::gModuleStrings = ModuleManifest("Strings", initialize, deinitialize, sModuleDependencies); \ No newline at end of file diff --git a/Strings/public/Logging.hpp b/Strings/public/Logging.hpp index dbe9977..8d943ac 100644 --- a/Strings/public/Logging.hpp +++ b/Strings/public/Logging.hpp @@ -1,59 +1,58 @@ - -#pragma once - -#include "Buffer.hpp" -#include "List.hpp" -#include "Strings.hpp" - -namespace tp { - - class Logger { - public: - - class Report { - String mData; - Buffer mLineOffsets; - - public: - enum Type { INFO, ERR, WARN, SUC } mType = INFO; - - public: - Report(); - explicit Report(const String& text); - Report(const String& text, Type type); - - public: - [[nodiscard]] ualni getLineCount() const; - [[nodiscard]] String getString() const; - - private: - void calcLineCount(); - }; - - private: - List::Node* mCursor = nullptr; - List mBuff; - ualni mLineCount = 0; - - public: - void write(const String& in, bool post = true, Report::Type type = Report::Type::INFO); - - [[nodiscard]] String read(); - [[nodiscard]] const List& getBuff() const { return mBuff; } - [[nodiscard]] ualni getLineCount() const { return mLineCount; } - - public: - static void initializeGlobal(); - static void deinitializeGlobal(); - }; - - extern Logger* gLogger; -} - -#define LOG(val) tp::str::gLogger->write((val), 1) - -#ifdef ENV_BUILD_DEBUG -#define DEBUG_LOG(val) tp::str::gLogger->write((val), 1) -#else -#define DEBUG_LOG(val) (0) + +#pragma once + +#include "Buffer.hpp" +#include "List.hpp" +#include "Strings.hpp" + +namespace tp { + + class Logger { + public: + class Report { + String mData; + Buffer mLineOffsets; + + public: + enum Type { INFO, ERR, WARN, SUC } mType = INFO; + + public: + Report(); + explicit Report(const String& text); + Report(const String& text, Type type); + + public: + [[nodiscard]] ualni getLineCount() const; + [[nodiscard]] String getString() const; + + private: + void calcLineCount(); + }; + + private: + List::Node* mCursor = nullptr; + List mBuff; + ualni mLineCount = 0; + + public: + void write(const String& in, bool post = true, Report::Type type = Report::Type::INFO); + + [[nodiscard]] String read(); + [[nodiscard]] const List& getBuff() const { return mBuff; } + [[nodiscard]] ualni getLineCount() const { return mLineCount; } + + public: + static void initializeGlobal(); + static void deinitializeGlobal(); + }; + + extern Logger* gLogger; +} + +#define LOG(val) tp::str::gLogger->write((val), 1) + +#ifdef ENV_BUILD_DEBUG +#define DEBUG_LOG(val) tp::str::gLogger->write((val), 1) +#else +#define DEBUG_LOG(val) (0) #endif \ No newline at end of file diff --git a/Strings/public/StringLogic.hpp b/Strings/public/StringLogic.hpp index b86baa5..8c66eb3 100644 --- a/Strings/public/StringLogic.hpp +++ b/Strings/public/StringLogic.hpp @@ -1,140 +1,138 @@ -#pragma once - -#include "Allocators.hpp" -#include "Buffer.hpp" -#include "Utils.hpp" -#include -#include - -namespace tp { - - template - class StringLogic { - public: - - typedef halni Index; - typedef Index LineId; - typedef Index ColumnId; - - static inline bool isNewLineChar(tChar in) { return (in == '\n') || (in == '\r'); } - static inline bool isEndChar(tChar in) { return in == '\0'; } - static constexpr tChar getEndChar() { return '\0'; } - - static Index calcLength(const tChar* in) { - const tChar* iter = in; - while (*iter != '\0') iter++; - return iter - in; - } - - static void insertLogic(tChar* result, Index resultLen, const tChar* cur, const tChar* tar, Index at, Index len) { - auto curLen = calcLength(cur); - auto allLen = curLen + len; - ASSERT(allLen <= resultLen); - - DEBUG_ASSERT(curLen >= 0) - DEBUG_ASSERT(len >= 0) - DEBUG_ASSERT(at < curLen + 1 && at >= 0) - - for (Index idx = 0; idx < at; idx++) { - result[idx] = cur[idx]; - } - for (Index idx = 0; idx < len; idx++) { - result[idx + at] = tar[idx]; - } - for (Index idx = at + len; idx < allLen; idx++) { - result[idx] = cur[idx - len]; - } - result[allLen] = '\0'; - } - - // including end not including start - static void removeLogic(tChar* result, Index resultLen, const tChar* cur, Index start, Index end) { - auto curLen = calcLength(cur); - auto rangeLen = end - start; - auto newLen = curLen - rangeLen; - - ASSERT(newLen <= resultLen); - - result[newLen] = '\0'; - for (Index idx = 0; idx < start; idx++) { - result[idx] = cur[idx]; - } - for (Index idx = end; idx < curLen; idx++) { - result[idx - rangeLen] = cur[idx]; - } - } - - static bool isEqualLogic(const tChar* left, const tChar* right) { - Index idx = 0; - LOOP: - if (left[idx] == '\0' || right[idx] == '\0') { - if (left[idx] == '\0' && right[idx] == '\0') { - return true; - } - return false; - } - if (left[idx] != right[idx]) { - return false; - } - idx++; - goto LOOP; - } - - // returns 0 : nl1 + 1 : nl2 + 1 : nl3 + 1 : ... : size - static void calcLineOffsets(const tChar* aBuff, Index aLength, Buffer& aOut) { - Index lines = 0; - for (auto idx : Range(aLength)) { - if (isNewLineChar(aBuff[idx])) { - lines++; - } - } - aOut.reserve(lines + 2); // plus start and end offsets - lines = 0; - for (auto idx : Range(aLength)) { - if (isNewLineChar(aBuff[idx])) { - aOut[lines + 1] = Index(idx + 1); - lines++; - } - } - aOut[0] = 0; - aOut[lines + 1] = aLength; - } - - - static bool convertStringToValue(const tChar* input, alni& output) { - char* endPtr; - output = std::strtoll(input, &endPtr, 10); - return (endPtr == input + calcLength(input)); - } - - static bool convertStringToValue(const tChar* input, alnf& output) { - char* endPtr; - output = std::strtod(input, &endPtr); - return (endPtr == input + calcLength(input)); - } - - static bool convertStringToValue(const tChar* input, bool& output) { - output = !(isEqualLogic(input, "False") || isEqualLogic(input, "false") || isEqualLogic(input, "0")); - return true; - } - - static bool convertValueToString(alni input, tChar* output, Index bufferSize) { - int result = std::snprintf(output, bufferSize, "%lld", input); - return result >= 0; - } - - static bool convertValueToString(alnf input, tChar* output, Index bufferSize) { - int result = std::snprintf(output, bufferSize, "%f", input); - return result >= 0; - } - - static bool convertValueToString(bool input, tChar* output, Index bufferSize) { - const char* str = (input ? "true" : "false"); - Index length = calcLength(str); - if (length >= bufferSize) - return false; - memCopy(output, str, length + 1); - return true; - } - }; +#pragma once + +#include "Allocators.hpp" +#include "Buffer.hpp" +#include "Utils.hpp" +#include +#include + +namespace tp { + + template + class StringLogic { + public: + typedef halni Index; + typedef Index LineId; + typedef Index ColumnId; + + static inline bool isNewLineChar(tChar in) { return (in == '\n') || (in == '\r'); } + static inline bool isEndChar(tChar in) { return in == '\0'; } + static constexpr tChar getEndChar() { return '\0'; } + + static Index calcLength(const tChar* in) { + const tChar* iter = in; + while (*iter != '\0') + iter++; + return iter - in; + } + + static void insertLogic(tChar* result, Index resultLen, const tChar* cur, const tChar* tar, Index at, Index len) { + auto curLen = calcLength(cur); + auto allLen = curLen + len; + ASSERT(allLen <= resultLen); + + DEBUG_ASSERT(curLen >= 0) + DEBUG_ASSERT(len >= 0) + DEBUG_ASSERT(at < curLen + 1 && at >= 0) + + for (Index idx = 0; idx < at; idx++) { + result[idx] = cur[idx]; + } + for (Index idx = 0; idx < len; idx++) { + result[idx + at] = tar[idx]; + } + for (Index idx = at + len; idx < allLen; idx++) { + result[idx] = cur[idx - len]; + } + result[allLen] = '\0'; + } + + // including end not including start + static void removeLogic(tChar* result, Index resultLen, const tChar* cur, Index start, Index end) { + auto curLen = calcLength(cur); + auto rangeLen = end - start; + auto newLen = curLen - rangeLen; + + ASSERT(newLen <= resultLen); + + result[newLen] = '\0'; + for (Index idx = 0; idx < start; idx++) { + result[idx] = cur[idx]; + } + for (Index idx = end; idx < curLen; idx++) { + result[idx - rangeLen] = cur[idx]; + } + } + + static bool isEqualLogic(const tChar* left, const tChar* right) { + Index idx = 0; + LOOP: + if (left[idx] == '\0' || right[idx] == '\0') { + if (left[idx] == '\0' && right[idx] == '\0') { + return true; + } + return false; + } + if (left[idx] != right[idx]) { + return false; + } + idx++; + goto LOOP; + } + + // returns 0 : nl1 + 1 : nl2 + 1 : nl3 + 1 : ... : size + static void calcLineOffsets(const tChar* aBuff, Index aLength, Buffer& aOut) { + Index lines = 0; + for (auto idx : Range(aLength)) { + if (isNewLineChar(aBuff[idx])) { + lines++; + } + } + aOut.reserve(lines + 2); // plus start and end offsets + lines = 0; + for (auto idx : Range(aLength)) { + if (isNewLineChar(aBuff[idx])) { + aOut[lines + 1] = Index(idx + 1); + lines++; + } + } + aOut[0] = 0; + aOut[lines + 1] = aLength; + } + + static bool convertStringToValue(const tChar* input, alni& output) { + char* endPtr; + output = std::strtoll(input, &endPtr, 10); + return (endPtr == input + calcLength(input)); + } + + static bool convertStringToValue(const tChar* input, alnf& output) { + char* endPtr; + output = std::strtod(input, &endPtr); + return (endPtr == input + calcLength(input)); + } + + static bool convertStringToValue(const tChar* input, bool& output) { + output = !(isEqualLogic(input, "False") || isEqualLogic(input, "false") || isEqualLogic(input, "0")); + return true; + } + + static bool convertValueToString(alni input, tChar* output, Index bufferSize) { + int result = std::snprintf(output, bufferSize, "%lld", input); + return result >= 0; + } + + static bool convertValueToString(alnf input, tChar* output, Index bufferSize) { + int result = std::snprintf(output, bufferSize, "%f", input); + return result >= 0; + } + + static bool convertValueToString(bool input, tChar* output, Index bufferSize) { + const char* str = (input ? "true" : "false"); + Index length = calcLength(str); + if (length >= bufferSize) return false; + memCopy(output, str, length + 1); + return true; + } + }; } \ No newline at end of file diff --git a/Strings/public/Strings.hpp b/Strings/public/Strings.hpp index 5bdf9f8..3675d92 100644 --- a/Strings/public/Strings.hpp +++ b/Strings/public/Strings.hpp @@ -1,286 +1,273 @@ -#pragma once - -#include "Allocators.hpp" -#include "StringLogic.hpp" - -namespace tp { - - // Static data - extern ModuleManifest gModuleStrings; - - template class StringTemplate; - - // Hidden slave class - template - class StringData { - friend StringTemplate; - typedef StringLogic Logic; - typedef typename StringLogic::Index Index; - - private: - uint2 mIsConst; // source is non-modifiable - uint2 mEditedIdx; // editor id - uint4 mReferenceCount; // number of users of this - tChar* mBuff; // actual string data - - StringData() { - mBuff = (tChar*) "*"; - mReferenceCount = 1; - mIsConst = true; - mEditedIdx = 0; - } - - StringData(const tChar* aBuff, bool aIsConst) { - MODULE_SANITY_CHECK(gModuleStrings) - DEBUG_ASSERT(aBuff) - mBuff = (tChar*) aBuff; - mReferenceCount = 0; - mIsConst = aIsConst; - mEditedIdx = 0; - } - - explicit StringData(tChar* aBuff) { - MODULE_SANITY_CHECK(gModuleStrings) - DEBUG_ASSERT(aBuff) - auto const len = Logic::calcLength(aBuff); - mReferenceCount = 0; - mIsConst = false; - mEditedIdx = 0; - mBuff = new tChar[len + 1]; - mBuff[len] = Logic::getEndChar(); - memCopy(mBuff, aBuff, len); - } - - [[nodiscard]] tChar* getBuffer() { - return mBuff; - } - - ~StringData() { - if (!mIsConst) delete[] mBuff; - } - - void resize(Index size) { - DEBUG_ASSERT(mReferenceCount == 1 && !mIsConst) - delete[] mBuff; - mBuff = new tChar[size + 1]; - mBuff[size] = Logic::getEndChar(); - } - }; - - template - class StringTemplate { - public: - typedef StringLogic Logic; - typedef StringData Data; - typedef typename Logic::Index Index; - - enum { - STRINGS_POOL_SIZE = 1024, - MAX_INT_STRING_LENGTH = 10, - MAX_BOOL_STRING_LENGTH = 10, - MAX_FLOAT_STRING_LENGTH = 10, - }; - static PoolAlloc, STRINGS_POOL_SIZE> sStringPool; - static Data sNullString; - - private: - Data* mData; - - public: // Main Interface - // Creates null string reference - StringTemplate() { - mData = &sNullString; - incReference(mData); - } - - // References existing string data - StringTemplate(const StringTemplate& in) { - mData = in.mData; - incReference(mData); - } - - // Creates new string data from raw data pointer. - // Does not own string buffer - string buffer will not be freed. Initializes as const memory. - StringTemplate(const tChar* raw) { - mData = new (sStringPool.allocate(0)) StringData(raw, true); - incReference(mData); - } - - // Copies raw data and claims ownership over it - StringTemplate(tChar* raw) { - mData = new (sStringPool.allocate(0)) StringData(raw); - incReference(mData); - } - - ~StringTemplate() { - decReference(mData); - } - - private: - static void incReference(Data* dp) { - dp->mReferenceCount++; - } - - void decReference(Data* dp) { - DEBUG_ASSERT(dp->mReferenceCount > 0) - dp->mReferenceCount--; - if (!dp->mReferenceCount) { - mData->~StringData(); - sStringPool.deallocate(mData); - } - } - - public: // Access - // used to read data - [[nodiscard]] const tChar* read() const { - return mData->mBuff; - } - - // used to write data - // output will be null if in TextEditing mode - [[nodiscard]] tChar* write() { - makeModifiable(); - return mData->getBuffer(); - } - - // output will be null if in TextEditing mode - tChar* resize(Index size) { - makeModifiable(); - mData->resize(size); - return write(); - } - - public: - void makeModifiable() { - // We have no rights to modify if someone references that memory too - // So we need to create new copy of StringData - if (mData->mReferenceCount > 1) { - mData = new (sStringPool.allocate(0)) StringData(mData->mBuff); - incReference(mData); - return; - } - - // Also if initial raw data was marked as const - create copy of raw data - // Note - raw data will be lost at this point if no other record of such is stored - if (mData->mIsConst) { - mData = new (sStringPool.allocate(0)) StringData(mData->mBuff); - incReference(mData); - } - } - - template - void archiveWrite(tArchiver& ar) const { - auto size = this->size(); - ar << size; - ar.writeBytes(read(), size); - } - - template - void archiveRead(tArchiver& ar) { - Index size; - ar >> size; - resize(size); - ar.readBytes(write(), size); - } - - public: // Syntax sugars - - explicit StringTemplate(alni val) { - tChar raw[MAX_INT_STRING_LENGTH]; - Logic::convertValueToString(val, raw, MAX_INT_STRING_LENGTH); - mData = new (sStringPool.allocate(0)) StringData(raw); - incReference(mData); - } - - explicit StringTemplate(alnf val) { - tChar raw[MAX_INT_STRING_LENGTH]; - Logic::convertValueToString(val, raw, MAX_FLOAT_STRING_LENGTH); - mData = new (sStringPool.allocate(0)) StringData(raw); - incReference(mData); - } - - explicit StringTemplate(bool val) { - tChar raw[MAX_INT_STRING_LENGTH]; - Logic::convertValueToString(val, raw, MAX_BOOL_STRING_LENGTH); - mData = new (sStringPool.allocate(0)) StringData(raw); - incReference(mData); - } - - explicit operator alni() { - alni out; - Logic::convertStringToValue(read(), out); - return out; - } - - explicit operator alnf() { - alnf out; - Logic::convertStringToValue(read(), out); - return out; - } - - explicit operator bool() { - bool out; - Logic::convertStringToValue(read(), out); - return out; - } - - Index size() const { - return Logic::calcLength(read()); - } - - void calcLineOffsets(Buffer& aOut) const { - Logic::calcLineOffsets(read(), size(), aOut); - } - - StringTemplate& operator=(tChar* in) { - this->~StringTemplate(); - new (this) StringTemplate(in); - return *this; - } - - StringTemplate& operator=(const tChar* in) { - this->~StringTemplate(); - new (this) StringTemplate(in); - return *this; - } - - StringTemplate& operator=(const StringTemplate& in) { - if (&in == this) return *this; - this->~StringTemplate(); - new (this) StringTemplate(in); - return *this; - } - - bool operator==(const StringTemplate& in) const { - if (&in == this) return true; - if (in.mData == mData) return true; - return Logic::isEqualLogic(in.read(), read()); - } - - StringTemplate operator+(const StringTemplate& in) const { - StringTemplate out; - auto const newSize = in.size() + size(); - out.resize(newSize); - Logic::insertLogic(out.write(), newSize, read(), in.read(), size(), in.size()); - return out; - } - - public: // Debugging - [[nodiscard]] ualni getReferenceCount() const { return mData->mReferenceCount; } - [[nodiscard]] bool getIsConstFlag() const { return mData->mIsConst; } - }; - - - template - PoolAlloc, StringTemplate::STRINGS_POOL_SIZE> StringTemplate::sStringPool; - - template - StringData StringTemplate::sNullString; - - using String = StringTemplate; - - template - ualni hash(StringTemplate in) { - return hash(in.read()); - } +#pragma once + +#include "Allocators.hpp" +#include "StringLogic.hpp" + +namespace tp { + + // Static data + extern ModuleManifest gModuleStrings; + + template + class StringTemplate; + + // Hidden slave class + template + class StringData { + friend StringTemplate; + typedef StringLogic Logic; + typedef typename StringLogic::Index Index; + + private: + uint2 mIsConst; // source is non-modifiable + uint2 mEditedIdx; // editor id + uint4 mReferenceCount; // number of users of this + tChar* mBuff; // actual string data + + StringData() { + mBuff = (tChar*) "*"; + mReferenceCount = 1; + mIsConst = true; + mEditedIdx = 0; + } + + StringData(const tChar* aBuff, bool aIsConst) { + MODULE_SANITY_CHECK(gModuleStrings) + DEBUG_ASSERT(aBuff) + mBuff = (tChar*) aBuff; + mReferenceCount = 0; + mIsConst = aIsConst; + mEditedIdx = 0; + } + + explicit StringData(tChar* aBuff) { + MODULE_SANITY_CHECK(gModuleStrings) + DEBUG_ASSERT(aBuff) + auto const len = Logic::calcLength(aBuff); + mReferenceCount = 0; + mIsConst = false; + mEditedIdx = 0; + mBuff = new tChar[len + 1]; + mBuff[len] = Logic::getEndChar(); + memCopy(mBuff, aBuff, len); + } + + [[nodiscard]] tChar* getBuffer() { return mBuff; } + + ~StringData() { + if (!mIsConst) delete[] mBuff; + } + + void resize(Index size) { + DEBUG_ASSERT(mReferenceCount == 1 && !mIsConst) + delete[] mBuff; + mBuff = new tChar[size + 1]; + mBuff[size] = Logic::getEndChar(); + } + }; + + template + class StringTemplate { + public: + typedef StringLogic Logic; + typedef StringData Data; + typedef typename Logic::Index Index; + + enum { + STRINGS_POOL_SIZE = 1024, + MAX_INT_STRING_LENGTH = 10, + MAX_BOOL_STRING_LENGTH = 10, + MAX_FLOAT_STRING_LENGTH = 10, + }; + static PoolAlloc, STRINGS_POOL_SIZE> sStringPool; + static Data sNullString; + + private: + Data* mData; + + public: // Main Interface + // Creates null string reference + StringTemplate() { + mData = &sNullString; + incReference(mData); + } + + // References existing string data + StringTemplate(const StringTemplate& in) { + mData = in.mData; + incReference(mData); + } + + // Creates new string data from raw data pointer. + // Does not own string buffer - string buffer will not be freed. Initializes as const memory. + StringTemplate(const tChar* raw) { + mData = new (sStringPool.allocate(0)) StringData(raw, true); + incReference(mData); + } + + // Copies raw data and claims ownership over it + StringTemplate(tChar* raw) { + mData = new (sStringPool.allocate(0)) StringData(raw); + incReference(mData); + } + + ~StringTemplate() { decReference(mData); } + + private: + static void incReference(Data* dp) { dp->mReferenceCount++; } + + void decReference(Data* dp) { + DEBUG_ASSERT(dp->mReferenceCount > 0) + dp->mReferenceCount--; + if (!dp->mReferenceCount) { + mData->~StringData(); + sStringPool.deallocate(mData); + } + } + + public: // Access + // used to read data + [[nodiscard]] const tChar* read() const { return mData->mBuff; } + + // used to write data + // output will be null if in TextEditing mode + [[nodiscard]] tChar* write() { + makeModifiable(); + return mData->getBuffer(); + } + + // output will be null if in TextEditing mode + tChar* resize(Index size) { + makeModifiable(); + mData->resize(size); + return write(); + } + + public: + void makeModifiable() { + // We have no rights to modify if someone references that memory too + // So we need to create new copy of StringData + if (mData->mReferenceCount > 1) { + mData = new (sStringPool.allocate(0)) StringData(mData->mBuff); + incReference(mData); + return; + } + + // Also if initial raw data was marked as const - create copy of raw data + // Note - raw data will be lost at this point if no other record of such is stored + if (mData->mIsConst) { + mData = new (sStringPool.allocate(0)) StringData(mData->mBuff); + incReference(mData); + } + } + + template + void archiveWrite(tArchiver& ar) const { + auto size = this->size(); + ar << size; + ar.writeBytes(read(), size); + } + + template + void archiveRead(tArchiver& ar) { + Index size; + ar >> size; + resize(size); + ar.readBytes(write(), size); + } + + public: // Syntax sugars + explicit StringTemplate(alni val) { + tChar raw[MAX_INT_STRING_LENGTH]; + Logic::convertValueToString(val, raw, MAX_INT_STRING_LENGTH); + mData = new (sStringPool.allocate(0)) StringData(raw); + incReference(mData); + } + + explicit StringTemplate(alnf val) { + tChar raw[MAX_INT_STRING_LENGTH]; + Logic::convertValueToString(val, raw, MAX_FLOAT_STRING_LENGTH); + mData = new (sStringPool.allocate(0)) StringData(raw); + incReference(mData); + } + + explicit StringTemplate(bool val) { + tChar raw[MAX_INT_STRING_LENGTH]; + Logic::convertValueToString(val, raw, MAX_BOOL_STRING_LENGTH); + mData = new (sStringPool.allocate(0)) StringData(raw); + incReference(mData); + } + + explicit operator alni() { + alni out; + Logic::convertStringToValue(read(), out); + return out; + } + + explicit operator alnf() { + alnf out; + Logic::convertStringToValue(read(), out); + return out; + } + + explicit operator bool() { + bool out; + Logic::convertStringToValue(read(), out); + return out; + } + + Index size() const { return Logic::calcLength(read()); } + + void calcLineOffsets(Buffer& aOut) const { Logic::calcLineOffsets(read(), size(), aOut); } + + StringTemplate& operator=(tChar* in) { + this->~StringTemplate(); + new (this) StringTemplate(in); + return *this; + } + + StringTemplate& operator=(const tChar* in) { + this->~StringTemplate(); + new (this) StringTemplate(in); + return *this; + } + + StringTemplate& operator=(const StringTemplate& in) { + if (&in == this) return *this; + this->~StringTemplate(); + new (this) StringTemplate(in); + return *this; + } + + bool operator==(const StringTemplate& in) const { + if (&in == this) return true; + if (in.mData == mData) return true; + return Logic::isEqualLogic(in.read(), read()); + } + + StringTemplate operator+(const StringTemplate& in) const { + StringTemplate out; + auto const newSize = in.size() + size(); + out.resize(newSize); + Logic::insertLogic(out.write(), newSize, read(), in.read(), size(), in.size()); + return out; + } + + public: // Debugging + [[nodiscard]] ualni getReferenceCount() const { return mData->mReferenceCount; } + [[nodiscard]] bool getIsConstFlag() const { return mData->mIsConst; } + }; + + template + PoolAlloc, StringTemplate::STRINGS_POOL_SIZE> StringTemplate::sStringPool; + + template + StringData StringTemplate::sNullString; + + using String = StringTemplate; + + template + ualni hash(StringTemplate in) { + return hash(in.read()); + } } \ No newline at end of file diff --git a/Strings/tests/Tests.cpp b/Strings/tests/Tests.cpp index 0129583..413a264 100644 --- a/Strings/tests/Tests.cpp +++ b/Strings/tests/Tests.cpp @@ -1,24 +1,24 @@ - -#include "Tests.hpp" - -#include "Strings.hpp" - -void testStringLogic(); -void testStrings(); -void testLogging(); - -int main() { - - tp::ModuleManifest* deps[] = { &tp::gModuleStrings, &tp::gModuleUtils, nullptr }; - tp::ModuleManifest testModule("StringsTest", nullptr, nullptr, deps); - - if (!testModule.initialize()) { - return 1; - } - - testStringLogic(); - testStrings(); - testLogging(); - - testModule.deinitialize(); + +#include "Tests.hpp" + +#include "Strings.hpp" + +void testStringLogic(); +void testStrings(); +void testLogging(); + +int main() { + + tp::ModuleManifest* deps[] = { &tp::gModuleStrings, &tp::gModuleUtils, nullptr }; + tp::ModuleManifest testModule("StringsTest", nullptr, nullptr, deps); + + if (!testModule.initialize()) { + return 1; + } + + testStringLogic(); + testStrings(); + testLogging(); + + testModule.deinitialize(); } \ No newline at end of file diff --git a/Strings/tests/Tests.hpp b/Strings/tests/Tests.hpp index 9f2e45d..b906c49 100644 --- a/Strings/tests/Tests.hpp +++ b/Strings/tests/Tests.hpp @@ -1,4 +1,4 @@ #pragma once -#include "Testing.hpp" -#include "Allocators.hpp" \ No newline at end of file +#include "Allocators.hpp" +#include "Testing.hpp" \ No newline at end of file diff --git a/Strings/tests/TestsLogging.cpp b/Strings/tests/TestsLogging.cpp index 58c281b..92c68b2 100644 --- a/Strings/tests/TestsLogging.cpp +++ b/Strings/tests/TestsLogging.cpp @@ -1,9 +1,7 @@ -#include "Tests.hpp" #include "Logging.hpp" +#include "Tests.hpp" using namespace tp; -TEST_DEF(Logging) { - -} \ No newline at end of file +TEST_DEF(Logging) {} \ No newline at end of file diff --git a/Strings/tests/TestsStrings.cpp b/Strings/tests/TestsStrings.cpp index 5bdee31..5e20bf8 100644 --- a/Strings/tests/TestsStrings.cpp +++ b/Strings/tests/TestsStrings.cpp @@ -1,7 +1,7 @@ #include "NewPlacement.hpp" -#include "Tests.hpp" #include "Strings.hpp" +#include "Tests.hpp" using namespace tp; @@ -12,9 +12,7 @@ struct TestStruct { TEST_DEF_STATIC(Addition) { String str1 = "abc"; String str2 = "def"; - { - str1 + str2; - } + { str1 + str2; } { TEST(str1 + str2 == "abcdef"); TEST(str1 + "aaaccc" == "abcaaaccc"); diff --git a/Strings/tests/TestsStringsLogic.cpp b/Strings/tests/TestsStringsLogic.cpp index 7de8051..1d30d92 100644 --- a/Strings/tests/TestsStringsLogic.cpp +++ b/Strings/tests/TestsStringsLogic.cpp @@ -1,13 +1,12 @@ #include "NewPlacement.hpp" -#include "Tests.hpp" #include "StringLogic.hpp" +#include "Tests.hpp" using namespace tp; typedef StringLogic Logic; - TEST_DEF(isNewLineChar) { // Test isNewLineChar function TEST(Logic::isNewLineChar('\n')); @@ -107,7 +106,6 @@ TEST_DEF(removeLogicGood) { TEST(Logic::isEqualLogic(removed, result)); } - TEST_DEF(insertLogic) { // Test insertLogic function testinsertLogicGood(); @@ -232,7 +230,6 @@ TEST_DEF(calcLineOffsets) { TEST(offsets[6] == 16); } - TEST_DEF(StringLogic) { testisNewLineChar(); testisEndChar(); diff --git a/Tokenizer/private/Tokenizer.cpp b/Tokenizer/private/Tokenizer.cpp index 618498b..e447a6e 100644 --- a/Tokenizer/private/Tokenizer.cpp +++ b/Tokenizer/private/Tokenizer.cpp @@ -1,14 +1,10 @@ - -#include "Tokenizer.hpp" - -using namespace tp; - -static ModuleManifest* sModuleDependencies[] = { - &tp::gModuleStrings, - nullptr -}; - -void deinit(const ModuleManifest*) {} - -ModuleManifest tp::gModuleTokenizer = ModuleManifest("Tokenizer", nullptr, deinit, sModuleDependencies); - + +#include "Tokenizer.hpp" + +using namespace tp; + +static ModuleManifest* sModuleDependencies[] = { &tp::gModuleStrings, nullptr }; + +void deinit(const ModuleManifest*) {} + +ModuleManifest tp::gModuleTokenizer = ModuleManifest("Tokenizer", nullptr, deinit, sModuleDependencies); diff --git a/Tokenizer/public/Tokenizer.hpp b/Tokenizer/public/Tokenizer.hpp index 869beba..57abfc7 100644 --- a/Tokenizer/public/Tokenizer.hpp +++ b/Tokenizer/public/Tokenizer.hpp @@ -1,211 +1,184 @@ - -#pragma once - -#include "RegularExpression.h" -#include "Strings.hpp" - -namespace tp { - - extern ModuleManifest gModuleTokenizer; - - template - class Tokenizer { - - TransitionMatrix mTransitionMatrix; - - RegEx::CompileError mError; - - bool scanFailed() { - return mTransitionMatrix.isTrapped(); - } - - public: - // Some useful RE to be reused - static constexpr const tAlphabetType* etherRE = "\n|\t| |\r"; - static constexpr const tAlphabetType* intRE = "((\\-)|(\\+))?[0-9]+i?"; - static constexpr const tAlphabetType* floatRE = R"(((\-)|(\+))?([0-9]+)(\.)([0-9]*)?f?)"; - static constexpr const tAlphabetType* commentBlockRE = R"((/\*){\*-\*}*(\*/))"; - static constexpr const tAlphabetType* stringRE = R"("{"-"}*")"; - static constexpr const tAlphabetType* idRE = "([a-z]|[A-Z]|_)+([a-z]|[A-Z]|[0-9]|_)*"; - - public: - - Tokenizer() { - MODULE_SANITY_CHECK(gModuleTokenizer) - } - - void build(const InitialierList>& rules) { - NFA nfa; - - mError = RegEx::compile(nfa, rules); - if (mError.isError()) { - return; - } - - DFA dfa(nfa); - mTransitionMatrix.construct(dfa); - } - - [[nodiscard]] bool isBuild() const { - return !mError.isError(); - } - - auto getMatrix() const { return &mTransitionMatrix; } - - const RegEx::CompileError& getBuildError() { - return mError; - } - - void resetMatrix() { - mTransitionMatrix.reset(); - } - - tTokType advanceSymbol(tAlphabetType symbol) { - return mTransitionMatrix.move(symbol); - } - - tTokType advanceToken(const tAlphabetType* source, ualni source_len, ualni* token_len) { - tTokType out = tNoTokVal; - *token_len = 0; - for (ualni idx = 0; idx < source_len; idx++) { - out = advanceSymbol(source[idx]); - if (out != tNoTokVal) { - *token_len = idx; - break; - } - } - return out; - } - - ~Tokenizer() = default; - }; - - template - class SimpleTokenizer { - public: - typedef Tokenizer tTokenizer; - - private: - tTokenizer mTokenizer; - - const tAlphabetType* mSource = nullptr; - ualni mLastTokLen = 0; - ualni mSourceLen = 0; - ualni mAdvancedOffset = 0; - - public: - - struct Cursor { - const tAlphabetType* mSource = nullptr; - ualni mAdvancedOffset = 0; - const tAlphabetType* str() { return mSource + mAdvancedOffset; } - - struct Location2D { - ualni line = 0; - ualni character = 0; - }; - - Location2D get2DLocation() { - Location2D out; - typedef typename StringLogic::Index Idx; - Buffer offsets; - StringLogic::calcLineOffsets(mSource, StringLogic::calcLength(mSource), offsets); - for (ualni idx = 1; idx < offsets.size(); idx++) { - if (offsets[idx] > mAdvancedOffset) { - out.line = idx - 1; - break; - } - } - out.character = mAdvancedOffset - offsets[out.line]; - return out; - } - }; - - SimpleTokenizer() = default; - auto getTokenizer() const { return &mTokenizer; } - - void build(const InitialierList>& rules) { - mTokenizer.build(rules); - } - - [[nodiscard]] bool isBuild() const { - return mTokenizer.isBuild(); - } - - const RegEx::CompileError& getBuildError() { - return mTokenizer.getBuildError(); - } - - void bindSource(const tAlphabetType* source) { - mSource = source; - while (mSource[mSourceLen]) mSourceLen++; - mSourceLen++; - } - - [[nodiscard]] bool isInputLeft() const { - if (!mSource) { - return false; - } - if (mSource[mAdvancedOffset] == 0) { - return false; - } - return true; - } - - Cursor getCursor() const { - return { mSource, mAdvancedOffset }; - } - - Cursor getCursorPrev() const { - return { mSource, mAdvancedOffset - mLastTokLen }; - } - - void setCursor(const Cursor& crs) { - mAdvancedOffset = crs.mAdvancedOffset; - mLastTokLen = 0; - } - - tTokType readTok() { - if (mSourceLen == mAdvancedOffset + 1) { - return tSourceEndTokVal; - } - - tTokType out = mTokenizer.advanceToken(mSource + mAdvancedOffset, mSourceLen - mAdvancedOffset, &mLastTokLen); - mAdvancedOffset += mLastTokLen; - return out; - } - - tTokType lookupTok() { - auto out = readTok(); - discardTok(); - return out; - } - - void discardTok() { - mTokenizer.resetMatrix(); - mAdvancedOffset -= mLastTokLen; - mLastTokLen = 0; - } - - void skipTok() { - readTok(); - } - - void reset() { - mAdvancedOffset = mLastTokLen = 0; - mTokenizer.resetMatrix(); - } - - [[nodiscard]] ualni lastTokLEn() const { - return mLastTokLen; - } - - String extractVal() { - auto crs = getCursorPrev(); - String out; - out.resize(mLastTokLen); - memCopy(out.write(), crs.str(), mLastTokLen); - return out; - } - }; + +#pragma once + +#include "RegularExpression.h" +#include "Strings.hpp" + +namespace tp { + + extern ModuleManifest gModuleTokenizer; + + template + class Tokenizer { + + TransitionMatrix mTransitionMatrix; + + RegEx::CompileError mError; + + bool scanFailed() { return mTransitionMatrix.isTrapped(); } + + public: + // Some useful RE to be reused + static constexpr const tAlphabetType* etherRE = "\n|\t| |\r"; + static constexpr const tAlphabetType* intRE = "((\\-)|(\\+))?[0-9]+i?"; + static constexpr const tAlphabetType* floatRE = R"(((\-)|(\+))?([0-9]+)(\.)([0-9]*)?f?)"; + static constexpr const tAlphabetType* commentBlockRE = R"((/\*){\*-\*}*(\*/))"; + static constexpr const tAlphabetType* stringRE = R"("{"-"}*")"; + static constexpr const tAlphabetType* idRE = "([a-z]|[A-Z]|_)+([a-z]|[A-Z]|[0-9]|_)*"; + + public: + Tokenizer() { MODULE_SANITY_CHECK(gModuleTokenizer) } + + void build(const InitialierList>& rules) { + NFA nfa; + + mError = RegEx::compile(nfa, rules); + if (mError.isError()) { + return; + } + + DFA dfa(nfa); + mTransitionMatrix.construct(dfa); + } + + [[nodiscard]] bool isBuild() const { return !mError.isError(); } + + auto getMatrix() const { return &mTransitionMatrix; } + + const RegEx::CompileError& getBuildError() { return mError; } + + void resetMatrix() { mTransitionMatrix.reset(); } + + tTokType advanceSymbol(tAlphabetType symbol) { return mTransitionMatrix.move(symbol); } + + tTokType advanceToken(const tAlphabetType* source, ualni source_len, ualni* token_len) { + tTokType out = tNoTokVal; + *token_len = 0; + for (ualni idx = 0; idx < source_len; idx++) { + out = advanceSymbol(source[idx]); + if (out != tNoTokVal) { + *token_len = idx; + break; + } + } + return out; + } + + ~Tokenizer() = default; + }; + + template + class SimpleTokenizer { + public: + typedef Tokenizer tTokenizer; + + private: + tTokenizer mTokenizer; + + const tAlphabetType* mSource = nullptr; + ualni mLastTokLen = 0; + ualni mSourceLen = 0; + ualni mAdvancedOffset = 0; + + public: + struct Cursor { + const tAlphabetType* mSource = nullptr; + ualni mAdvancedOffset = 0; + const tAlphabetType* str() { return mSource + mAdvancedOffset; } + + struct Location2D { + ualni line = 0; + ualni character = 0; + }; + + Location2D get2DLocation() { + Location2D out; + typedef typename StringLogic::Index Idx; + Buffer offsets; + StringLogic::calcLineOffsets(mSource, StringLogic::calcLength(mSource), offsets); + for (ualni idx = 1; idx < offsets.size(); idx++) { + if (offsets[idx] > mAdvancedOffset) { + out.line = idx - 1; + break; + } + } + out.character = mAdvancedOffset - offsets[out.line]; + return out; + } + }; + + SimpleTokenizer() = default; + auto getTokenizer() const { return &mTokenizer; } + + void build(const InitialierList>& rules) { mTokenizer.build(rules); } + + [[nodiscard]] bool isBuild() const { return mTokenizer.isBuild(); } + + const RegEx::CompileError& getBuildError() { return mTokenizer.getBuildError(); } + + void bindSource(const tAlphabetType* source) { + mSource = source; + while (mSource[mSourceLen]) + mSourceLen++; + mSourceLen++; + } + + [[nodiscard]] bool isInputLeft() const { + if (!mSource) { + return false; + } + if (mSource[mAdvancedOffset] == 0) { + return false; + } + return true; + } + + Cursor getCursor() const { return { mSource, mAdvancedOffset }; } + + Cursor getCursorPrev() const { return { mSource, mAdvancedOffset - mLastTokLen }; } + + void setCursor(const Cursor& crs) { + mAdvancedOffset = crs.mAdvancedOffset; + mLastTokLen = 0; + } + + tTokType readTok() { + if (mSourceLen == mAdvancedOffset + 1) { + return tSourceEndTokVal; + } + + tTokType out = mTokenizer.advanceToken(mSource + mAdvancedOffset, mSourceLen - mAdvancedOffset, &mLastTokLen); + mAdvancedOffset += mLastTokLen; + return out; + } + + tTokType lookupTok() { + auto out = readTok(); + discardTok(); + return out; + } + + void discardTok() { + mTokenizer.resetMatrix(); + mAdvancedOffset -= mLastTokLen; + mLastTokLen = 0; + } + + void skipTok() { readTok(); } + + void reset() { + mAdvancedOffset = mLastTokLen = 0; + mTokenizer.resetMatrix(); + } + + [[nodiscard]] ualni lastTokLEn() const { return mLastTokLen; } + + String extractVal() { + auto crs = getCursorPrev(); + String out; + out.resize(mLastTokLen); + memCopy(out.write(), crs.str(), mLastTokLen); + return out; + } + }; } \ No newline at end of file diff --git a/Tokenizer/tests/TestTokenizer.cpp b/Tokenizer/tests/TestTokenizer.cpp index 350e51e..be898a1 100644 --- a/Tokenizer/tests/TestTokenizer.cpp +++ b/Tokenizer/tests/TestTokenizer.cpp @@ -11,7 +11,7 @@ using namespace tp; ualni outputHashPassed = 1156; const char* script = -R"( + R"( /* yea comment "and string inside" with int 123 and float 0.123f */ @@ -76,7 +76,7 @@ TEST_DEF_STATIC(General) { CONST_STRING, ID, - //COMMENT_LINE, + // COMMENT_LINE, COMMENT_BLOCK, }; @@ -84,45 +84,45 @@ TEST_DEF_STATIC(General) { SimpleTokenizer lexer; lexer.build({ - { "\n|\t| |\r", TokType::SPACE }, - { "var", TokType::VAR }, - { "class", TokType::CLASS_DEF }, - { "self", TokType::SELF }, - { "\\{", TokType::SCOPE_IN }, - { "\\}", TokType::SCOPE_OUT }, - { "=", TokType::ASSIGN }, - { "def", TokType::DEF_FUNC }, - { "<<", TokType::PRINT }, - { "if", TokType::IF }, - { "else", TokType::ELSE }, - { "while", TokType::WHILE }, - { "\\(", TokType::BRACKET_IN }, - { "\\)", TokType::BRACKET_OUT }, - { ",", TokType::COMMA }, - { "new", TokType::NEW }, - { "\\.", TokType::CHILD }, - { "return", TokType::RETURN }, - { "==", TokType::EQUAL }, - { "!=", TokType::NOT_EQUAL }, - { ">", TokType::MORE }, - { "<", TokType::LESS }, - { ">=", TokType::QE_OR_MORE }, - { "<=", TokType::QE_OR_LESS }, - { "!", TokType::BOOL_NOT }, - { "&&", TokType::BOOL_AND }, - { "\\|\\|", TokType::BOOL_OR }, - { "\\+", TokType::ADD }, - { "\\*", TokType::MUL }, - { "\\-", TokType::SUB }, - { "/", TokType::DIV }, - { ";", TokType::STM_END }, - { "true", TokType::CONST_TRUE }, - { "false", TokType::CONST_FALSE }, - { "((\\-)|(\\+))?[0-9]+i?", TokType::CONST_INT }, - { R"(((\-)|(\+))?([0-9]+)(\.)([0-9]*)?f?)", TokType::CONST_FLOAT }, - { R"((/\*){\*-\*}*(\*/))", TokType::COMMENT_BLOCK }, - { R"("{"-"}*")", TokType::CONST_STRING }, - { "([a-z]|[A-Z]|_)+([a-z]|[A-Z]|[0-9]|_)*", TokType::ID }, + { "\n|\t| |\r", TokType::SPACE }, + { "var", TokType::VAR }, + { "class", TokType::CLASS_DEF }, + { "self", TokType::SELF }, + { "\\{", TokType::SCOPE_IN }, + { "\\}", TokType::SCOPE_OUT }, + { "=", TokType::ASSIGN }, + { "def", TokType::DEF_FUNC }, + { "<<", TokType::PRINT }, + { "if", TokType::IF }, + { "else", TokType::ELSE }, + { "while", TokType::WHILE }, + { "\\(", TokType::BRACKET_IN }, + { "\\)", TokType::BRACKET_OUT }, + { ",", TokType::COMMA }, + { "new", TokType::NEW }, + { "\\.", TokType::CHILD }, + { "return", TokType::RETURN }, + { "==", TokType::EQUAL }, + { "!=", TokType::NOT_EQUAL }, + { ">", TokType::MORE }, + { "<", TokType::LESS }, + { ">=", TokType::QE_OR_MORE }, + { "<=", TokType::QE_OR_LESS }, + { "!", TokType::BOOL_NOT }, + { "&&", TokType::BOOL_AND }, + { "\\|\\|", TokType::BOOL_OR }, + { "\\+", TokType::ADD }, + { "\\*", TokType::MUL }, + { "\\-", TokType::SUB }, + { "/", TokType::DIV }, + { ";", TokType::STM_END }, + { "true", TokType::CONST_TRUE }, + { "false", TokType::CONST_FALSE }, + { "((\\-)|(\\+))?[0-9]+i?", TokType::CONST_INT }, + { R"(((\-)|(\+))?([0-9]+)(\.)([0-9]*)?f?)", TokType::CONST_FLOAT }, + { R"((/\*){\*-\*}*(\*/))", TokType::COMMENT_BLOCK }, + { R"("{"-"}*")", TokType::CONST_STRING }, + { "([a-z]|[A-Z]|_)+([a-z]|[A-Z]|[0-9]|_)*", TokType::ID }, }); if (!lexer.isBuild()) { @@ -141,47 +141,207 @@ TEST_DEF_STATIC(General) { outputHash += ualni(tok); switch (tok) { - case TokType::SPACE: { printf(" "); } break; - case TokType::VAR: { LOG(VAR); } break; - case TokType::CLASS_DEF: { LOG(CLASS_DEF); } break; - case TokType::SELF: { LOG(SELF); } break; - case TokType::SCOPE_IN: { LOG(SCOPE_IN); } break; - case TokType::SCOPE_OUT: { LOG(SCOPE_OUT); } break; - case TokType::ASSIGN: { LOG(ASSIGN); } break; - case TokType::DEF_FUNC: { LOG(DEF_FUNC); } break; - case TokType::PRINT: { LOG(PRINT); } break; - case TokType::IF: { LOG(IF); } break; - case TokType::ELSE: { LOG(ELSE); } break; - case TokType::WHILE: { LOG(WHILE); } break; - case TokType::BRACKET_IN: { LOG(BRACKET_IN); } break; - case TokType::BRACKET_OUT: { LOG(BRACKET_OUT); } break; - case TokType::COMMA: { LOG(COMMA); } break; - case TokType::NEW: { LOG(NEW); } break; - case TokType::CHILD: { LOG(CHILD); } break; - case TokType::RETURN: { LOG(RETURN); } break; - case TokType::EQUAL: { LOG(EQUAL); } break; - case TokType::NOT_EQUAL: { LOG(NOT_EQUAL); } break; - case TokType::MORE: { LOG(MORE); } break; - case TokType::LESS: { LOG(LESS); } break; - case TokType::QE_OR_MORE: { LOG(QE_OR_MORE); } break; - case TokType::QE_OR_LESS: { LOG(QE_OR_LESS); } break; - case TokType::BOOL_NOT: { LOG(BOOL_NOT); } break; - case TokType::BOOL_AND: { LOG(BOOL_AND); } break; - case TokType::BOOL_OR: { LOG(BOOL_OR); } break; - case TokType::ADD: { LOG(ADD); } break; - case TokType::MUL: { LOG(MUL); } break; - case TokType::SUB: { LOG(SUB); } break; - case TokType::DIV: { LOG(DIV); } break; - case TokType::STM_END: { LOG(STM_END); } break; - case TokType::CONST_TRUE: { LOG(TRUE); } break; - case TokType::CONST_FALSE: { LOG(FALSE); } break; - case TokType::CONST_INT: { LOG(INT); } break; - case TokType::CONST_FLOAT: { LOG(FLOAT); } break; - case TokType::CONST_STRING: { LOG(STRING); } break; - case TokType::ID: { LOG(ID); } break; - //case TokType::COMMENT_LINE: { LOG(COMMENT_LINE) } break; - case TokType::COMMENT_BLOCK: { LOG(COMMENT_BLOCK); } break; - case TokType::FAILED: { LOG(FAILED); } break; + case TokType::SPACE: + { + printf(" "); + } + break; + case TokType::VAR: + { + LOG(VAR); + } + break; + case TokType::CLASS_DEF: + { + LOG(CLASS_DEF); + } + break; + case TokType::SELF: + { + LOG(SELF); + } + break; + case TokType::SCOPE_IN: + { + LOG(SCOPE_IN); + } + break; + case TokType::SCOPE_OUT: + { + LOG(SCOPE_OUT); + } + break; + case TokType::ASSIGN: + { + LOG(ASSIGN); + } + break; + case TokType::DEF_FUNC: + { + LOG(DEF_FUNC); + } + break; + case TokType::PRINT: + { + LOG(PRINT); + } + break; + case TokType::IF: + { + LOG(IF); + } + break; + case TokType::ELSE: + { + LOG(ELSE); + } + break; + case TokType::WHILE: + { + LOG(WHILE); + } + break; + case TokType::BRACKET_IN: + { + LOG(BRACKET_IN); + } + break; + case TokType::BRACKET_OUT: + { + LOG(BRACKET_OUT); + } + break; + case TokType::COMMA: + { + LOG(COMMA); + } + break; + case TokType::NEW: + { + LOG(NEW); + } + break; + case TokType::CHILD: + { + LOG(CHILD); + } + break; + case TokType::RETURN: + { + LOG(RETURN); + } + break; + case TokType::EQUAL: + { + LOG(EQUAL); + } + break; + case TokType::NOT_EQUAL: + { + LOG(NOT_EQUAL); + } + break; + case TokType::MORE: + { + LOG(MORE); + } + break; + case TokType::LESS: + { + LOG(LESS); + } + break; + case TokType::QE_OR_MORE: + { + LOG(QE_OR_MORE); + } + break; + case TokType::QE_OR_LESS: + { + LOG(QE_OR_LESS); + } + break; + case TokType::BOOL_NOT: + { + LOG(BOOL_NOT); + } + break; + case TokType::BOOL_AND: + { + LOG(BOOL_AND); + } + break; + case TokType::BOOL_OR: + { + LOG(BOOL_OR); + } + break; + case TokType::ADD: + { + LOG(ADD); + } + break; + case TokType::MUL: + { + LOG(MUL); + } + break; + case TokType::SUB: + { + LOG(SUB); + } + break; + case TokType::DIV: + { + LOG(DIV); + } + break; + case TokType::STM_END: + { + LOG(STM_END); + } + break; + case TokType::CONST_TRUE: + { + LOG(TRUE); + } + break; + case TokType::CONST_FALSE: + { + LOG(FALSE); + } + break; + case TokType::CONST_INT: + { + LOG(INT); + } + break; + case TokType::CONST_FLOAT: + { + LOG(FLOAT); + } + break; + case TokType::CONST_STRING: + { + LOG(STRING); + } + break; + case TokType::ID: + { + LOG(ID); + } + break; + // case TokType::COMMENT_LINE: { LOG(COMMENT_LINE) } break; + case TokType::COMMENT_BLOCK: + { + LOG(COMMENT_BLOCK); + } + break; + case TokType::FAILED: + { + LOG(FAILED); + } + break; case TokType::NONE: case TokType::TOK_SOURCE_END: break; } @@ -207,9 +367,9 @@ TEST_DEF(Simple) { SimpleTokenizer lexer; lexer.build({ - { " ", TokType::SPACE }, - { "([a-c]|A)+", TokType::ID }, - { "A", TokType::START }, + { " ", TokType::SPACE }, + { "([a-c]|A)+", TokType::ID }, + { "A", TokType::START }, }); if (!lexer.isBuild()) { diff --git a/Tokenizer/tests/tests.cpp b/Tokenizer/tests/tests.cpp index 4e721e9..77398c0 100644 --- a/Tokenizer/tests/tests.cpp +++ b/Tokenizer/tests/tests.cpp @@ -1,18 +1,18 @@ - -#include "Tokenizer.hpp" -#include "Testing.hpp" - -void testTokenizer(); - -int main(int argc, char* argv[]) { - - tp::ModuleManifest* ModuleDependencies[] = { &tp::gModuleTokenizer, nullptr }; - tp::ModuleManifest TestModule("TokenizerTest", nullptr, nullptr, ModuleDependencies); - if (!TestModule.initialize()) { - return 1; - } - - testTokenizer(); - - TestModule.deinitialize(); + +#include "Testing.hpp" +#include "Tokenizer.hpp" + +void testTokenizer(); + +int main(int argc, char* argv[]) { + + tp::ModuleManifest* ModuleDependencies[] = { &tp::gModuleTokenizer, nullptr }; + tp::ModuleManifest TestModule("TokenizerTest", nullptr, nullptr, ModuleDependencies); + if (!TestModule.initialize()) { + return 1; + } + + testTokenizer(); + + TestModule.deinitialize(); } \ No newline at end of file diff --git a/Utils/private/Debugging.cpp b/Utils/private/Debugging.cpp index 965da3d..ed9cf8a 100644 --- a/Utils/private/Debugging.cpp +++ b/Utils/private/Debugging.cpp @@ -8,9 +8,7 @@ using namespace tp; CallStackCapture* tp::gCSCapture = nullptr; -void initializeCallStackCapture() { - gCSCapture = new (malloc(sizeof(CallStackCapture))) CallStackCapture(); -} +void initializeCallStackCapture() { gCSCapture = new (malloc(sizeof(CallStackCapture))) CallStackCapture(); } void deinitializeCallStackCapture() { gCSCapture->~CallStackCapture(); @@ -20,12 +18,16 @@ void deinitializeCallStackCapture() { ualni CallStackCapture::CallStack::getDepth() const { ualni len = 0; for (long long frame : frames) { - if (!frame) { break; } + if (!frame) { + break; + } len++; } ualni stripedLen = 0; for (auto i = FRAMES_TO_SKIP_START; i < len - FRAMES_TO_SKIP_END; i++) { - if (!frames[i]) { break; } + if (!frames[i]) { + break; + } stripedLen++; } return stripedLen; @@ -34,11 +36,13 @@ ualni CallStackCapture::CallStack::getDepth() const { ualni CallStackCapture::hashCallStack(CallStackKey key) { auto const cs = key.cs; ualni out = 0; - for (ualni i = 0; cs->frames[i]; i++) { out += cs->frames[i]; } + for (ualni i = 0; cs->frames[i]; i++) { + out += cs->frames[i]; + } return out; } -bool CallStackCapture::CallStackKey::operator==(const CallStackCapture::CallStackKey &in) const { +bool CallStackCapture::CallStackKey::operator==(const CallStackCapture::CallStackKey& in) const { for (auto i : Range(MAX_CALL_DEPTH_CAPTURE)) { if (cs->frames[i] != in.cs->frames[i]) { return false; @@ -105,21 +109,19 @@ void CallStackCapture::clear() { mSymbols.removeAll(); } -CallStackCapture::~CallStackCapture() { - free(mBuff); -} +CallStackCapture::~CallStackCapture() { free(mBuff); } // ---------------------------------- Platform Depended ---------------------------------- // #if defined(ENV_OS_LINUX) -#include -#include #include #include +#include +#include void CallStackCapture::platformWriteStackTrace(CallStack* stack) { - auto depth = backtrace((void**)stack->frames, (int) MAX_CALL_DEPTH_CAPTURE - 1); + auto depth = backtrace((void**) stack->frames, (int) MAX_CALL_DEPTH_CAPTURE - 1); stack->frames[depth] = 0; } @@ -139,20 +141,20 @@ static void getGetSourceFromBinaryAddress(const char* binary, const char* addres if (linePtr != nullptr && buff[0] != '?' && buff[1] != '?' && buff[2] != ':') { *linePtr = '\0'; auto sourceLen = std::strlen(buff); - std::strcpy(file, buff + ((sourceLen > MAX_DEBUG_INFO_LEN) ? (sourceLen - MAX_DEBUG_INFO_LEN) : 0)); + std::strcpy(file, buff + ((sourceLen > MAX_DEBUG_INFO_LEN) ? (sourceLen - MAX_DEBUG_INFO_LEN) : 0)); *line = strtoul(linePtr + 1, nullptr, 10); return; } } - std::strcpy(file, "unresolved"); + std::strcpy(file, "unresolved"); *line = 0; } static void getDemangledName(const char* func, char* out) { int status; size_t funcDemangledSize = MAX_DEBUG_INFO_LEN; - char* funcDemangled = (char*)malloc(funcDemangledSize); + char* funcDemangled = (char*) malloc(funcDemangledSize); char* ret = abi::__cxa_demangle(func, funcDemangled, &funcDemangledSize, &status); if (status == 0) { funcDemangled = ret; @@ -176,10 +178,15 @@ void CallStackCapture::platformWriteDebugSymbols(FramePointer frame, DebugSymbol char* offset = nullptr; // 'bin fun+addr' - for (char *p = bin; *p; ++p) { - if (*p == '(') { *p = 0; func = p + 1; } - else if (*p == '+') { offset = p; } - else if (*p == ')' && offset) { *p = 0; } + for (char* p = bin; *p; ++p) { + if (*p == '(') { + *p = 0; + func = p + 1; + } else if (*p == '+') { + offset = p; + } else if (*p == ')' && offset) { + *p = 0; + } } if (func && offset) { @@ -189,11 +196,11 @@ void CallStackCapture::platformWriteDebugSymbols(FramePointer frame, DebugSymbol *offset = 0; getDemangledName(func, out->function); } else { - std::strcpy(out->function, "unresolved"); + std::strcpy(out->function, "unresolved"); } } else { - std::strcpy(out->file, "unresolved"); - std::strcpy(out->function, "unresolved"); + std::strcpy(out->file, "unresolved"); + std::strcpy(out->function, "unresolved"); } free(symbolsArray); @@ -217,7 +224,7 @@ void CallStackCapture::logAll() { #else void CallStackCapture::platformWriteStackTrace(CallStack* stack) { stack->frames[0] = 0; } void CallStackCapture::platformWriteDebugSymbols(FramePointer frame, DebugSymbols* out) { - std::strcpy(out->file, "unresolved"); - std::strcpy(out->function, "unresolved"); + std::strcpy(out->file, "unresolved"); + std::strcpy(out->function, "unresolved"); } #endif \ No newline at end of file diff --git a/Utils/private/Testing.cpp b/Utils/private/Testing.cpp index d2aaa56..10283b6 100644 --- a/Utils/private/Testing.cpp +++ b/Utils/private/Testing.cpp @@ -44,9 +44,7 @@ bool Testing::hasFailed() { return mRootTest.mHasFailed; } -void Testing::setRootName(const char* name) { - mRootTest.mName = name; -} +void Testing::setRootName(const char* name) { mRootTest.mName = name; } void Testing::TestingNode::updateState() { for (auto child : mSubTests) { diff --git a/Utils/private/Timing.cpp b/Utils/private/Timing.cpp index 518a4f7..ae37422 100644 --- a/Utils/private/Timing.cpp +++ b/Utils/private/Timing.cpp @@ -5,8 +5,7 @@ #include "Timing.hpp" #include "Utils.hpp" -#define GETTIMEMSC() (time_ms)\ - (std::chrono::duration_cast(std::chrono::time_point_cast(std::chrono::high_resolution_clock::now()).time_since_epoch()).count()) +#define GETTIMEMSC() (time_ms)(std::chrono::duration_cast(std::chrono::time_point_cast(std::chrono::high_resolution_clock::now()).time_since_epoch()).count()) #define THREAD_SLEEP(time_ms) std::this_thread::sleep_for(std::chrono::milliseconds(time_ms)) @@ -18,10 +17,7 @@ namespace tp { return gCurrentTime; } - void sleep(time_ms mDuration) { - THREAD_SLEEP(mDuration); - } - + void sleep(time_ms mDuration) { THREAD_SLEEP(mDuration); } Timer::Timer() { mDuration = 0; @@ -33,21 +29,13 @@ namespace tp { this->mDuration = mDuration; } - bool Timer::isTimeout() { - return mDuration < GETTIMEMSC() - mStart; - } + bool Timer::isTimeout() { return mDuration < GETTIMEMSC() - mStart; } - void Timer::reset() { - mStart = GETTIMEMSC(); - } + void Timer::reset() { mStart = GETTIMEMSC(); } - time_ms Timer::timePassed() { - return GETTIMEMSC() - mStart; - } + time_ms Timer::timePassed() { return GETTIMEMSC() - mStart; } - time_ms Timer::remainder() { - return mDuration - (GETTIMEMSC() - mStart); - } + time_ms Timer::remainder() { return mDuration - (GETTIMEMSC() - mStart); } time_ms Timer::start() { return mStart; } time_ms Timer::duration() { return mDuration; } diff --git a/Utils/private/Utils.cpp b/Utils/private/Utils.cpp index 11f2011..a0ce799 100644 --- a/Utils/private/Utils.cpp +++ b/Utils/private/Utils.cpp @@ -18,7 +18,9 @@ static bool initialize(const tp::ModuleManifest*) { static void deinitialize(const tp::ModuleManifest*) { deinitializeCallStackCapture(); tp::gTesting.reportState(); - if (tp::gTesting.hasFailed()) { exit(1); } + if (tp::gTesting.hasFailed()) { + exit(1); + } } namespace tp { @@ -87,9 +89,7 @@ namespace tp { return 0; } - bool memEqual(const void* left, const void* right, uhalni len) { - return memCompare(left, right, len) == 0; - } + bool memEqual(const void* left, const void* right, uhalni len) { return memCompare(left, right, len) == 0; } int1 memCompareVal(const void* left, uhalni len, uint1 val) { MODULE_SANITY_CHECK(gModuleBase) diff --git a/Utils/public/Debugging.hpp b/Utils/public/Debugging.hpp index 5444ae6..7722138 100644 --- a/Utils/public/Debugging.hpp +++ b/Utils/public/Debugging.hpp @@ -24,8 +24,10 @@ namespace tp { class Iterator { const FramePointer* mFrame; + public: - explicit Iterator(const FramePointer* frame) : mFrame(frame) {}; + explicit Iterator(const FramePointer* frame) : + mFrame(frame){}; FramePointer getFrame() { return *mFrame; } bool operator==(const Iterator& in) const { return in.mFrame == mFrame; } void operator++() { mFrame++; } @@ -41,6 +43,7 @@ namespace tp { char function[MAX_DEBUG_INFO_LEN + 1] = { 0 }; char file[MAX_DEBUG_INFO_LEN + 1] = { 0 }; ualni line = 0; + public: [[nodiscard]] const char* getFunc() const { return function; } [[nodiscard]] const char* getFile() const { return file; } @@ -58,8 +61,7 @@ namespace tp { void logAll(); public: - - template + template void write(Saver& file) { file.write(mBuffLoad); for (auto cs : *this) { @@ -72,7 +74,7 @@ namespace tp { } // independent of the configuration - template + template void read(Loader& file) { clear(); ualni loadLen; @@ -89,8 +91,10 @@ namespace tp { public: class Iterator { const CallStack* mSnapshot; + public: - explicit Iterator(const CallStack* start) : mSnapshot(start) {}; + explicit Iterator(const CallStack* start) : + mSnapshot(start){}; const CallStack* getCallStack() { return mSnapshot; } bool operator==(const Iterator& in) const { return in.mSnapshot == mSnapshot; } void operator++() { mSnapshot++; } @@ -98,10 +102,9 @@ namespace tp { }; [[nodiscard]] Iterator begin() const { return Iterator(mBuff); } - [[nodiscard]] Iterator end() const { return Iterator(mBuff + mBuffLoad); } + [[nodiscard]] Iterator end() const { return Iterator(mBuff + mBuffLoad); } private: - struct CallStackKey { CallStack* cs; bool operator==(const CallStackKey& in) const; diff --git a/Utils/public/Multithreading.hpp b/Utils/public/Multithreading.hpp index 779914d..7f0b6c5 100644 --- a/Utils/public/Multithreading.hpp +++ b/Utils/public/Multithreading.hpp @@ -4,16 +4,13 @@ namespace tp { class Mutex { - pthread_mutex_t mMutex {}; + pthread_mutex_t mMutex{}; + public: Mutex() = default; - void lock() { - pthread_mutex_lock(&mMutex); - } + void lock() { pthread_mutex_lock(&mMutex); } - void unlock() { - pthread_mutex_unlock(&mMutex); - } + void unlock() { pthread_mutex_unlock(&mMutex); } }; } \ No newline at end of file diff --git a/Utils/public/Sorting.hpp b/Utils/public/Sorting.hpp index 70e602f..53c0c03 100644 --- a/Utils/public/Sorting.hpp +++ b/Utils/public/Sorting.hpp @@ -1,97 +1,95 @@ - -#pragma once - -#include "Utils.hpp" - -namespace tp { - - template - inline bool compare(const Type& val1, const Type& val2) { - return val1 > val2; - } - - struct SortMerge { - - template - static void sort(Type* buff, int length, bool (*grater)(const Type& obj1, const Type& obj2) = &compare) { - mergeSort(buff, 0, length - 1, grater); - } - - private: - - template - static void merge(Type* buff, int left, int middle, int right, bool (*grater)(const Type& obj1, const Type& obj2)) { - int n1 = middle - left + 1; - int n2 = right - middle; - - Type* Left = new Type[n1]; - Type* Right = new Type[n2]; - - for (int i = 0; i < n1; i++) { - Left[i] = buff[left + i]; - } - - for (int j = 0; j < n2; j++) { - Right[j] = buff[middle + 1 + j]; - } - - int i = 0; - int j = 0; - int k = left; - - while (i < n1 && j < n2) { - if (!(grater(Left[i], Right[j]))) { - buff[k] = Left[i]; - i++; - } else { - buff[k] = Right[j]; - j++; - } - k++; - } - - while (i < n1) { - buff[k] = Left[i]; - i++; - k++; - } - - while (j < n2) { - buff[k] = Right[j]; - j++; - k++; - } - - delete[] Left; - delete[] Right; - } - - template - static void mergeSort(Type* buff, int left, int right, bool (*grater)(const Type& obj1, const Type& obj2)) { - - if (left >= right) { - return; - } - - int middle = left + (right - left) / 2; - - mergeSort(buff, left, middle, grater); - mergeSort(buff, middle + 1, right, grater); - merge(buff, left, middle, right, grater); - } - - }; - - struct SortInsert { - template - static void sort(Type* buff, int length, bool (*grater)(const Type& obj1, const Type& obj2) = &compare) { - for (int i = 0; i < length; i++) { - for (int j = i + 1; j < length; j++) { - if (grater(*buff[i], *buff[j])) { - swap(buff[i], buff[j]); - } - } - } - } - }; + +#pragma once + +#include "Utils.hpp" + +namespace tp { + + template + inline bool compare(const Type& val1, const Type& val2) { + return val1 > val2; + } + + struct SortMerge { + + template + static void sort(Type* buff, int length, bool (*grater)(const Type& obj1, const Type& obj2) = &compare) { + mergeSort(buff, 0, length - 1, grater); + } + + private: + template + static void merge(Type* buff, int left, int middle, int right, bool (*grater)(const Type& obj1, const Type& obj2)) { + int n1 = middle - left + 1; + int n2 = right - middle; + + Type* Left = new Type[n1]; + Type* Right = new Type[n2]; + + for (int i = 0; i < n1; i++) { + Left[i] = buff[left + i]; + } + + for (int j = 0; j < n2; j++) { + Right[j] = buff[middle + 1 + j]; + } + + int i = 0; + int j = 0; + int k = left; + + while (i < n1 && j < n2) { + if (!(grater(Left[i], Right[j]))) { + buff[k] = Left[i]; + i++; + } else { + buff[k] = Right[j]; + j++; + } + k++; + } + + while (i < n1) { + buff[k] = Left[i]; + i++; + k++; + } + + while (j < n2) { + buff[k] = Right[j]; + j++; + k++; + } + + delete[] Left; + delete[] Right; + } + + template + static void mergeSort(Type* buff, int left, int right, bool (*grater)(const Type& obj1, const Type& obj2)) { + + if (left >= right) { + return; + } + + int middle = left + (right - left) / 2; + + mergeSort(buff, left, middle, grater); + mergeSort(buff, middle + 1, right, grater); + merge(buff, left, middle, right, grater); + } + }; + + struct SortInsert { + template + static void sort(Type* buff, int length, bool (*grater)(const Type& obj1, const Type& obj2) = &compare) { + for (int i = 0; i < length; i++) { + for (int j = i + 1; j < length; j++) { + if (grater(*buff[i], *buff[j])) { + swap(buff[i], buff[j]); + } + } + } + } + }; } \ No newline at end of file diff --git a/Utils/public/Testing.hpp b/Utils/public/Testing.hpp index 25f76c2..e271f77 100644 --- a/Utils/public/Testing.hpp +++ b/Utils/public/Testing.hpp @@ -6,7 +6,6 @@ namespace tp { class Testing { public: - struct FailedCheck { const char* expression = nullptr; const char* file = nullptr; @@ -23,7 +22,10 @@ namespace tp { private: struct TestingNode { - struct FailedCheckRecord { FailedCheck failedCheck; ualni times; }; + struct FailedCheckRecord { + FailedCheck failedCheck; + ualni times; + }; List mFailedChecks; List mSubTests; const char* mName = "Unnamed"; @@ -42,24 +44,28 @@ namespace tp { extern Testing gTesting; } -#define TEST_DEF(Name)\ - static void Name##FunctorBody();\ - void test##Name() { \ - tp::gTesting.startTest(#Name);\ - Name##FunctorBody();\ - tp::gTesting.endTest();\ - } \ +#define TEST_DEF(Name) \ + static void Name##FunctorBody(); \ + void test##Name() { \ + tp::gTesting.startTest(#Name); \ + Name##FunctorBody(); \ + tp::gTesting.endTest(); \ + } \ void Name##FunctorBody() -#define TEST_DEF_STATIC(Name)\ - static void Name##FunctorBody();\ - static void test##Name() { \ - tp::gTesting.startTest(#Name);\ - Name##FunctorBody();\ - tp::gTesting.endTest();\ - } \ +#define TEST_DEF_STATIC(Name) \ + static void Name##FunctorBody(); \ + static void test##Name() { \ + tp::gTesting.startTest(#Name); \ + Name##FunctorBody(); \ + tp::gTesting.endTest(); \ + } \ void Name##FunctorBody() -#define TEST(expr) if (!(expr)) tp::gTesting.addFailedCheck({ #expr, __FILE__, __LINE__ }) -#define TEST_ASSERT(expr) TEST(expr); if (!(expr)) return -#define TEST_EQUAL(l, r) if (!((l) == (r))) tp::gTesting.addFailedCheck({ #l" == "#r, __FILE__, __LINE__ }) +#define TEST(expr) \ + if (!(expr)) tp::gTesting.addFailedCheck({ #expr, __FILE__, __LINE__ }) +#define TEST_ASSERT(expr) \ + TEST(expr); \ + if (!(expr)) return +#define TEST_EQUAL(l, r) \ + if (!((l) == (r))) tp::gTesting.addFailedCheck({ #l " == " #r, __FILE__, __LINE__ }) diff --git a/Utils/public/Timing.hpp b/Utils/public/Timing.hpp index f37f1f1..3909bfd 100644 --- a/Utils/public/Timing.hpp +++ b/Utils/public/Timing.hpp @@ -15,7 +15,6 @@ namespace tp { time_ms mDuration; public: - Timer(); explicit Timer(time_ms time); @@ -41,7 +40,8 @@ namespace tp { Timer time; halni fps = 0; - FpsCounter() : time(1000) {} + FpsCounter() : + time(1000) {} void update(bool log = true) { frames++; diff --git a/Utils/public/Utils.hpp b/Utils/public/Utils.hpp index de49a7b..9cdc4f6 100644 --- a/Utils/public/Utils.hpp +++ b/Utils/public/Utils.hpp @@ -1,120 +1,126 @@ -#pragma once - -#include "Module.hpp" - -#define PTR_OFFSET(first, offset) (*((&first) + offset)) -#define MEMBER_OFFSET(s, m) (alni(&(((s*) 0)->m))) - -namespace tp { - - extern ModuleManifest gModuleUtils; - - void memSetVal(void* p, uhalni byteSize, uint1 val); - void memCopy(void* left, const void* right, uhalni len); - int1 memCompare(const void* left, const void* right, uhalni len); - bool memEqual(const void* left, const void* right, uhalni len); - int1 memCompareVal(const void* left, uhalni len, uint1 val); -} - -namespace tp { - [[nodiscard]] alnf randomFloat(); -} - -namespace tp { - - template - class Pair { - public: - Pair() = default; - - template - Pair(U1 t1, U2 t2) : head(static_cast(t1)), - tail(static_cast(t2)) {} - - union { - T1 t1; - T1 head; - T1 x; - }; - - union { - T2 t2; - T2 tail; - T2 y; - }; - - bool operator==(const Pair& in) const { return in.t1 == t1 && in.t2 == t2; } - - bool operator!=(const Pair& in) const { return !this->operator==(in); } - }; - - template - class Bits { - Type mFlags = 0; - - public: - Bits() = default; - - explicit Bits(Type val) { mFlags = val; } - - explicit Bits(bool val) { - for (int bit = 0; bit < sizeof(Type); bit++) { - set(bit, val); - } - } - - bool get(int1 idx) { return mFlags & (1l << idx); } - - void set(int1 idx, bool val) { - if (val) { - mFlags |= (1l << idx); - } else { - mFlags &= ~(1l << idx); - } - } - }; - - template - class Range { - public: - class Iterator { - public: - tType mIndex; - - explicit Iterator(tType pStartIndex) : mIndex(pStartIndex) {} - - tType index() const { return mIndex; } - - inline void operator++() { mIndex++; } - - inline operator tType() const { return mIndex; } - - inline bool operator==(Iterator pIndex) { return mIndex == pIndex.mIndex; } - - inline bool operator!=(Iterator pIndex) { return mIndex != pIndex.mIndex; } - - inline const Iterator& operator*() { return *this; } - }; - - tType mBegin = 0; - tType mEnd = 0; - - Range() = default; - - explicit Range(tType pEndIndex) : mBegin(0), mEnd(pEndIndex) {} - - Range(tType pStartIndex, tType pEndIndex) : mBegin(pStartIndex), mEnd(pEndIndex) {} - - bool valid() { return mBegin < mEnd; } - - tType idxBegin() const { return mBegin; } - - tType idxEnd() const { return mEnd; } - - tType idxDiff() const { return mEnd - mBegin; } - - Iterator begin() { return Iterator(mBegin); } - - Iterator end() { return Iterator(mEnd); } - }; -} +#pragma once + +#include "Module.hpp" + +#define PTR_OFFSET(first, offset) (*((&first) + offset)) +#define MEMBER_OFFSET(s, m) (alni(&(((s*) 0)->m))) + +namespace tp { + + extern ModuleManifest gModuleUtils; + + void memSetVal(void* p, uhalni byteSize, uint1 val); + void memCopy(void* left, const void* right, uhalni len); + int1 memCompare(const void* left, const void* right, uhalni len); + bool memEqual(const void* left, const void* right, uhalni len); + int1 memCompareVal(const void* left, uhalni len, uint1 val); +} + +namespace tp { + [[nodiscard]] alnf randomFloat(); +} + +namespace tp { + + template + class Pair { + public: + Pair() = default; + + template + Pair(U1 t1, U2 t2) : + head(static_cast(t1)), + tail(static_cast(t2)) {} + + union { + T1 t1; + T1 head; + T1 x; + }; + + union { + T2 t2; + T2 tail; + T2 y; + }; + + bool operator==(const Pair& in) const { return in.t1 == t1 && in.t2 == t2; } + + bool operator!=(const Pair& in) const { return !this->operator==(in); } + }; + + template + class Bits { + Type mFlags = 0; + + public: + Bits() = default; + + explicit Bits(Type val) { mFlags = val; } + + explicit Bits(bool val) { + for (int bit = 0; bit < sizeof(Type); bit++) { + set(bit, val); + } + } + + bool get(int1 idx) { return mFlags & (1l << idx); } + + void set(int1 idx, bool val) { + if (val) { + mFlags |= (1l << idx); + } else { + mFlags &= ~(1l << idx); + } + } + }; + + template + class Range { + public: + class Iterator { + public: + tType mIndex; + + explicit Iterator(tType pStartIndex) : + mIndex(pStartIndex) {} + + tType index() const { return mIndex; } + + inline void operator++() { mIndex++; } + + inline operator tType() const { return mIndex; } + + inline bool operator==(Iterator pIndex) { return mIndex == pIndex.mIndex; } + + inline bool operator!=(Iterator pIndex) { return mIndex != pIndex.mIndex; } + + inline const Iterator& operator*() { return *this; } + }; + + tType mBegin = 0; + tType mEnd = 0; + + Range() = default; + + explicit Range(tType pEndIndex) : + mBegin(0), + mEnd(pEndIndex) {} + + Range(tType pStartIndex, tType pEndIndex) : + mBegin(pStartIndex), + mEnd(pEndIndex) {} + + bool valid() { return mBegin < mEnd; } + + tType idxBegin() const { return mBegin; } + + tType idxEnd() const { return mEnd; } + + tType idxDiff() const { return mEnd - mBegin; } + + Iterator begin() { return Iterator(mBegin); } + + Iterator end() { return Iterator(mEnd); } + }; +} diff --git a/Utils/tests/Tests.cpp b/Utils/tests/Tests.cpp index d3e1a49..8bb9bcc 100644 --- a/Utils/tests/Tests.cpp +++ b/Utils/tests/Tests.cpp @@ -1,7 +1,7 @@ -#include "Utils.hpp" #include "Debugging.hpp" #include "Testing.hpp" +#include "Utils.hpp" #include @@ -16,9 +16,7 @@ void printSnapshot(const tp::CallStackCapture::CallStack* snapshot) { printf("\n"); } -void common() { - auto tmp = gCSCapture->getSnapshot(); -} +void common() { auto tmp = gCSCapture->getSnapshot(); } void first() { common();