Coverage Report

Created: 2025-07-18 07:08

/src/ogre/Components/RTShaderSystem/include/OgreShaderGenerator.h
Line
Count
Source (jump to first uncovered line)
1
/*
2
-----------------------------------------------------------------------------
3
This source file is part of OGRE
4
(Object-oriented Graphics Rendering Engine)
5
For the latest info, see http://www.ogre3d.org
6
7
Copyright (c) 2000-2014 Torus Knot Software Ltd
8
Permission is hereby granted, free of charge, to any person obtaining a copy
9
of this software and associated documentation files (the "Software"), to deal
10
in the Software without restriction, including without limitation the rights
11
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
copies of the Software, and to permit persons to whom the Software is
13
furnished to do so, subject to the following conditions:
14
15
The above copyright notice and this permission notice shall be included in
16
all copies or substantial portions of the Software.
17
18
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
THE SOFTWARE.
25
-----------------------------------------------------------------------------
26
*/
27
#ifndef _ShaderGenerator_
28
#define _ShaderGenerator_
29
30
#include "OgreShaderPrerequisites.h"
31
#include "OgreSingleton.h"
32
#include "OgreRenderObjectListener.h"
33
#include "OgreSceneManager.h"
34
#include "OgreShaderRenderState.h"
35
#include "OgreScriptTranslator.h"
36
#include "OgreShaderScriptTranslator.h"
37
#include "OgreMaterialSerializer.h"
38
39
40
namespace Ogre {
41
42
43
namespace RTShader {
44
45
/** \addtogroup Optional
46
*  @{
47
*/
48
/** \addtogroup RTShader
49
*  @{
50
*/
51
52
class SGRenderObjectListener;
53
class SGSceneManagerListener;
54
class SGScriptTranslatorManager;
55
class SGResourceGroupListener;
56
class SGMaterialSerializerListener;
57
class ProgramManager;
58
59
/** Shader generator system main interface. This singleton based class
60
enables automatic generation of shader code based on existing material techniques.
61
*/
62
class _OgreRTSSExport ShaderGenerator : public Singleton<ShaderGenerator>, public RTShaderSystemAlloc
63
{
64
// Interface.
65
public:
66
67
    /** 
68
    Initialize the Shader Generator System.
69
    Return true upon success.
70
    */
71
    static bool initialize();
72
73
    /** 
74
    Destroy the Shader Generator instance.
75
    */
76
    static void destroy();
77
78
79
    /** Override standard Singleton retrieval.
80
81
    Why do we do this? Well, it's because the Singleton
82
    implementation is in a .h file, which means it gets compiled
83
    into anybody who includes it. This is needed for the
84
    Singleton template to work, but we actually only want it
85
    compiled into the implementation of the class based on the
86
    Singleton, not all of them. If we don't change this, we get
87
    link errors when trying to use the Singleton-based class from
88
    an outside dll.
89
    @par
90
    This method just delegates to the template version anyway,
91
    but the implementation stays in this single compilation unit,
92
    preventing link errors.
93
    */
94
    static ShaderGenerator& getSingleton(); 
95
96
97
    /// @copydoc Singleton::getSingleton()
98
    static ShaderGenerator* getSingletonPtr();
99
100
    /** 
101
    Add a scene manager to the shader generator scene managers list.
102
    @param sceneMgr The scene manager to add to the list.
103
    */
104
    void addSceneManager(SceneManager* sceneMgr);
105
106
    /** 
107
    Remove a scene manager from the shader generator scene managers list.
108
    @param sceneMgr The scene manager to remove from the list.
109
    */
110
    void removeSceneManager(SceneManager* sceneMgr);
111
112
    /** 
113
    Get the active scene manager that is doint the actual scene rendering.
114
    This attribute will be update on the call to preFindVisibleObjects. 
115
    */
116
    SceneManager* getActiveSceneManager();
117
118
    /** 
119
    Set the active scene manager against which new render states are compiled.
120
    Note that normally the setting of the active scene manager is updated through the
121
    preFindVisibleObjects method.
122
    */
123
124
    void _setActiveSceneManager(SceneManager* sceneManager);
125
126
    /** 
127
    Set the target shader language.
128
    @param shaderLanguage The output shader language to use.
129
    @remarks The default shader language is cg.
130
    */
131
    void setTargetLanguage(const String& shaderLanguage);
132
133
    /** 
134
    Return the target shader language currently in use.     
135
    */
136
0
    const String& getTargetLanguage() const { return mShaderLanguage; }
137
138
    /** 
139
    Set the output shader target profiles.
140
    @param type shader type
141
    @param shaderProfiles The target profiles for the shader.
142
    */
143
    void setShaderProfiles(GpuProgramType type, const String& shaderProfiles);
144
145
    /** 
146
    Get the output shader target profiles.
147
    */
148
    const String& getShaderProfiles(GpuProgramType type) const;
149
150
    /** 
151
    Set the output shader cache path. Generated shader code will be written to this path.
152
    In case of empty cache path shaders will be generated directly from system memory.
153
    @param cachePath The cache path of the shader.  
154
    The default is empty cache path.
155
    */
156
    void setShaderCachePath(const String& cachePath);
157
158
    /** 
159
    Get the output shader cache path.
160
    */
161
0
    const String& getShaderCachePath() const { return mShaderCachePath; }
162
163
    /** 
164
    Flush the shader cache. This operation will cause all active schemes to be invalidated and will
165
    destroy any CPU/GPU program that created by this shader generator.
166
    */
167
    void flushShaderCache();
168
169
    /** 
170
    Return a global render state associated with the given scheme name.
171
    Modifying this render state will affect all techniques that belongs to that scheme.
172
    This is the best way to apply global changes to all techniques.
173
    After altering the render state one should call invalidateScheme method in order to 
174
    regenerate shaders.
175
    @param schemeName The destination scheme name.
176
    */
177
    RenderState* getRenderState(const String& schemeName);
178
179
180
    typedef std::pair<RenderState*, bool> RenderStateCreateOrRetrieveResult;
181
    /** 
182
    Returns a requested render state. If the render state does not exist this function creates it.
183
    @param schemeName The scheme name to retrieve.
184
    */
185
    RenderStateCreateOrRetrieveResult createOrRetrieveRenderState(const String& schemeName);
186
187
188
    /** 
189
    Tells if a given render state exists
190
    @param schemeName The scheme name to check.
191
    */
192
0
    bool hasRenderState(const String& schemeName) const { return getScheme(schemeName); }
193
    
194
    /**
195
     Get render state of specific pass.
196
     Using this method allows the user to customize the behavior of a specific pass.
197
     @param schemeName The destination scheme name.
198
     @param materialName The specific material name.
199
     @param groupName The specific material name.
200
     @param passIndex The pass index.
201
     */
202
    RenderState* getRenderState(const String& schemeName, const String& materialName, const String& groupName, unsigned short passIndex);
203
204
    /// @overload
205
    RenderState* getRenderState(const String& schemeName, const Material& mat, uint16 passIndex = 0)
206
0
    {
207
0
        return getRenderState(schemeName, mat.getName(), mat.getGroup(), passIndex);
208
0
    }
209
210
    /** 
211
    Add sub render state factory. Plugins or 3d party applications may implement sub classes of
212
    SubRenderState interface. Add the matching factory will allow the application to create instances 
213
    of these sub classes.
214
    @param factory The factory to add.
215
    */
216
    void addSubRenderStateFactory(SubRenderStateFactory* factory);
217
218
    /** 
219
    Returns the number of existing factories
220
    */
221
    size_t getNumSubRenderStateFactories() const;
222
223
    /** 
224
    Returns a sub render state factory by index
225
    @note index must be lower than the value returned by getNumSubRenderStateFactories()
226
    */
227
    SubRenderStateFactory* getSubRenderStateFactory(size_t index);
228
229
    /** 
230
    Returns a sub render state factory by name
231
    */
232
    SubRenderStateFactory* getSubRenderStateFactory(const String& type);
233
234
    /** 
235
    Remove sub render state factory. 
236
    @param factory The factory to remove.
237
    */
238
    void removeSubRenderStateFactory(SubRenderStateFactory* factory);
239
240
    /** 
241
    Create an instance of sub render state from a given type. 
242
    @param type The type of sub render state to create.
243
    */
244
    SubRenderState* createSubRenderState(const String& type);
245
246
    /// @overload
247
    template<typename T>
248
    T* createSubRenderState()
249
    {
250
        return static_cast<T*>(createSubRenderState(T::Type));
251
    }
252
253
    /** 
254
    Destroy an instance of sub render state. 
255
    @param subRenderState The instance to destroy.
256
    */
257
    void destroySubRenderState(SubRenderState* subRenderState);
258
259
    /**
260
     Checks if a shader based technique has been created for a given technique.
261
     Return true if exist. False if not.
262
     @param materialName The source material name.
263
     @param groupName The source group name.
264
     @param srcTechniqueSchemeName The source technique scheme name.
265
     @param dstTechniqueSchemeName The destination shader based technique scheme name.
266
     */
267
    bool hasShaderBasedTechnique(const String& materialName, const String& groupName, const String& srcTechniqueSchemeName, const String& dstTechniqueSchemeName) const;
268
269
    /// @overload
270
    bool hasShaderBasedTechnique(const Material& mat, const String& srcTechniqueSchemeName, const String& dstTechniqueSchemeName) const
271
0
    {
272
0
        return hasShaderBasedTechnique(mat.getName(), mat.getGroup(), srcTechniqueSchemeName, dstTechniqueSchemeName);
273
0
    }
274
275
    /**
276
    Create shader based technique from a given technique.
277
    Return true upon success. Failure may occur if the source technique is not FFP pure, or different
278
    source technique is mapped to the requested destination scheme.
279
    @param srcMat The source material.
280
    @param srcTechniqueSchemeName The source technique scheme name.
281
    @param dstTechniqueSchemeName The destination shader based technique scheme name.
282
    @param overProgrammable If true a shader will be created even if the pass already has shaders
283
    */
284
    bool createShaderBasedTechnique(const Material& srcMat, const String& srcTechniqueSchemeName, const String& dstTechniqueSchemeName, bool overProgrammable = false);
285
286
    /// @overload
287
    bool createShaderBasedTechnique(const Technique* srcTech, const String& dstTechniqueSchemeName, bool overProgrammable = false);
288
289
    /**
290
     Remove shader based technique from a given technique.
291
     Return true upon success. Failure may occur if the given source technique was not previously
292
     registered successfully using the createShaderBasedTechnique method.
293
     @param srcTech The source technique.
294
     @param dstTechniqueSchemeName The destination shader based technique scheme name.
295
     */
296
    bool removeShaderBasedTechnique(const Technique* srcTech, const String& dstTechniqueSchemeName);
297
298
    /** 
299
    Remove all shader based techniques of the given material. 
300
    Return true upon success.
301
    @param materialName The source material name.   
302
    @param groupName The source group name. 
303
    */
304
    bool removeAllShaderBasedTechniques(const String& materialName, const String& groupName OGRE_RESOURCE_GROUP_INIT);
305
306
    /// @overload
307
    bool removeAllShaderBasedTechniques(const Material& mat)
308
0
    {
309
0
        return removeAllShaderBasedTechniques(mat.getName(), mat.getGroup());
310
0
    }
311
312
    /** 
313
    Clone all shader based techniques from one material to another.
314
    This function can be used in conjunction with the Material::clone() function to copy 
315
    both material properties and RTSS state from one material to another.
316
    @param srcMat The source material
317
    @param dstMat The destination material
318
    @return True if successful
319
    */
320
    bool cloneShaderBasedTechniques(Material& srcMat, Material& dstMat);
321
322
    /** 
323
    Remove all shader based techniques that created by this shader generator.   
324
    */
325
    void removeAllShaderBasedTechniques();
326
327
    /** 
328
    Create a scheme.
329
    @param schemeName The scheme name to create.
330
    */
331
    void createScheme(const String& schemeName);
332
333
    /** 
334
    Invalidate a given scheme. This action will lead to shader regeneration of all techniques belongs to the
335
    given scheme name.
336
    @param schemeName The scheme to invalidate.
337
    */
338
    void invalidateScheme(const String& schemeName) const
339
0
    {
340
0
        if (auto scheme = getScheme(schemeName))
341
0
            scheme->invalidate();
342
0
    }
343
344
    /** 
345
    Validate a given scheme. This action will generate shader programs for all techniques of the
346
    given scheme name.
347
    @param schemeName The scheme to validate.
348
    */
349
    bool validateScheme(const String& schemeName) const;
350
    
351
    /** 
352
    Invalidate specific material scheme. This action will lead to shader regeneration of the technique belongs to the
353
    given scheme name.
354
    @param schemeName The scheme to invalidate.
355
    @param materialName The material to invalidate.
356
    @param groupName The source group name. 
357
    */
358
    void invalidateMaterial(const String& schemeName, const String& materialName,
359
                            const String& groupName OGRE_RESOURCE_GROUP_INIT) const
360
0
    {
361
0
        if (auto scheme = getScheme(schemeName))
362
0
            scheme->invalidate(materialName, groupName);
363
0
    }
364
365
    /// @overload
366
    void invalidateMaterial(const String& schemeName, const Material& mat)
367
0
    {
368
0
        invalidateMaterial(schemeName, mat.getName(), mat.getGroup());
369
0
    }
370
371
    /** 
372
    Validate specific material scheme. This action will generate shader programs for the technique of the
373
    given scheme name.
374
    @param schemeName The scheme to validate.
375
    @param materialName The material to validate.
376
    @param groupName The source group name. 
377
    */
378
    bool validateMaterial(const String& schemeName, const String& materialName, const String& groupName OGRE_RESOURCE_GROUP_INIT) const;
379
380
    /// @overload
381
    void validateMaterial(const String& schemeName, const Material& mat) const
382
0
    {
383
0
        validateMaterial(schemeName, mat.getName(), mat.getGroup());
384
0
    }
385
386
  /**
387
  Invalidate specific material scheme. This action will lead to shader regeneration of the technique belongs to the
388
  given scheme name.
389
  @param schemeName The scheme to invalidate.
390
  @param materialName The material to invalidate.
391
  @param groupName The source group name.
392
  */
393
    void invalidateMaterialIlluminationPasses(const String& schemeName, const String& materialName,
394
                                              const String& groupName OGRE_RESOURCE_GROUP_INIT) const
395
0
    {
396
0
        if (auto scheme = getScheme(schemeName))
397
0
            scheme->invalidateIlluminationPasses(materialName, groupName);
398
0
    }
399
400
        /**
401
  Validate specific material scheme. This action will generate shader programs illumination passes of the technique of the
402
  given scheme name.
403
  @param schemeName The scheme to validate.
404
  @param materialName The material to validate.
405
  @param groupName The source group name.
406
  */
407
    bool validateMaterialIlluminationPasses(const String& schemeName, const String& materialName,
408
                                            const String& groupName OGRE_RESOURCE_GROUP_INIT) const;
409
410
    /** 
411
    Return custom material Serializer of the shader generator.
412
    This is useful when you'd like to export certain material that contains shader generator effects.
413
    I.E - when writing an exporter you may want mark your material as shader generated material 
414
    so in the next time you will load it by your application it will automatically generate shaders with custom
415
    attributes you wanted. To do it you'll have to do the following steps:
416
    1. Create shader based technique for you material via the createShaderBasedTechnique() method.
417
    2. Create MaterialSerializer instance.
418
    3. Add the return instance of serializer listener to the MaterialSerializer.
419
    4. Call one of the export methods of MaterialSerializer.
420
    */
421
    MaterialSerializer::Listener* getMaterialSerializerListener();
422
423
    /** Return the current number of generated shaders. */
424
    size_t getShaderCount(GpuProgramType type) const;
425
426
    /** Set the vertex shader outputs compaction policy. 
427
    @see VSOutputCompactPolicy.
428
    @param policy The policy to set.
429
    */
430
0
    void setVertexShaderOutputsCompactPolicy(VSOutputCompactPolicy policy)  { mVSOutputCompactPolicy = policy; }
431
    
432
    /** Get the vertex shader outputs compaction policy. 
433
    @see VSOutputCompactPolicy. 
434
    */
435
0
    VSOutputCompactPolicy getVertexShaderOutputsCompactPolicy() const { return mVSOutputCompactPolicy; }
436
437
438
    /** Sets whether shaders are created for passes with shaders.
439
    Note that this only refers to when the system parses the materials itself.
440
    Not for when calling the createShaderBasedTechnique() function directly
441
    @param value The value to set this attribute pass.  
442
    */
443
0
    void setCreateShaderOverProgrammablePass(bool value) { mCreateShaderOverProgrammablePass = value; }
444
445
    /** Returns whether shaders are created for passes with shaders.
446
    @see setCreateShaderOverProgrammablePass(). 
447
    */
448
0
    bool getCreateShaderOverProgrammablePass() const { return mCreateShaderOverProgrammablePass; }
449
450
451
    /** Returns the amount of schemes used in the for RT shader generation
452
    */
453
    size_t getRTShaderSchemeCount() const;
454
455
    /** Returns the scheme name used in the for RT shader generation by index
456
    */
457
    const String& getRTShaderScheme(size_t index) const;
458
459
    /// mark the given texture unit as non-FFP
460
    static void _markNonFFP(const TextureUnitState* tu);
461
462
    /// same as @ref MSN_SHADERGEN
463
    static String DEFAULT_SCHEME_NAME;
464
private:
465
    class SGPass;
466
    class SGTechnique;
467
    class SGMaterial;
468
    class SGScheme;
469
470
    typedef std::pair<String,String>                MatGroupPair;
471
    struct MatGroupPair_less
472
    {
473
        // ensure we arrange the list first by material name then by group name
474
        bool operator()(const MatGroupPair& p1, const MatGroupPair& p2) const
475
0
        {
476
0
            int cmpVal = strcmp(p1.first.c_str(),p2.first.c_str());
477
0
            return (cmpVal < 0) || ((cmpVal == 0) && (strcmp(p1.second.c_str(),p2.second.c_str()) < 0));
478
0
        }
479
    };
480
481
    typedef std::vector<SGPass*>                   SGPassList;
482
    typedef SGPassList::iterator                        SGPassIterator;
483
    typedef SGPassList::const_iterator              SGPassConstIterator;
484
485
    typedef std::vector<SGTechnique*>              SGTechniqueList;
486
    typedef SGTechniqueList::iterator               SGTechniqueIterator;
487
    typedef SGTechniqueList::const_iterator         SGTechniqueConstIterator;
488
489
    typedef std::map<SGTechnique*, SGTechnique*>   SGTechniqueMap;
490
    typedef SGTechniqueMap::iterator                    SGTechniqueMapIterator;
491
    
492
    typedef std::map<MatGroupPair, SGMaterial*, MatGroupPair_less> SGMaterialMap;
493
    typedef SGMaterialMap::iterator                 SGMaterialIterator;
494
    typedef SGMaterialMap::const_iterator           SGMaterialConstIterator;
495
496
    typedef std::map<String, SGScheme*>                SGSchemeMap;
497
    typedef SGSchemeMap::iterator                   SGSchemeIterator;
498
    typedef SGSchemeMap::const_iterator             SGSchemeConstIterator;
499
500
    typedef std::map<uint32, ScriptTranslator*>        SGScriptTranslatorMap;
501
    typedef SGScriptTranslatorMap::iterator         SGScriptTranslatorIterator;
502
    typedef SGScriptTranslatorMap::const_iterator   SGScriptTranslatorConstIterator;
503
504
505
    
506
    /** Shader generator pass wrapper class. */
507
    class _OgreRTSSExport SGPass : public RTShaderSystemAlloc
508
    {
509
    public:
510
    SGPass(SGTechnique* parent, Pass* srcPass, Pass* dstPass, IlluminationStage stage);
511
        ~SGPass();
512
    
513
        /** Build the render state and acquire the CPU/GPU programs */
514
        void buildTargetRenderState();
515
516
        /** Get source pass. */
517
0
        Pass* getSrcPass() { return mSrcPass; }
518
519
        /** Get destination pass. */
520
0
        Pass* getDstPass() { return mDstPass; }
521
522
    /** Get illumination stage. */
523
0
    IlluminationStage getIlluminationStage() { return mStage; }
524
525
    /** Get illumination state. */
526
0
    bool isIlluminationPass() { return mStage != IS_UNKNOWN; }
527
528
        /** Get custom render state of this pass. */
529
0
        RenderState* getCustomRenderState() { return mCustomRenderState; }
530
531
        /** Set the custom render state of this pass. */
532
0
        void setCustomRenderState(RenderState* customRenderState) { mCustomRenderState = customRenderState; }
533
534
0
        const SGTechnique* getParent() const { return mParent; }
535
    protected:
536
        // Parent technique.
537
        SGTechnique* mParent;
538
        // Source pass.
539
        Pass* mSrcPass;
540
        // Destination pass.
541
        Pass* mDstPass;
542
    // Illumination stage
543
    IlluminationStage mStage;
544
        // Custom render state.
545
        RenderState* mCustomRenderState;
546
    };
547
548
    
549
    /** Shader generator technique wrapper class. */
550
    class _OgreRTSSExport SGTechnique : public RTShaderSystemAlloc
551
    {
552
    public:
553
        SGTechnique(SGMaterial* parent, const Technique* srcTechnique,
554
                    const String& dstTechniqueSchemeName, bool overProgrammable);
555
        ~SGTechnique();
556
        
557
        /** Get the parent SGMaterial */
558
0
        const SGMaterial* getParent() const { return mParent; }
559
        
560
        /** Get the source technique. */
561
0
        const Technique* getSourceTechnique() { return mSrcTechnique; }
562
563
        /** Get the destination technique. */
564
0
        Technique* getDestinationTechnique() { return mDstTechnique; }
565
566
        /** Get the destination technique scheme name. */
567
0
        const String& getDestinationTechniqueSchemeName() const { return mDstTechniqueSchemeName; }
568
        
569
        /** Build the render state. */
570
        void buildTargetRenderState();
571
572
    /** Build the render state for illumination passes. */
573
    void buildIlluminationTargetRenderState();
574
575
    /** Destroy the illumination passes entries. */
576
    void destroyIlluminationSGPasses();
577
578
        /** Release the CPU/GPU programs of this technique. */
579
        void releasePrograms();
580
581
        /** Tells the technique that it needs to generate shader code. */
582
0
        void setBuildDestinationTechnique(bool buildTechnique)  { mBuildDstTechnique = buildTechnique; }        
583
584
        /** Tells if the destination technique should be build. */
585
0
        bool getBuildDestinationTechnique() const               { return mBuildDstTechnique; }
586
587
        /** Get render state of specific pass.
588
        @param passIndex The pass index.
589
        */
590
        RenderState* getRenderState(unsigned short passIndex);
591
        /** Tells if a custom render state exists for the given pass. */
592
        bool hasRenderState(unsigned short passIndex);
593
594
        /// whether shaders are created for passes with shaders
595
0
        bool overProgrammablePass() { return mOverProgrammable; }
596
597
0
        const SGPassList& getPassList() const  { return mPassEntries; }
598
599
        // Key name for associating with a Technique instance.
600
        static String UserKey;
601
602
    protected:
603
        
604
        /** Create the passes entries. */
605
        void createSGPasses();
606
607
    /** Create the illumination passes entries. */
608
    void createIlluminationSGPasses();
609
610
        /** Destroy the passes entries. */
611
        void destroySGPasses();
612
        
613
    protected:
614
        // Auto mutex.
615
        OGRE_AUTO_MUTEX;
616
        // Parent material.     
617
        SGMaterial* mParent;
618
        // Source technique.
619
        const Technique* mSrcTechnique;
620
        // Destination technique.
621
        Technique* mDstTechnique;
622
    // All passes entries, both normal and illumination.
623
        SGPassList mPassEntries;
624
        // The custom render states of all passes.
625
        typedef std::vector<RenderState*> RenderStateList;
626
        RenderStateList mCustomRenderStates;
627
        // Flag that tells if destination technique should be build.        
628
        bool mBuildDstTechnique;
629
        // Scheme name of destination technique.
630
        String mDstTechniqueSchemeName;
631
        bool mOverProgrammable;
632
    };
633
634
    
635
    /** Shader generator material wrapper class. */
636
    class _OgreRTSSExport SGMaterial : public RTShaderSystemAlloc
637
    {   
638
    
639
    public:
640
        /** Class constructor. */
641
        SGMaterial(const String& materialName, const String& groupName) : mName(materialName), mGroup(groupName) 
642
0
        {}
643
644
        /** Get the material name. */
645
0
        const String& getMaterialName() const   { return mName; }
646
        
647
        /** Get the group name. */
648
0
        const String& getGroupName() const  { return mGroup; }
649
650
        /** Get the const techniques list of this material. */
651
0
        const SGTechniqueList& getTechniqueList() const  { return mTechniqueEntries; }
652
653
        /** Get the techniques list of this material. */
654
0
        SGTechniqueList& getTechniqueList()              { return mTechniqueEntries; }
655
    
656
    protected:
657
        // The material name.
658
        String mName;
659
        // The group name.
660
        String mGroup;
661
        // All passes entries.
662
        SGTechniqueList mTechniqueEntries;
663
    };
664
665
    
666
    /** Shader generator scheme class. */
667
    class _OgreRTSSExport SGScheme : public RTShaderSystemAlloc
668
    {   
669
    public:
670
        SGScheme(const String& schemeName);
671
        ~SGScheme();    
672
673
674
        /** Return true if this scheme dose not contains any techniques.
675
        */
676
0
        bool empty() const  { return mTechniqueEntries.empty(); }
677
        
678
        /** Invalidate the whole scheme.
679
        @see ShaderGenerator::invalidateScheme.
680
        */
681
        void invalidate();
682
683
        /** Validate the whole scheme.
684
        @see ShaderGenerator::validateScheme.
685
        */
686
        void validate();
687
688
        /** Invalidate specific material.
689
        @see ShaderGenerator::invalidateMaterial.
690
        */
691
        void invalidate(const String& materialName, const String& groupName);
692
693
        /** Validate specific material.
694
        @see ShaderGenerator::validateMaterial.
695
        */
696
        bool validate(const String& materialName, const String& groupName);
697
698
    /** Validate illumination passes of the specific material.
699
    @see ShaderGenerator::invalidateMaterialIlluminationPasses.
700
    */
701
        void invalidateIlluminationPasses(const String& materialName, const String& groupName);
702
703
    /** Validate illumination passes of the specific material.
704
    @see ShaderGenerator::validateMaterialIlluminationPasses.
705
    */
706
        bool validateIlluminationPasses(const String& materialName, const String& groupName);
707
708
        /** Add a technique to current techniques list. */
709
        void addTechniqueEntry(SGTechnique* techEntry);
710
711
        /** Remove a technique from the current techniques list. */
712
        void removeTechniqueEntry(SGTechnique* techEntry);
713
714
715
        /** Get global render state of this scheme. 
716
        @see ShaderGenerator::getRenderState.
717
        */
718
        RenderState* getRenderState();
719
720
        /** Get specific pass render state. 
721
        @see ShaderGenerator::getRenderState.
722
        */
723
        RenderState* getRenderState(const String& materialName, const String& groupName, unsigned short passIndex);
724
725
    protected:
726
        /** Synchronize the current light settings of this scheme with the current settings of the scene. */
727
        void synchronizeWithLightSettings();
728
729
        /** Synchronize the fog settings of this scheme with the current settings of the scene. */
730
        void synchronizeWithFogSettings();
731
732
733
    protected:
734
        // Scheme name.
735
        String mName;
736
        // Technique entries.
737
        SGTechniqueList mTechniqueEntries;
738
        // Tells if this scheme is out of date.
739
        bool mOutOfDate;
740
        // The global render state of this scheme.
741
        std::unique_ptr<RenderState> mRenderState;
742
        // Current fog mode.
743
        FogMode mFogMode;
744
    };
745
746
    //-----------------------------------------------------------------------------
747
    typedef std::map<String, SubRenderStateFactory*>       SubRenderStateFactoryMap;
748
    typedef SubRenderStateFactoryMap::iterator              SubRenderStateFactoryIterator;
749
    typedef SubRenderStateFactoryMap::const_iterator        SubRenderStateFactoryConstIterator;
750
751
    //-----------------------------------------------------------------------------
752
    typedef std::set<SceneManager*>                         SceneManagerMap;
753
    typedef SceneManagerMap::iterator                       SceneManagerIterator;
754
    typedef SceneManagerMap::const_iterator                 SceneManagerConstIterator;
755
756
    friend class SGRenderObjectListener;
757
    friend class SGSceneManagerListener;
758
759
    /** Class default constructor */
760
    ShaderGenerator();
761
762
    /** Class destructor */
763
    ~ShaderGenerator();
764
765
    /** Initialize the shader generator instance. */
766
    bool _initialize();
767
    
768
    /** Destory the shader generator instance. */
769
    void _destroy();
770
 
771
    /** Called from the sub class of the RenderObjectLister when single object is rendered. */
772
    void notifyRenderSingleObject(Renderable* rend, const Pass* pass,  const AutoParamDataSource* source, const LightList* pLightList, bool suppressRenderStateChanges);
773
774
    /** Called from the sub class of the SceneManager::Listener when finding visible object process starts. */
775
    void preFindVisibleObjects(SceneManager* source, SceneManager::IlluminationRenderStage irs, Viewport* v);
776
777
    /** Create sub render state core extensions factories */
778
    void createBuiltinSRSFactories();
779
780
    /** Destroy sub render state core extensions factories */
781
    void destroyBuiltinSRSFactories();
782
783
    SGScheme* getScheme(const String& name) const;
784
785
    /** Create an instance of the SubRenderState based on script properties using the
786
    current sub render state factories.
787
    @see SubRenderStateFactory::createInstance  
788
    @param compiler The compiler instance.
789
    @param prop The abstract property node.
790
    @param pass The pass that is the parent context of this node.
791
    @param translator The translator for the specific SubRenderState
792
    */
793
    SubRenderState* createSubRenderState(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator);
794
    
795
    /** Create an instance of the SubRenderState based on script properties using the
796
    current sub render state factories.
797
    @see SubRenderStateFactory::createInstance  
798
    @param compiler The compiler instance.
799
    @param prop The abstract property node.
800
    @param texState The texture unit state that is the parent context of this node.
801
    @param translator The translator for the specific SubRenderState
802
    */
803
    SubRenderState* createSubRenderState(ScriptCompiler* compiler, PropertyAbstractNode* prop, TextureUnitState* texState, SGScriptTranslator* translator);
804
805
    /** Return a matching script translator. */
806
    ScriptTranslator* getTranslator(const AbstractNodePtr& node);
807
808
    /** Finds an entry iterator in the mMaterialEntriesMap map.
809
    This function is able to find materials with group specified as 
810
    AUTODETECT_RESOURCE_GROUP_NAME 
811
    */
812
    SGMaterialIterator findMaterialEntryIt(const String& materialName, const String& groupName);
813
    SGMaterialConstIterator findMaterialEntryIt(const String& materialName, const String& groupName) const;
814
815
816
    typedef std::pair<SGScheme*, bool> SchemeCreateOrRetrieveResult;
817
    /** 
818
    Returns a requested scheme. If the scheme does not exist this function creates it.
819
    @param schemeName The scheme name to retrieve.
820
    */
821
    SchemeCreateOrRetrieveResult createOrRetrieveScheme(const String& schemeName);
822
823
    /** Used to check if finalizing */
824
    bool getIsFinalizing() const;
825
826
    /** Internal method that creates list of SGPass instances composing the given material. */
827
    SGPassList createSGPassList(Material* mat) const;
828
829
    // Auto mutex.
830
    OGRE_AUTO_MUTEX;
831
    // The active scene manager.
832
    SceneManager* mActiveSceneMgr;
833
    // A map of all scene managers this generator is bound to.
834
    SceneManagerMap mSceneManagerMap;
835
    // Render object listener.
836
    std::unique_ptr<SGRenderObjectListener> mRenderObjectListener;
837
    // Scene manager listener.
838
    std::unique_ptr<SGSceneManagerListener> mSceneManagerListener;
839
    // Script translator manager.
840
    std::unique_ptr<SGScriptTranslatorManager> mScriptTranslatorManager;
841
    // Custom material Serializer listener - allows exporting material that contains shader generated techniques.
842
    std::unique_ptr<SGMaterialSerializerListener> mMaterialSerializerListener;
843
    // get notified if materials get dropped
844
    std::unique_ptr<SGResourceGroupListener> mResourceGroupListener;
845
    // The core translator of the RT Shader System.
846
    SGScriptTranslator mCoreScriptTranslator;
847
    // The target shader language (currently only cg supported).
848
    String mShaderLanguage;
849
    // The target vertex shader profile. Will be used as argument for program compilation.
850
    String mVertexShaderProfiles;
851
    // The target fragment shader profile. Will be used as argument for program compilation.
852
    String mFragmentShaderProfiles;
853
    // Path for caching the generated shaders.
854
    String mShaderCachePath;
855
    // Shader program manager.
856
    std::unique_ptr<ProgramManager> mProgramManager;
857
    // Shader program writer manager.
858
    std::unique_ptr<ProgramWriterManager> mProgramWriterManager;
859
    // Material entries map.
860
    SGMaterialMap mMaterialEntriesMap;
861
    // Scheme entries map.
862
    SGSchemeMap mSchemeEntriesMap;
863
    // All technique entries map.
864
    SGTechniqueMap mTechniqueEntriesMap;
865
    // Sub render state registered factories.
866
    SubRenderStateFactoryMap mSubRenderStateFactories;
867
    // Sub render state core extension factories.
868
    std::vector<SubRenderStateFactory*> mBuiltinSRSFactories;
869
    // True if active view port use a valid SGScheme.
870
    bool mActiveViewportValid;
871
    // Light count per light type.
872
    int mLightCount[3];
873
    // Vertex shader outputs compact policy.
874
    VSOutputCompactPolicy mVSOutputCompactPolicy;
875
    // Tells whether shaders are created for passes with shaders
876
    bool mCreateShaderOverProgrammablePass;
877
    // A flag to indicate finalizing
878
    bool mIsFinalizing;
879
880
    uint32 ID_RT_SHADER_SYSTEM;
881
882
    friend class SGPass;
883
    friend class SGScriptTranslatorManager;
884
    friend class SGScriptTranslator;
885
    friend class SGMaterialSerializerListener;
886
    
887
};
888
889
/** @} */
890
/** @} */
891
892
}
893
}
894
895
#endif
896