@@ -42,6 +42,7 @@ use bevy_naga_reflect::dynamic_shader::DynamicShader;
4242
4343use bevy:: shader:: Shader as ShaderAsset ;
4444
45+ use crate :: config:: { Config , ConfigKey } ;
4546use crate :: error:: { ProcessingError , Result } ;
4647use crate :: material:: MaterialValue ;
4748use crate :: render:: material:: UntypedMaterial ;
@@ -140,6 +141,56 @@ pub fn create_shader(
140141 . id ( ) )
141142}
142143
144+ pub fn load_shader ( In ( path) : In < std:: path:: PathBuf > , world : & mut World ) -> Result < Entity > {
145+ use bevy:: asset:: {
146+ AssetPath , LoadState , handle_internal_asset_events,
147+ io:: { AssetSourceId , embedded:: GetAssetServer } ,
148+ } ;
149+ use bevy:: ecs:: system:: RunSystemOnce ;
150+
151+ let config = world. resource :: < Config > ( ) ;
152+ let asset_path: AssetPath = match config. get ( ConfigKey :: AssetRootPath ) {
153+ Some ( _) => {
154+ AssetPath :: from_path_buf ( path) . with_source ( AssetSourceId :: from ( "assets_directory" ) )
155+ }
156+ None => AssetPath :: from_path_buf ( path) ,
157+ } ;
158+
159+ let handle: Handle < ShaderAsset > = world. get_asset_server ( ) . load ( asset_path) ;
160+
161+ while let LoadState :: Loading = world. get_asset_server ( ) . load_state ( & handle) {
162+ world. run_system_once ( handle_internal_asset_events) . unwrap ( ) ;
163+ }
164+
165+ let source = {
166+ let shader_assets = world. resource :: < Assets < ShaderAsset > > ( ) ;
167+ let shader = shader_assets
168+ . get ( & handle)
169+ . ok_or ( ProcessingError :: ShaderNotFound ) ?;
170+ match & shader. source {
171+ bevy:: shader:: Source :: Wesl ( s) | bevy:: shader:: Source :: Wgsl ( s) => s. to_string ( ) ,
172+ _ => {
173+ return Err ( ProcessingError :: ShaderCompilationError (
174+ "Unsupported shader source format" . to_string ( ) ,
175+ ) ) ;
176+ }
177+ }
178+ } ;
179+
180+ let ( compiled_wgsl, module) = compile_shader ( & source) ?;
181+
182+ let shader_handle = world
183+ . resource_mut :: < Assets < ShaderAsset > > ( )
184+ . add ( ShaderAsset :: from_wgsl ( compiled_wgsl, "custom_material" ) ) ;
185+
186+ Ok ( world
187+ . spawn ( Shader {
188+ module,
189+ shader_handle,
190+ } )
191+ . id ( ) )
192+ }
193+
143194pub fn destroy_shader ( In ( entity) : In < Entity > , mut commands : Commands ) -> Result < ( ) > {
144195 commands. entity ( entity) . despawn ( ) ;
145196 Ok ( ( ) )
0 commit comments