#development
1 messages Β· Page 102 of 1
pog, now you can render text
So can someone maybe help
Sorry, I totally don't understand this code and I don't see how something like this could work without awaitMessages or a collector. Also you have
if(embed) return message.channel.send()
in your code which will probably always be "true" so your whole command will always stop there with return
You can correct me, but at least that's what it looks like to me
I have a collector
Okay, and how should if(embed) return message.channel.send() work?
as you can see embed says "Welcome channel has been set to ${channel.name}!" and if that embed is sent the bot will send the embed where it says "enter the welcome message now" but my problem is that if the welcome message is entered the bot will react with "Done!" or something like that
But your command ends there because you have return
This whole if(embed) thing is useless, you just send embed3 the same way you sent embed a few lines above
can i just move embed3 to above the message.reply and then do message.reply({ embeds: [embed], [embed3] })
It's more like message.reply({embeds: [embed, embed3]})
oh lmao whoops
Or you can combine these two embeds into one
na
okay but now one more thing
how can i send the doneEmbed after the welcome message has been entered
Are you sure that else works at all?
please press alt + F or whatever the format shortcut is for vscode
i dont use vscode xd
what editor is that?
Fluid Nodes provides you with high quality hardware and cheap hosting. Game Hosting, Discord Bot Hosting and much more.
ig it does but i can try to end the else befor the doneEmbed
Personally, it's the first time I see such an else in javascript
how would you do it
if(something) {
return
} else {
// do whatever else
}
Also you would like to do something with the existing embed when someone actually typed "cancel". Something like removing the old embed and sending a new one with a message that the command got canceled or editing the existing embed because users may think that the bot is broken
For textures Iβm pretty sure GL_ONE_MINUS_SRC_ALPHA is the best option
not textures, just shapes
I'll send u a screenshot of what I mean later
but basically, translucent parts are either going color -> black/white -> transparent
not color -> transparent
yeah I haven't gotten that far in opengl
your knowledge is far beyond mine at this point
eh
ChatGPT for writing advanced SQL queries is... 
I wonder how good it is at regex π
actually u just gave me the idea to ask chartgpt how to fix my opengl issues
Oh yeah?
I'm saving so much time doing data analysis right now
I'm querying my bot's db to figure out when people prefer to use prefixed commands over slash commands and there's a lot of counting, grouping, alias merging, ratio calculations and sorting to do and it's flying through the statements
it wrote two statements that threw an error but just pasting the error back into it gave me a fixed version
it's a massive timesaver
obscure opengl issues might not work for it but you can give it a shot
Thats what I've found too, for sql its pretty neat
I used it to generate simulated data
It wrote this function
-- function random_id creates a random id
CREATE OR REPLACE FUNCTION random_id(min_val INT=17, max_val INT=21)
RETURNS text AS
$$
DECLARE
word_length NUMERIC = floor(random() * (max_val-min_val) + min_val)::INTEGER;
random_word TEXT = '';
BEGIN
-- only if the word length we get has a remainder after being divided by 5. This gives
-- some randomness to when words are produced or not. Adjust for your tastes.
IF(word_length % 5) > 1 THEN
SELECT * INTO random_word FROM (
WITH symbols(characters) AS (VALUES ('0123456789'))
SELECT string_agg(substr(characters, (random() * length(characters) + 1) :: INTEGER, 1), ''), 'g1' AS idx
FROM symbols
JOIN generate_series(1,word_length) AS word(chr_idx) on 1 = 1 -- word length
group by idx) a;
END IF;
RETURN random_word;
END
$$ LANGUAGE 'plpgsql';
and this to create simulated data, creating rows more frequently over a period of a year.
WITH simulated_data
AS
(with recursive t(time) as (
select now() - interval '1 year'
union all
select time + justify_interval(
make_interval(
secs => (
random() * (
(interval_to_seconds(age(now(), time))) /
(interval_to_seconds(age(now(), now() - interval '1 year')))
) *
(interval_to_seconds(interval '5 minutes'))
)
)
)
from t
where time < now()
)
select
time,
918872882472439838 AS entityid,
random_id(17,19) AS userid
from t
limit 1000000
)
INSERT INTO vote (time, entityid, userid)
SELECT time, entityid, userid FROM simulated_data;
Its not perfect, but it was really neat.
Awesome! That is super useful for beta testing a bot feature π
I'm currently working out which of my commands have the most use for prefixes vs slash commands:
SELECT
CASE
WHEN command = 'pu' THEN 'pickup'
WHEN command = 'tod' THEN 'truthordare'
WHEN command = 'hg' THEN 'hangrygames'
ELSE command
END AS command_alias,
COUNT(CASE WHEN type = 'message' THEN 1 ELSE NULL END) AS message_count,
COUNT(CASE WHEN type = 'slash' THEN 1 ELSE NULL END) AS slash_count,
CASE
WHEN COUNT(CASE WHEN type = 'slash' THEN 1 ELSE NULL END) = 0 THEN NULL
ELSE COUNT(CASE WHEN type = 'message' THEN 1 ELSE NULL END)::float / COUNT(CASE WHEN type = 'slash' THEN 1 ELSE NULL END)
END AS ratio
FROM logs
WHERE type IN ('message', 'slash')
AND timestamp BETWEEN NOW()::timestamp - (INTERVAL '30D') AND timestamp
GROUP BY
CASE
WHEN command = 'pu' THEN 'pickup'
WHEN command = 'tod' THEN 'truthordare'
WHEN command = 'hg' THEN 'hangrygames'
ELSE command
END
ORDER BY ratio DESC NULLS LAST;
Yes my db is a bit jank
But yeah it's ordering them all by ratio so I can see which ones get used with prefixes more often
And I'm actually surprised by the results
thats useful π
Ultimately with ChatGPT, you still need to know what to ask for to get the results you need, so you still need an understanding of how to get it, you just don't need to know how to write the SQL statements themselves 
It at least gets you on the right train
I had to do a few edits a few times, but thats fine
Also some of what it gave me was a bit weird so I simplified it
WHEN command = 'pu' THEN 'pickup'
WHEN command = 'tod' THEN 'truthordare'
WHEN command = 'hg' THEN 'hangrygames'
π yeah
It's like copilot but for everything 
So i got pm2 running on one of my vps's where one of my bots is hosted. The bot was off while pm2 was showing no errors on its logs and it looked like it still was on
I had to restart the bot to get it back up
Is it normal?
the ws connection could have broken and then gotten terminated so, it's likely
I just found out from my data that at least 4 of the top 10 servers using prefixes over the last 30 days are Turkish
I had no idea I had such a large Turkish userbase I'm stunned π
for the longest time, my user base was korean until recently it mostly became russian
probably because I have a russian translation
They've also been going hard over the last 30 days
Is there a way to prevent it? Some of these bots are for my customers can't check on them all the time
I'm literally at the point now where I'm getting so much value out of ChatGPT I would literally be more than happy to pay for it tbh
You're kinda at the mercy of Discord's gateway, but if the gateway lib can catch itself and recover, there should be no issue
And apparently, shipping, kissing and hugging is all Turkey wants to do 

Any Turkish users out there who might be able to shed some light as to why my Turkish users hate slash commands?
I'm very curious
Idk if it's a question of Discord not doing a good job at promoting them outside of English-speaking users or what?
It has made me lazy af
I should prolly stop using it at some point
I mean, there's some stuff I just don't have the time to learn and regex or sql are some of them
Yeah! I think it's useful for stuff you're not interested in learning
π its worth paying for it from what I understand
What are the benefits of paid?
mostly faster responses iirc
It does teach u but at the same time makes you lazy
Ah
Faster and prolly larger responses
It's fast and accurate enough for me on the free version
And limits are much larger
There are limits?
Ofc seems like u haven't been hit by one
Yeah I'm not a heavy user
You wont be able to use it for around 30 minutes
tbh, for programming stuff, you dont need a ton
It depends from the complexity of the qudstions
Yeah ^
And i haven't really been hit with the limit lately
Which is weird
I still prefer bing ai, same thing just has search
and having access to seperate modes is nice
Isn't that very limited
10 requests per conversation, 150 per day iirc
The new gpt will have around 100 trillion params
They use their api?
Oh didn't know
170
invested?
kek
https://i.imgur.com/t8l1dRN.png
this is really nice depending on what I'm looking for
more precise for newer things, like if I want to ask about nextjs app directory itll search for it.
More balanced for everything thats 2 years old+
so general coding questions, sql stuff etc.
Lovely
GitHub Copilot uses the OpenAI Codex to suggest code and entire functions in real-time, right from your editor.
π I noticed copilot has trouble with standalone stuff.
It's also hard to do followup stugg
Stuff*
Like "when I ran the code you gave me I got this error"
Chatgpt and bingai seem to do really good with those things
Plus, tbh even when copilot was free I had to turn it off.
The constant suggestions just was awful
yah it keeps suggesting the most random things
Yeah, copilot I don't think you can ever do that?
Ah well. I tried to trick it.
Lmao
if you use a macbook/imac i recommend downloading raycast
of course i do
HSAPHIFA
confetti too
ok
Sounds fancy
is that in spotlight? π
no
no it's not
omw
i set my keybind to double tapping option key
dictionary too
github stuff on there too
and theres meme gen
lmfao
or dvd menu!
that is cursed
how do i do a chatgpt search with this?
theres a chatgpt thing in the store (free)
this is amazing
its so clean
why do i feel like a boomer whose grandson is explaining something to? 
lol
THIS
Generate discord time stamp seems really useful
yeah its great
Is that Mac only?
supports youtube music
AMAZING
yeah it is
omg i should make a phish.gg thing
check scam invites lul
saves me using /inviteinfo -> checking in browser
Reminds me a bit of the command picker in the obsidian notepad (which you should download if you haven't already)
Can you make your own private plugins for this?
yes
There's an API I guess?
Start building your perfect tools with the Raycast API.
i love that if i'm working and i like a song i can just hit my hotkey and type "radio"
lol
Thanks for the recommendation π
The emoji search is pretty neat too but it's not as quick as the native keyboard shortcut
It has a global colour picker?
This is great
Do you use paste @spark flint?
Nope
But might have to look into it
holy that looks nice
@rose warren https://www.raycast.com/ai 
very nice
i love the raycast api
Not learning regex may cost you quite heavily down the line. I do not proclaim myself an expert in regex, but I did make one that extracts info from JS error stacks.
If you ever find some time to fiddle with regex, a really fun site I found is https://regexr.com
It explains regex operators pretty clearly imo
just finished my bot! now i just gotta wait for it to get approved π
I wish this is available for windows tooβ¦
bruh resume is resume but resume is also resume from pause/resume
teach that to an ai model
Its all about the context
You won't just say, hey check out my resume and people will think you aren't talking about a document displaying your qualifications
Its obvious what it is if the context is correct
what is the requirements and process of getting your bot verified?
Through?
what are the requirements of getting your bot verified?
and what are the process do i need to go through to get it verified?
Are you asking how to get your bot on top.gg or verified on discord
A lot of people confuse getting your bot on topgg with a verification thing
discord.
You will get a message at 75+ servers about a verification process, just follow the instructions in that message
hmm
Then you'll have to wait for them to process your application, which is not a guarantee you will be accepted
ok
Prepare a photo of your ID card, driving license or passport from both sides right away because they require it for each verification
Do they actually?
yes
Makes sense
Prevents people from just spam creating bots and then getting em verified
wow
i need an ID card
why the expires in showing me that its going to be expires in a weird date?
your using milliseconds
it should be in seconds
so divide it by 1000 and round it
<t:${Math.round(Date.now() + timeoutDurationMS / 1000)}:R>
i did
<t:${Math.round((Date.now() + timeoutDurationMS) / 1000)}:R>
oh
yes order of operations it'll do timeoutDurationMS / 1000 first
fun fact: Date.now returns time in milliseconds
@sharp geyser has been stinky for <t:50000>
I tried
Hi
Hi
that is uncalled for
same
time to report you to nom
@drowsy crag aurel bully me
guys while i'm here i might as well ask a question
what is it
can i do a different timezone with .toLocaleDateString() ?????????????????????????????????????
user an international formatter
why is there so many question marks
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options that options param conforms to these
scroll down till you see options or press CTRL + F and search timeZone
this changes depending on the locale that's installed on the user's machine
so that alone works
while this is true but that is not helpful for something like a bot
^
It would always conform to the systems timezone then and not let people view their own if thats what he is wanting
then use it
that require you to know the user's preferred language / timezone though
IANA time zones
let the user set it themselves
nvm found
yah i am
https://www.iana.org/time-zones there is this but have fun
it requires you to download the database yourself and sift through them
sadge
yeah i'm ok
whats the best way to store these timezones
if i put it in my code i'll have 600 extra lines
store in idk
true
when i put it in json i get error
format the damn string bruh
what does that mean
you process that string so it become valid json code
does live share share the directory env files too?
it share everything in the workspace
oh
Ello, I'm working on a new type of economy bot(minecraft based) with proper upgrades etc(don't wanna get into details as this ain't what the message is about), anyway, long story short the bot has a decent amount of dms that could be considered "dm-advertising"(like itll dm you if theres an event running explaining the event, also giving the invite to the bots discord server since thats where events are held), and a bunch of other things like when a major update happens and so on. Now I know normally this is frowned upon, but I'm curious if this is ok since I've made all of the dm messages opt-outtable(like it'll clearly state in the footnote what command to use to stop recieving dms about that feature), and also a bunch of settings to enable certain dm messages(default turned off but if enabled can remind about voting etc). Anyway, I'm just curious if dm messages are allowed as long as all of them are clear and easy to opt-out of, and any more niche ones are off by default and require you to opt-in. Furthermore, when you run the initial startup command it will send you a few dms, explaining the general important commands, features etc. It'll also explain the dm messaging and give you a list of all enabled ones and the commands to opt-out of them. Summary : are dm messages ok(some including advertising links like voting and main server), if most of them are off by default requiring an opt-in, and the ones on by default clearly state how to opt-out of them when they are sent?
sorry about long post lol just curious before i continue with the development of my bot
i aint reading allat
I use regex maybe once a year at most so it's not worth my time
but I appreciate the resource! Looks super helpful
DM ads are against TOS
As is using a bot for advertising in general
also sending out mass dms is very likely going to get your bot flagged
ok so no advertising a bot event/event?
I see your point, so maybe just send a dm explaining a new major update or something when a user first executes a command after that update
possibly
you could do what dank memer does
when someone runs a command and there's news it'll send a follow up message like
"There's some news! run blah blah to read it"
The bot's status is there
You'll have to provide more info than that
Including what language for a start 
javascriptttttttttttt
What are you trying to convert to an array?
a list of timezones seperated by a comma
Also, I'd recommend ChatGPT
string.split(regex | string): Array<string>
w chat gpt
yup
thats what chat gpt told me

My bot is not being reviewed its been 4 days
-upto
When will my bot be reviewed?
Currently our average bot reviewal times are around two weeks or more.
Because of this β and because some bots take longer to review than others due to their features β we can't guarantee your bot will be reviewed as quickly as someone else's in the past and we also can't guarantee your bot will be reviewed within that timeframe. There is no exact time for how long bot approval can take. There is no way to check your bot's position in our reviewal queue, but remember you're not first and you're not last!
You may edit your bot's page as much as you like both before and after it's reviewed and this will have no impact on its place in queue.
You can read more about our bot reviewal process in this support article: How the Bot Reviewal Process Works.
In the meantime, please make sure your bot follows all of our Bot Guidelines for a quick and smooth approval!
why does in this code: https://sourceb.in/ROrduEXI8o showing that the index number is -1 even tho its in the database?
index log: -1
and guild log
Are you sure it's -1?
Looks like you're not just returning on if it's -1 but also if its 0
what
pretty sure its -1
If (!index || index === -1)
Will run if index is 0
i logged index and it shows me that its -1
updated code
so what are the value ranges
what is "value ranges"?
what are all possible values given for that check condition
is it only integers that are grater than -1
or is it possible null or undefined
or what
you are being vague
SPIT THE ANSWER
using js, I probably wouldnt even do a typecheck here.
it should be numbers
but why did they find the index
should have gotten the result object directly smh
gtp4
!!!
lua doesn't support multithreading (as in, base lua)
isnt discordia dead asf
Who the hell uses Lua for anything other than modding a few games nowadays
don't make the neovim devs come out
ironically, there's one huge project I know that's written entirely in lua
path of building
which is basically 80% of path of exile's gameplay
Anyone? 
People like lua for quick game scripting for some reason
I mean outside of roblox
I personally donβt understand why but some people do like it
I mean, it's not a script at all
Actually havent touched roblox stuff in ages got bored rather quickly
A powerful build planner for Path of Exile
it's a whole tool
I have no idea how they kept their sanity doing it
especially given how math-heavy path of exile build-making is
did u try debugging it?
yes, see msg right after it lol
an interpreted, dynamic, bare-bones language where c / python / ruby was the alternative
hm, idk then
isn't the py lib unmaintained?
u could just use raw http requests, topgg api is simple enough
that's a good idea, i might have to
it's what I did
my dragndrop acting goofy but it works ig
bro it's so sad, dblpy gives a different error. Rly no working library, github issue opened in 2020 and still relevant lmao
iirc the former maintainer is no longer on topgg
u could try to fork it, I think they'd probably accept a new maintainer
looks neato
ty
hmm
Are you trying to view my site?
yeah
good site 
I didn't pay the vps bill 
gg
what is the site made in?
solidjs
idk what that is but im guessing some shitty react wrapper
just make it a github page and hos tfor free
its not really react at all
https://www.solidjs.com/ it is its own framework that still uses the jsx stuff tho
its a model of react, vue and svelte
I am too lazy to do that
my site literally has nothing but a nav bar
lmao
gg
github pages is making a single cname file update then renaming the repo to you name.github.pages or whatever, p nice if you're worried about money
I might one day if I ever do anything worthy of putting on my site
Right now without any achievements no one will care about who I am
wont have any achievements if you don't go out and make em >:)
Facts which is why I am trying to find the motivation to continue learning C++
based
My goal is by the end of the summer make a small game in unreal using C++
learn the horrors of ncurses and make a terminal based game
also fair
If I am going to go through the horror of learning C++ might as well learn unreal as well
C++ isn't that bad
its not
I said something in mod chat earlier, I wonder if the reason I like bing ai more is because it has been using gpt 4.
Have you seen the presentation they did?
It's insane
but a lot of concepts confuse me cause I am actually putting effort into learning it rather than how i did with js and just make a discord bot and dick around
like what?
They hand drew a website idea(poorly) then asked gpt-4 to write the css html and javascript for it and it worked.
I am using learncpp.com to try and get the basics down and its been going well so far, but I am wondering more about how UB works and what exactly it looks like cause it seems to be formless as it can take any form and you wont know until shit hits the fan
the live stream?
Yeah
yup crazy stuff man
x = x++ is an example of UB
makes u wonder where humanity is going
also bing will surpass google with that one
Just a few more months and we will see bing ai premium with more of these gpt-4 new features.
I will be buying the premium for those features.
microsoft has been on beast mode lately
I dont mind if its $60 a month kek
it's around 30 atm
20usd for chatgpt plus iirc
Bing is still free, but they have to do premium at some point.
they kinda already make extra by putting ads in windows
which as a paid product, shouldn't have ads at all
don't you need to use edge to use bing ai
@lyric mountain are you decent with multithreading in Java? I need to solve a CME Iβm getting by putting a lock on my ECS and Iβm not fully sure about how to go about it. I gotta write an essay for a bit before I can provide more details, was just curious if you have any tips or suggestions
I basically have a call to component.repaint() (every update cycle) which signals the rendering thread from swing to render the frames by reading the data from my ECS, but I basically need to (in js terms) await component.repaint(), however Iβm not sure how to do that entirely
kinda
make repaint return a CompletableFuture
it's the equivalent (although more powerful) of Promise
var lock = new CompletableFuture<>();
themethod {
...
lock.complete(null);
}
return lock;
on the other side: doTheThing().get()
it won't continue until the CF is completed
it's atomic, so it'll work even if u pass it to an entirely unrelated thread
Are you sure? Because the thing is that component.repaint() is being run on my updating/game logic thread, but the actual sequence of methods that leads to is on the swing thread
ye I am, I use that a lot to await stages happening in other threads
Alright Iβll give it a try later when Iβm done with this essay
Swing will execute the task u pass to it, just put lock.complete(null) at the end of said task
Should only take me like an hour and a half or something
sure
the best part about CF is how you can use it to make a thread dependant on another thread's task, but not necessarily the entire thread
like, u can have 2 or more threads that are co-dependant but don't need to wait for the entire thing to finish
Yeah thatβs basically exactly what Iβm looking for because I donβt want the method to continue until Iβve waited for everything to paint
Since my rendering logic within the paintComponent method of the canvas actually loops over the ECS entities
If I get lag while I try to add entities, then it causes a CME because the rendering is still reading data (iterating over the ECS entities with a foreach) in the swing thread and my game thread is adding to the ECS still
CF is fast right?
it's as fast as possible
Perfect
it's basically an atomic switch that stops a thread until you complete it
Exactly what I was looking for
another example of how it's useful:
var lockA = new CompletableFuture<>();
var lockB = new CompletableFuture<>();
Thread 1
-----------------------------
heavyCalculation {
...
var res = lockB.get(); // need the result of the other thread
res.calcSomething();
...
...
lockA.complete(1.21); // allow the other thread to continue
}
Thread 2
-----------------------------
heavyCalculation {
...
lockB.complete(3.1415); // pass the value to the other thread so it can continue
var otherRes = lockA.get(); // now I need it
...
...
doFinalThing(otherRes);
}
this way both threads can do their own things until they need something from the other
making the final result correct even with a ton of threads
Is it advisable to use this even if you donβt care about the return value? Iβd only be using it to block the thread from continuing
it is, just make it return null
yw
u can also extend it to remove the need of needing a return type
I usually just go with Void as the type
Iβll probably just use Void
Yeah
Multithreading is a pain in the ass but itβs actually quite rewarding when it works
yep
btw, if ur using threads to process outscreen data it's better to use ForkJoinThreadPool
Huh π³
FJ threads will "steal" tasks from other threads if there are idle threads while one is taking too long to complete
it's more optimized than WorkStealingThreadPool
Atm I only have a swing thread and a game thread
I havenβt multithreaded the actual engine part of it
ah ic
I shouldnβt need to for now at least
Since this is just for a game my friend and I are making
Java overcomplicates multithreading like every language other than julia tbf
lol
And it seems complex at first but once youβve done it a few times itβs more manageable
I wont dare touch multithreading in c++
C++ multithreading is actually not that bad tbh
They have abstractions similar to Java in modern C++
Like std::future and such
yea but I have no ide what I am doing in C++ yet
so I am stil learning
I havent had much time to actually sit down and use C++ yet tho sadly
hm, future
I have super important deadlines for senior year
it uses the same naming as java
My first multithreaded C++ project was a monkey typewriter
That was fun
Especially because itβs super simple and easy to parallelize
lmao
remember haku?
They donβt have threads do they?
I asked in here about it
No
but roblox engine supports it somehow
it does some black magic under the hood
misty doing some roblox script fuckery
Probably either modified lua engine or worker threads
Might even be something like transpiling
it's a custom engine, Luau
probably offloading the threads to something else
Since I know engines like Unity use stuff like IL2CPP to convert C# IL to c++ code for performance
ye idk what roblox does behind the scenes
I know they use a modified lua tho its called luau
basically typescript but for lua
@lyric mountain another question, how should I share the cf between classes? I have this method, and I need to wait until the repaint method is finished, but I don't know how to wait for it using cf since I don't have control of the repaint method
Would it just be something like ```java
public void update(float dt) {
// Update other systems here
updateInput();
physicsSystem.update(dt);
world.update(dt);
var lock = new CompleteableFuture<Void>();
window.repaint();
lock.complete(null);
}
return it
just a sec
np take as much time as u need
...in my entire update method? I don't understand really, I only need to wait for the window.repaint() call
u can also run update inside it
return CompletableFuture.runAsync(TheClass::update)
oh, it has param
Oh wait I think I understand now, I'll try it but I don't think it'll work
Wait I don't see how this would work, since the repaint() call is happening on another thread
well, the repaint call tells the other thread to do work
repaint returns a cf?
no, that static method
yep, it's basically the way the promise constructor works
u wrap the task in an async task, then u can do whatever u need with it
waffle just found out
ok so it's still not working, I did this: CompletableFuture.runAsync(() -> window.repaint()).get()
It seems like it just does not care about it finishing
well, not like that
you want to pass the task to the renderer, then wait it outside
so u cant create an async task and await it in the same place, it's the same as doing nothing
show what ur passing to swing renderer
just the minimal methods, I just need to know what ur passing to what
So the render system works by iterating over the entities provided to it by the ECS, but the ECS is shared between two threads which causes problems when the rendering falls behind. ```java
public class RenderSystem extends ECSSystem {
public void update(Graphics window) {
for(int entity : entities) {
TransformComponent comp = world.getComponent(entity, TransformComponent.class);
SpriteRenderComponent s = world.getComponent(entity, SpriteRenderComponent.class);
Vec2f drawPos = comp.position.add(s.position);
window.drawImage(s.sprite, (int)drawPos.x, (int)drawPos.y, s.width, s.height, null);
}
}
}
Basically this update method is called in my canvas component that overrides jpanel's paintComponent(Graphics g) method
@Override
public void paintComponent(Graphics window) {
super.paintComponent(window);
Graphics2D graph = (Graphics2D) window;
BufferedImage back = (BufferedImage) (createImage(getWidth(), getHeight()));
Graphics graphToBack = back.createGraphics();
renderSystem.update(graphToBack);
fontRenderSystem.update(graphToBack);
graph.drawImage(back, null, 0, 0);
}
Yeah I know I'm not sharing the graphics between threads, that stays on the render thread only
So the render thread is the main thread, and the game logic thread is spawned in my Game class
and the run method is just a game loop
which calls update on a certain interval
in combination with Thread.sleep for the delay between frames
and where's the async issue?
ideally I'd be able to await the repaint call in the update method here
u can actually do it differently
actually, nvm
ok so, I suppose u want to parallelize because it's making the screen stutter right?
like, why do u need to await the update?
well, not really. The issue is that when I get frame lag (whether it's due to spawning a lot of entities, or just a spike, or something else lags the pc, etc) I can get ConcurrentModificationExceptions because the render system is in the process of accessing a Set of integers from an ECS whilst the update function continues to run and add/remove from the set
Since the Set gets modified in a foreach loop, it causes a lot of exceptions
Basically the renderer and the game loop are falling out of sync
where are u editing entities?
Here's an example of what I mean (ignore the FPS counter, it's wrong because the update method is still called consistently while the frames lag behind): https://gyazo.com/91184c53150e31aba17e7fc72d0943d5
As I spawn a lot of entities and cause lag, I get a TON of exceptions from the event dispatch thread from swing
renderer is reading from entities, falls behind, entities gets updated while it's still reading from it
Well, technically it's from a call in my testing client code whenever the user presses space, I use world.addGameObject(new Bullet(parameters))
But as for what that method actually does, here:
The important part of this code is that it adds to the entities by doing entityManager.createEntity()
ok so, for the iterator issue u can simply make a carbon copy of the list before iterating
List.of(entities)
this will unlink the iterator from that list
isn't that going to be very expensive to call every frame
yes, the other option is wrapping entities in a getter and using synchronized
this will prevent 2 threads from calling getEntities() at the same time
if they do call it, they'll be told to wait until the lock holder releases it
it's fully automatic, u just need to add the keyword
CompletableFuture ain't gonna help in your case since it's not the issue I thought it was
So I would do something more like protected synchronized Set<Integer> getEntities() { return this.entities } in the base class
you should tho put the runtime logic entirely inside that class, leaving only the task of rendering to the frontend
yes
no need for this, it's always implied unless u have another variable with the same name in that scope
ic
ok so I'm still getting a CME so maybe my problem is bigger than I thought
I don't see how this could be a thing..?
Maybe I should just use a traditional lock in the ECSSystem base class
it's because swing executes in it's own thread, but yeah, this will be a complicated issue
the correct approach would be to never touch the set outside of the enclosing class
you can have an internal Graphics2D inside your game
let it render whatever it needs to render then flush to the screen when the render() method is called
u can grab a swing component's g2d by using component.getGraphics()
u just need to make sure to remove the original painComponent() call else it'll override your calls (it'll render a white background on top of ur render)
optionally u can let Graphics2D render in a loop and use a flag to retrieve the current frame
which is what opengl does iirc
yeah ideally I'd be able to remove swing from the equation for anything other than getting graphics from it
since swing is annoying asf
public var frameRequest = null;
public void render() {
BufferedImage canvas = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = canvas.createGraphics();
while (true) {
g2d.fillRect(0, 0, WIDTH, HEIGHT);
...
render your things
...
if (frameRequest != null) {
frameRequest.complete(canvas.createImage(WIDTH, HEIGHT))
frameRequest = null;
}
}
}
for example
tho this will still lag the next frame if too much is going in the render task
but won't lag the program, just the fps
to request a frame you'd call game.frameRequest = new CompletableFuture<>(); from inside swing
Yeah lag is natural in any game, I just don't want to be throwing a ton of CMEs whilst doing it lol
and await it ofc
var frameReq = new CompletableFuture<BufferedImage>();
game.frameRequest = frameReq;
var frame = frame.get();
This is honestly probably 10 million times easier than relying on swing calling the paintComponent method
lmao
I should probably swap over to this
if nothing is there to render it'll skip that frame, so it won't hold the method hostage
u can also go more bananas and make it skip the remaining code if nothing has changed
by having a custom "state" check before starting to render
for example, using your set:
public void render() {
BufferedImage canvas = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = canvas.createGraphics();
Integer prevHash = null;
while (true) {
if (entities.hashCode() == prevHash) continue;
g2d.fillRect(0, 0, WIDTH, HEIGHT);
...
render your things
...
if (frameRequest != null) {
frameRequest.complete(canvas.createImage(WIDTH, HEIGHT))
frameRequest = null;
}
prevHash = entities.hashCode();
}
}
this will skip processing if the result would be the same
ofc you'd need to include the player position and stuff
Technically I can't do it that easy since the entities positions and stuff change yeah
And the position data can change without the set changing
But yeah I see what you're saying
that was just an example considering only the set
u can make a custom data structure or smth to store the previous state
The real question is where would I be drawing to, because I see that there's a bufferedimage and g2d object, but how would that get on to a window?
Since drawing to those alone obviously won't do anything
actually, got an even better idea regarding that
nvm, would not work, but we can continue with the CF idea
public void paintComponent(Graphics g) {
var frameReq = new CompletableFuture<BufferedImage>();
game.frameRequest = frameReq;
g.drawImage(frame.get(), 0, 0, null);
}
Ahh
Iβd still be required to call repaint but this separates the logic out much better since I can call render from the same thread I call my game logic from
Which is an ideal situation because then it executes sequentially
This will prevent the CME entirely cuz you'll never use it outside its thread
Yeah
Only thing swing will do is render the frame
Sweet, Iβm gonna try this rq
Gl
alright I'm failing miserably
What's the issue?
so I've got something like this (the above method is paintComponent)
And I'm using double buffering so that the images don't disappear
Huh? The images shouldn't disappear
but as of right now I'm getting behavior where I can only spawn one bullet and then it's done and won't spawn any more
Did u remove the super call?
Once some lag happens the images start to blink a lot
Also you had it in a while true loop but I'm just assuming that was simulating a game loop
U can also use
SwingUtilities.invokeLater(() -> {
var g = component.getGraphics();
g.drawImage(frame, 0, 0, null);
});
From inside the runtime
Oh wait hold on
And remove CF entirely
I got it working
Oh
Yeah
Apparently having canvas as an instance variable was fucking with everything, even though I was resetting it each time?
U mean the BufferedImage?
Yeah
U shouldn't create it om every iteration, nor redefine it
That's why I called g2d.fillRect(0, 0, WIDTH, HEIGHT)
This will clear the current frame
Problem is that I'm not sure how to deal with it when the user changes the width or height of the canvas
Since I can't seem to find an event listener to resize it
WindowListener
It's a JFrame-specific event
This Swing Java Tutorial describes developing graphical user interfaces (GUIs) for applications and applets using Swing components
Btw, since u have a graphical interface u can later on learn how to use VolatileImage
It's a much faster (and volatile) image type that's processed by the gpu
I'd use it for my game, but it's headless
Now I'm oddly getting a black screen
this is with g2d and canvas being instance variables now
Repaint should be called outside frameRequest
And outside render at all
If ur going to put it outside render, use the swing utilities thing
Just pass the component to tge game and use it to call a screen refresh
Remove frameRequest altogether
^
U need to use invokeLater because Swing dislikes other threads modifying it
yeah seems to like that even less, just completely freezes up
Really?
How are u doing it?
can't even close the window
getFrame just returns the canvas's BufferedImage
oh wait I'm a moron
I'm still using the frameRequest thing in the paintcomponent call hold on
It has to be in the same place as the rendering logic
Also I kinda wrote it wrong, u need to use the component's Graphics
Put a Graphics arg on the render function and call it from inside invokeLater
With your desired delay
yeah sorry my naming is a little bad, window is a class I wrote that extends JFrame which is called Window, which has an instance variable of another class I wrote called Canvas, which contains the render function (and extends JPanel)
The use it for rendering, instead of making a buffereimage
Hm, I think I understood
Yeah use Canvas' Graphics object, instead of making a new bufferedimage and painting it after
No need to do the step twice
render(window.canvas.getGraphics())
It won't freeze the app because it's being rendered async due to invokeLater
There are many ways to approach tbh
well I kinda wanted it to freeze the app because I don't want CMEs
I don't mean that
InvokeLater is kinda sequential, so 2 renders will never execute at the same time
But it doesn't run in the main thread
so it's rendering now, but it's flickering a lot
(also the background is black but that's an easy fix)
Did u remove the component's super call of paint/paintComponent?
Else it'll compete with your rendering
Remove it
That's the only thing I have in there though
U don't need it because you're not using components as component
With it there it'll try to render the background (and other elements inside the comp)
U want that method empty
Still the same issue with flickering
And when the background is black, only one of my bullets renders, but when the background is white, multiple render
super weird
Are u still creating a BufferedImage?
Nope
Drawing directly to the comp's Graphics?
Yup
Try removing double buffering to see if it works
SwingUtilities.invokeLater(() -> {
window.canvas.render(window.canvas.getGraphics());
});
I don't even have it implemented at this point
This is the entire render method: ```java
public void render(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
renderSystem.update(g);
fontRenderSystem.update(g);
}
Oh wait
U can remove the argument if it's inside the same component, but that's unrelated
Yeah I figured
The flicker is weird, it shouldn't exist because you're drawing it directly
Is the project open source?
If it helps to know, the flicker mainly only occurs when I hold down the spacebar and spawn bullets
Uhhh not at the moment but I have a repo for it I can push to and open up for you if you wanna take a look
Even by holding space it shouldn't be causing it
Something has to be interfering
Did u override both paint and paintComponent?
If not, try doing it
And removing super from both
Also make sure u remove double buffering, just to be sure
frame.setDoubleBuffering(false) ig
oh I didn't override paint
flickering still continues even after overriding it
It's less noticeable though
So it might be something related then
Also getting CMEs since swing is rendering it on a different thread
It's because it's invoking the render method on a separate thread
And the render method talks to the ECS which is also being accessed from the game thread in the rest of the update function
It's basically the same problem I had with calling repaint()
Ig the CF method would be better then?
Idk, it's hard to properly see without the ide lul
For this engine I need the rendering to lag along with the update function
Kinda got used to having ctrl click
Basically if rendering takes a long time, I need the game loop to wait on it before it starts updating more stuff
which is why I initially thought about a mutex
Remove the runAsync
See if it solves the CFE thing
Aight, just finished reading that class
also don't worry about the input class atm
work in progress, figured I'd fix the renderer before moving on
Ik, I'm trying to understand the flow
if I get rid of the SwingUtilities thing, everything works like a charm from what I can see
Does it?
However something I'm noticing is that I can't seem to change the color of the background
Despite having ```java
public void render() {
getGraphics().setColor(Color.WHITE);
getGraphics().fillRect(0, 0, width, height);
renderSystem.update(getGraphics());
fontRenderSystem.update(getGraphics());
}
It's still rendering the background as black
is something rendering over it
apparently doing this solved it? But now I have issues with flickering again: ```java
public void render() {
Graphics g = getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
renderSystem.update(g);
fontRenderSystem.update(g);
}
this is making no sense lmao
Lmao
You know what, the internal graphics is probably changing at a difference pace because of swing modifying it on another thread
Ok so, I THINK each call of getGraphics() creates a fork of the current graphics context
so using the component's graphics might be a bad idea unless there's a solution to that
Which is why it ignored your setColor call
patch notes:
fix black
known bugs:
reintroduced bug from previous version
lmao
Did u do the doubleBuffered thing i mentioned before?
setting it to false? yeah, same issue
Try enabling it then
Same thing
Maybe something here helps
oh boy
from what I'm reading swing does this a lot and the main solution is double buffering
Eh
Btw, u could try instead of adding the panel, use setContentPane() to add the canvas
Just a theory, but it'll be treated as the body instead of another comp on the tree
Just did that, didn't have any effect
Got the pc, now I'll be able to properly read it
ok so, from what I noticed, holding space is calling the render
instead of just modifying the state
I think I might've solved it
nvm, it's just high fps
holding space just adds a gameobject to the scene
I'm pretty sure I solved it with BufferStrategy
I'm going to test then I'll commit what I did so you can see
gonna reduce the fps to 2 so I can see each step lul
lol
Alright so it seems to be working
Unfortunately this has much worse performance in terms of what I was getting before for just idle FPS, but MUCH better performance when resizing images down from 1300x1300 to 50x50
I'll create a new project so I can test a few stuff, be back in a couple mins
spending 53% of my execution time in some mysterious thread (the other one is my game loop) that I'm going to assume is swing
mind if I use the sprites?
not even my sprites in the first place, feel free to use whatever you want lol
got everything working properly (almost)!
I only have an npe but I can solve that in a bit
nice
no CMEs, no flickering, no lag until around 60 thousand bullets rendered on screen (I think I'll be fine in that department lol)
u held space for 1000 seconds?
nah I just increased the amount of bullets per spacebar to be 100 lol
ah ok
I'll commit to it rq so you can see what changes I made
There we go
I basically word-for-word copied the double buffering guide from oracle, so that helped a lot lol
I'll see in a moment
Thank you for all the help, that was infinitely useful, you have no idea
wish I could've helped better, made such a confusion lul
Nah I learned a lot from this
Plus your advice helped me debug a ton of stuff in the process anyways
Yeah it does I just couldnβt be bothered to figure out the calculation
someone help
i made diff folders in slash commands indicating diff commands nd now whenever i run the command it shows me output of other command
for eg if i run help command it shows ping command
if i run botinfo command,it shows ping command
and i dont find any erros in file or console
even the command is registered
any1 on?
make sure to double check that you're exporting and requiring your commands correctly in your main file, and that your command handler is properly identifying the command name and executing the correct function
i think everything is ok,still same issue
see this is the issue
can someone say where the problem could be?
const { SlashCommandBuilder } = require("@discordjs/builders");
const { MessageEmbed } = require("discord.js")
module.exports = {
data: new SlashCommandBuilder()
.setName('botinfo')
.setDescription('Shows Information About The Bot'),
async execute(client,interaction) {
let slashsheruinfo = new Discord.MessageEmbed()
.setTitle("BOT INFO")
.setDescription("Here Is All The Information About @versed wedge")
.addFields (
{
name: "General Info",
value: `
- Name : ${client.user.username}
- Developer: @north cairn
- Ping: ${client.ws.ping + "ms"}
`
},
{
name: "System Info",
value: `
- Language: JavaScript
- Id: ${client.user.id}
- Discord.js: v${require("discord.js").version}
`
}
)
.setThumbnail(client.user.displayAvatarURL({dynamic: true}))
.setFooter("Thank You For Using Sheru")
.setColor("PURPLE")
.setTimestamp()
await interaction.reply({embeds: [slashsheruinfo]})
}
}```
this my botinfo slash command
anything wrong here?
No
const {MessageEmbed, Collection } = require("discord.js");
const { readdirSync } = require("fs");
const Discord = require("discord.js")
const client = require("../../index")
const fetch = require("node-fetch");
const { QuickDB } = require("quick.db")
const db = new QuickDB();
client.on("interactionCreate", async interaction => {
const { commandName } = interaction;
if (!interaction.isCommand()) return;
const slashCommand =
client.slashCommands.get(interaction.commandName);
const slash = client.slashCommands.get(slashCommand)
try {
await slash.execute(client, interaction);
} catch(err) {
console.log(err)
await interaction.reply({content: "An Error Occured!", ephemeral: true})
}
})```
i think something wrong here
3
lol
ik its in interactionCreate thing
just cant find
pls say
acc to me the issue is in that slash.execute thing ig
pls say whats isue
I wonder how didn't it return null instead of repeating the same command
say the issue
did you write that code?





