Skip to content

Commit

Permalink
midsave
Browse files Browse the repository at this point in the history
  • Loading branch information
SpazElectro committed Sep 3, 2023
1 parent cc0cfa7 commit 810c4a7
Show file tree
Hide file tree
Showing 17 changed files with 468 additions and 48 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,6 @@ token.txt
build
/experiments/hotreload/udp/*
/experiments/hotreload/tcp/*
/experiments/hotreload/combined/*
/experiments/hotreload/combined/*
/experiments/jj2livestream/bin
/experiments/jj2livestream/obj
3 changes: 2 additions & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"esbenp.prettier-vscode",
"michelemelluso.gitignore",
"ms-python.vscode-pylance",
"ms-vscode.cpptools"
"ms-vscode.cpptools",
"ms-dotnettools.csdevkit"
]
}
1 change: 1 addition & 0 deletions experiments/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
proxy/*.*
proxy/*
proxy
hotreload/animatepacketsamples
44 changes: 33 additions & 11 deletions experiments/hotreload/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,32 +139,54 @@ def udp_recv():
pingPacket = bytes(bytearray([0x03, last_pong, 0x00, 0x00, 0x00, 0x00, 0x32, 0x34, 0x20, 0x20]))
udp_client.sendto(b"\xA7\xD2" + pingPacket, server_address)

# animation packet (checksum excluded):
# id cu s cu s s cu cu cu cu cu cu cu s s
# 01 67 01 29 00 00 10 5D 80 AC 02 1E 02 00 00

def ping_server():
global END_CLIENT
while not END_CLIENT:
posPacket[-3] += 1
if posPacket[-3] == 5:
posPacket[-3] = 0

if posPacket[5] == 0xB5:
posPacket[5] = 0xB6
else:
posPacket[5] = 0xB5
# posPacket[-3] += 1
# if posPacket[-3] == 5:
# posPacket[-3] = 0
# if posPacket[5] == 0xB5:
# posPacket[5] = 0xB6
# else:
# posPacket[5] = 0xB5

build_keep_alive()
udp_send(posPacket)
time.sleep(1)
print("Sending position packet...")
time.sleep(0.125)

def udp_checksum(buffer):
x = 1
y = 1
x = 79
y = 79
for i in range(2, len(buffer)):
x += buffer[i]
y += x
buffer[0] = x % 251
buffer[1] = y % 251

# dont ask why we have 2
def compute_checksum(buffer):
L = R = 1
for n in range(2, len(buffer)):
L += buffer[n]
R += L
return bytes([L % 251]) + bytes([R % 251])

from construct import Int16ul

def build_keep_alive(data, udp_count):
prefix = bytes(1) + Int16ul.build(len(data))
udp_checksum = compute_checksum(data)
return prefix + udp_checksum + data

def udp_send(data):
udp_checksum(data)
# print(data)
udp_client.sendto(data, server_address)

udp_thread = threading.Thread(target=udp_recv)
Expand Down
35 changes: 28 additions & 7 deletions experiments/hotreload/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import threading
import uuid
import os
import hexdump

# Configuration
proxy_host = "127.0.0.1"
Expand All @@ -10,11 +11,15 @@
jj2_host = "127.0.0.1"
jj2_port = 10052

proxyfileindex = 0

# BUFFER_SIZE = 16384
BUFFER_SIZE = 32768

proxyfileindex = 0
USE_COMBINED_FOLDER = False
ASK_INPUT_TCP = False
ASK_INPUT_UDP = False
LOG_TCP_PACKETS = False
LOG_UDP_PACKETS = False

END_PROXY = False

Expand All @@ -28,7 +33,7 @@ def udp_proxy():
jj2_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
global proxyfileindex, END_PROXY
global proxyfileindex, END_PROXY, LOG_UDP_PACKETS
data: bytes = b""

try:
Expand All @@ -47,13 +52,21 @@ def forward_udp_to_jj2():
print(data)
udp_sock.sendto(response, client_addr)

if input(b"UDP " + bytearray(data)) == "y":
open(f"udp/{sessionuid}/{proxyfileindex}" if not USE_COMBINED_FOLDER else f"combined/udp{proxyfileindex}", "wb").write(data)
if ASK_INPUT_UDP:
if input(b"UDP " + bytearray(data)) == "y":
open(f"udp/{sessionuid}/{proxyfileindex}" if not USE_COMBINED_FOLDER else f"combined/udp{proxyfileindex}", "wb").write(data)
else:
if LOG_UDP_PACKETS:
print(f"UDP {hexdump.hexdump(data, result='return')}")
if data[2] == 0x01:
open(f"animatepacketsamples/{proxyfileindex}", "wb").write(data)
proxyfileindex += 1
proxyfileindex += 1

udp_thread = threading.Thread(target=forward_udp_to_jj2)
udp_thread.start()


def tcp_proxy():
tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_sock.bind((proxy_host, proxy_port))
Expand All @@ -70,13 +83,21 @@ def forward_tcp_to_jj2():

def forward_data(sock1, sock2):
while True:
global proxyfileindex
global proxyfileindex, LOG_TCP_PACKETS, LOG_UDP_PACKETS
data: bytes = sock1.recv(BUFFER_SIZE)
if END_PROXY: break

if sock1 is client_sock:
if sock1 is client_sock and ASK_INPUT_TCP:
if input(b"TCP " + bytearray(data)) == "y":
open(f"tcp/{sessionuid}/{proxyfileindex}" if not USE_COMBINED_FOLDER else f"combined/tcp{proxyfileindex}", "wb").write(data)
else:
if LOG_TCP_PACKETS and sock1 is client_sock:
print(f"TCP {hexdump.hexdump(data, result='return')}")
if sock1 is jj2_sock:
if data[1] == 0x49:
print("Spotted newping packet!")
LOG_TCP_PACKETS = True
LOG_UDP_PACKETS = True
proxyfileindex += 1

if not data:
Expand Down
180 changes: 180 additions & 0 deletions experiments/jj2livestream/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
//This example will show you how to:
//- Add jj2 client events.
//- Connect to & disconnect from a JJ2 server.
//- Log player messages, joining/leaving notifications, and loaded level name.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using JJ2ClientLib.JJ2;

using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Windows.Forms;

namespace jj2livestream
{
internal class Program
{
public static JJ2Client jj2 = new JJ2Client();

static byte[][] CaptureScreen()
{
// Capture the screen
using (Bitmap screenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height))
{
using (Graphics g = Graphics.FromImage(screenCapture))
{
g.CopyFromScreen(Point.Empty, Point.Empty, Screen.PrimaryScreen.Bounds.Size);
}

// Create a two-dimensional byte array to store encoded pixel colors
byte[][] encodedPixels = new byte[screenCapture.Width][];

for (int x = 0; x < screenCapture.Width; x++)
{
encodedPixels[x] = new byte[screenCapture.Height * 3]; // 3 bytes for R, G, and B per pixel

for (int y = 0; y < screenCapture.Height; y++)
{
Color pixelColor = screenCapture.GetPixel(x, y);
byte[] colorBytes = EncodeColor(pixelColor);

// Store the encoded color bytes in the array
encodedPixels[x][y * 3] = colorBytes[0]; // Red
encodedPixels[x][y * 3 + 1] = colorBytes[1]; // Green
encodedPixels[x][y * 3 + 2] = colorBytes[2]; // Blue
}
}

return encodedPixels;
}
}

static byte[] EncodeColor(Color color)
{
// Define a custom palette of colors (you can add more colors as needed)
Color[] palette = new Color[]
{
Color.Black,
Color.Red,
Color.Green,
Color.Blue,
Color.Yellow,
Color.Magenta,
Color.Cyan,
Color.White
};

byte[] colorBytes = new byte[3]; // Exclude alpha channel

// Find the closest color in the palette to the input color
Color closestColor = FindClosestColor(color, palette);

// Encode the closest color components into bytes
colorBytes[0] = closestColor.R;
colorBytes[1] = closestColor.G;
colorBytes[2] = closestColor.B;

return colorBytes;
}

static Color FindClosestColor(Color targetColor, Color[] palette)
{
Color closestColor = palette[0];
int closestDistance = ColorDistance(targetColor, palette[0]);

for (int i = 1; i < palette.Length; i++)
{
int distance = ColorDistance(targetColor, palette[i]);
if (distance < closestDistance)
{
closestColor = palette[i];
closestDistance = distance;
}
}

return closestColor;
}

static int ColorDistance(Color color1, Color color2)
{
int deltaR = color1.R - color2.R;
int deltaG = color1.G - color2.G;
int deltaB = color1.B - color2.B;
return deltaR * deltaR + deltaG * deltaG + deltaB * deltaB;
}

static byte[] ConvertToByteArray(byte[][] encodedPixels)
{
// Flatten the two-dimensional array into a single-dimensional array
return encodedPixels.SelectMany(row => row).ToArray();
}

public static void Main(string[] args)
{
jj2.Level_Initialized_Event += onLevelInitialize;
jj2.Connected_Event += onConnect;
jj2.Disconnected_Event += onDisconnect;
jj2.Failed_To_Connect_Event += onConnectFail;

//Connect to JJ2 server
string serverAddress = "localhost"; //127.0.0.1 (This machine)
UInt16 serverPort = 10052; //default JJ2 game port
Console.WriteLine(String.Format("* * * Connecting to [{0}]...", serverAddress));
jj2.JoinServer(serverAddress, null, "Livestreamer", serverPort);

//wait for user to press ESC key
while (true)
{
// if (Console.ReadKey().Key == ConsoleKey.Escape)
// {
// //Disconnect and release resources
// jj2.Leave();
// jj2.Dispose();
// break;
// }

// get all pixels onto the screen and put into an array and send thro jj2.sendpluspacketstream
// byte[] pixels = ConvertToByteArray(CaptureScreen());
byte[] testBytes = new byte[5];
testBytes[0] = 1;
testBytes[1] = 2;
testBytes[2] = 3;
testBytes[3] = 4;
testBytes[4] = 5;

jj2.SendJJ2PlusNetworkStream(testBytes, 0);

System.Threading.Thread.Sleep(10000);
}
}

private static void onLevelInitialize(string levelName, string yourName, byte yourID, byte yourSocketIndex, object user)
{
string line = string.Format("* * * Level begin [{0}] at [{1}]", levelName, DateTime.Now.ToString());
Console.WriteLine(line);
}

private static void onConnect(string serverIPAddrees, string serverAddress, ushort serverPort, object user)
{
string line = string.Format("* * * Connected to [{0}:{1}]", serverAddress, serverPort.ToString());
Console.WriteLine(line);
}

private static void onDisconnect(JJ2_Disconnect_Message disconnectMessage, string serverIPAddrees, string serverAddress, ushort serverPort, object user)
{
string line = string.Format("* * * Disconnected from [{0}:{1}] at [{2}] with reason [{3}]", serverAddress, serverPort.ToString(), DateTime.Now.ToString(), disconnectMessage.ToString());
Console.WriteLine(line);
}

private static void onConnectFail(string serverAddress, ushort serverPort, object user)
{
string line = string.Format("* * * Unable to connect to [{0}:{1}] ", serverAddress, serverPort.ToString());
Console.WriteLine(line);
}
}
}
20 changes: 20 additions & 0 deletions experiments/jj2livestream/jj2livestream.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PlatformTarget>x86</PlatformTarget>
<UseWindowsForms>True</UseWindowsForms>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="../jj2pyclient/reference/JJ2ClientLib/JJ2ClientLib/JJ2ClientLib.vbproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="System.Drawing.Common" Version="7.0.0" />
</ItemGroup>

</Project>
Submodule JJ2ClientLib updated from 000000 to 48c216
1 change: 1 addition & 0 deletions experiments/jj2pyclient/reference/jj2_deprecated
Submodule jj2_deprecated added at 62cca1
19 changes: 19 additions & 0 deletions experiments/packagemanager/site/cdn/packages/testpkg/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "testpkg",
"author": "Gamer",
"repository": {
"url": "https://www.github.com/Gamer/testpkg",
"type": "git"
},
"stats": {
"stars": 0,
"downloads": 0,
"views": 0
},
"dependencies": {
"stvutil": "^1.0.0"
},
"dependants": [
"stvhooks"
]
}
Loading

0 comments on commit 810c4a7

Please sign in to comment.